aboutsummaryrefslogtreecommitdiffstats
path: root/java/src
diff options
context:
space:
mode:
Diffstat (limited to 'java/src')
-rw-r--r--java/src/com/android/inputmethod/accessibility/AccessibilityEntityProvider.java134
-rw-r--r--java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java64
-rw-r--r--java/src/com/android/inputmethod/accessibility/AccessibleKeyboardViewProxy.java163
-rw-r--r--java/src/com/android/inputmethod/accessibility/KeyCodeDescriptionMapper.java82
-rw-r--r--java/src/com/android/inputmethod/annotations/ExternallyReferenced.java24
-rw-r--r--java/src/com/android/inputmethod/annotations/UsedForTesting.java24
-rw-r--r--java/src/com/android/inputmethod/compat/AudioManagerCompatWrapper.java54
-rw-r--r--java/src/com/android/inputmethod/compat/CompatUtils.java49
-rw-r--r--java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java16
-rw-r--r--java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java54
-rw-r--r--java/src/com/android/inputmethod/compat/InputMethodServiceCompatUtils.java7
-rw-r--r--java/src/com/android/inputmethod/compat/IntentCompatUtils.java36
-rw-r--r--java/src/com/android/inputmethod/compat/SettingsSecureCompatUtils.java4
-rw-r--r--java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java102
-rw-r--r--java/src/com/android/inputmethod/compat/SuggestionsInfoCompatUtils.java11
-rw-r--r--java/src/com/android/inputmethod/compat/TextViewCompatUtils.java44
-rw-r--r--java/src/com/android/inputmethod/compat/ViewCompatUtils.java68
-rw-r--r--java/src/com/android/inputmethod/event/Combiner.java29
-rw-r--r--java/src/com/android/inputmethod/event/DeadKeyCombiner.java61
-rw-r--r--java/src/com/android/inputmethod/event/Event.java93
-rw-r--r--java/src/com/android/inputmethod/event/EventDecoder.java24
-rw-r--r--java/src/com/android/inputmethod/event/EventDecoderSpec.java26
-rw-r--r--java/src/com/android/inputmethod/event/EventInterpreter.java133
-rw-r--r--java/src/com/android/inputmethod/event/HardwareEventDecoder.java26
-rw-r--r--java/src/com/android/inputmethod/event/HardwareKeyboardEventDecoder.java74
-rw-r--r--java/src/com/android/inputmethod/event/SoftwareEventDecoder.java29
-rw-r--r--java/src/com/android/inputmethod/event/SoftwareKeyboardEventDecoder.java27
-rw-r--r--java/src/com/android/inputmethod/keyboard/Key.java88
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyDetector.java20
-rw-r--r--java/src/com/android/inputmethod/keyboard/Keyboard.java99
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java36
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardId.java114
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java87
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java89
-rw-r--r--java/src/com/android/inputmethod/keyboard/KeyboardView.java385
-rw-r--r--java/src/com/android/inputmethod/keyboard/MainKeyboardView.java923
-rw-r--r--java/src/com/android/inputmethod/keyboard/MoreKeysKeyboard.java36
-rw-r--r--java/src/com/android/inputmethod/keyboard/MoreKeysKeyboardView.java235
-rw-r--r--java/src/com/android/inputmethod/keyboard/MoreKeysPanel.java86
-rw-r--r--java/src/com/android/inputmethod/keyboard/PointerTracker.java623
-rw-r--r--java/src/com/android/inputmethod/keyboard/ProximityInfo.java175
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java67
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/AlphabetShiftState.java16
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java176
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/GesturePreviewTrail.java217
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java80
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java26
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java201
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeySpecParser.java80
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyStyle.java21
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyStylesSet.java16
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardBuilder.java118
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardCodesSet.java54
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardIconsSet.java16
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardParams.java24
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardRow.java42
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java103
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeyboardTextsSet.java704
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/KeysCache.java16
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/ModifierKeyState.java16
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java26
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/PointerTrackerQueue.java26
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java318
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/RoundedLine.java112
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/ShiftKeyState.java16
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/SlidingKeyInputPreview.java90
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/TouchPositionCorrection.java19
-rw-r--r--java/src/com/android/inputmethod/keyboard/internal/TouchScreenRegulator.java (renamed from java/src/com/android/inputmethod/keyboard/internal/SuddenJumpingTouchEventHandler.java)38
-rw-r--r--java/src/com/android/inputmethod/latin/AdditionalSubtype.java18
-rw-r--r--java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java69
-rw-r--r--java/src/com/android/inputmethod/latin/AssetFileAddress.java25
-rw-r--r--java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java95
-rw-r--r--java/src/com/android/inputmethod/latin/AutoCorrection.java23
-rw-r--r--java/src/com/android/inputmethod/latin/BackupAgent.java23
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionary.java134
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java272
-rw-r--r--java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java210
-rw-r--r--java/src/com/android/inputmethod/latin/BoundedTreeSet.java16
-rw-r--r--java/src/com/android/inputmethod/latin/CapsModeUtils.java266
-rw-r--r--java/src/com/android/inputmethod/latin/CollectionUtils.java5
-rw-r--r--java/src/com/android/inputmethod/latin/Constants.java98
-rw-r--r--java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java35
-rw-r--r--java/src/com/android/inputmethod/latin/CoordinateUtils.java49
-rw-r--r--java/src/com/android/inputmethod/latin/DebugSettings.java68
-rw-r--r--java/src/com/android/inputmethod/latin/DebugSettingsActivity.java16
-rw-r--r--java/src/com/android/inputmethod/latin/DicTraverseSession.java6
-rw-r--r--java/src/com/android/inputmethod/latin/Dictionary.java31
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryCollection.java26
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryFactory.java81
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryInfoUtils.java355
-rw-r--r--java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java16
-rw-r--r--java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java44
-rw-r--r--java/src/com/android/inputmethod/latin/ExpandableDictionary.java97
-rw-r--r--java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java163
-rw-r--r--java/src/com/android/inputmethod/latin/FileTransforms.java16
-rw-r--r--java/src/com/android/inputmethod/latin/ImfUtils.java186
-rw-r--r--java/src/com/android/inputmethod/latin/InputAttributes.java96
-rw-r--r--java/src/com/android/inputmethod/latin/InputPointers.java46
-rw-r--r--java/src/com/android/inputmethod/latin/InputTypeUtils.java29
-rw-r--r--java/src/com/android/inputmethod/latin/InputView.java16
-rw-r--r--java/src/com/android/inputmethod/latin/IntentUtils.java45
-rw-r--r--java/src/com/android/inputmethod/latin/LastComposedWord.java30
-rw-r--r--java/src/com/android/inputmethod/latin/LatinIME.java959
-rw-r--r--java/src/com/android/inputmethod/latin/LatinImeLogger.java2
-rw-r--r--java/src/com/android/inputmethod/latin/LocaleUtils.java21
-rw-r--r--java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java32
-rw-r--r--java/src/com/android/inputmethod/latin/ResizableIntArray.java16
-rw-r--r--java/src/com/android/inputmethod/latin/ResourceUtils.java56
-rw-r--r--java/src/com/android/inputmethod/latin/RichInputConnection.java186
-rw-r--r--java/src/com/android/inputmethod/latin/RichInputMethodManager.java250
-rw-r--r--java/src/com/android/inputmethod/latin/SeekBarDialogPreference.java147
-rw-r--r--java/src/com/android/inputmethod/latin/Settings.java548
-rw-r--r--java/src/com/android/inputmethod/latin/SettingsActivity.java18
-rw-r--r--java/src/com/android/inputmethod/latin/SettingsFragment.java363
-rw-r--r--java/src/com/android/inputmethod/latin/SettingsValues.java417
-rw-r--r--java/src/com/android/inputmethod/latin/StringUtils.java340
-rw-r--r--java/src/com/android/inputmethod/latin/SubtypeLocale.java156
-rw-r--r--java/src/com/android/inputmethod/latin/SubtypeSwitcher.java109
-rw-r--r--java/src/com/android/inputmethod/latin/Suggest.java74
-rw-r--r--java/src/com/android/inputmethod/latin/SuggestedWords.java51
-rw-r--r--java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java9
-rw-r--r--java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java4
-rw-r--r--java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java4
-rw-r--r--java/src/com/android/inputmethod/latin/TargetApplicationGetter.java16
-rw-r--r--java/src/com/android/inputmethod/latin/UserBinaryDictionary.java51
-rw-r--r--java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java38
-rw-r--r--java/src/com/android/inputmethod/latin/UserHistoryDictionary.java69
-rw-r--r--java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java3
-rw-r--r--java/src/com/android/inputmethod/latin/Utils.java19
-rw-r--r--java/src/com/android/inputmethod/latin/VibratorUtils.java50
-rw-r--r--java/src/com/android/inputmethod/latin/WordComposer.java64
-rw-r--r--java/src/com/android/inputmethod/latin/WordListInfo.java18
-rw-r--r--java/src/com/android/inputmethod/latin/XmlParseUtils.java16
-rw-r--r--java/src/com/android/inputmethod/latin/define/JniLibName.java16
-rw-r--r--java/src/com/android/inputmethod/latin/define/ProductionFlag.java23
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java786
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java224
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/CharGroupInfo.java16
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/FormatSpec.java62
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java96
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/MakedictLog.java16
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/PendingAttribute.java16
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/UnsupportedFormatException.java16
-rw-r--r--java/src/com/android/inputmethod/latin/makedict/Word.java16
-rw-r--r--java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java122
-rw-r--r--java/src/com/android/inputmethod/latin/setup/SetupActivity.java357
-rw-r--r--java/src/com/android/inputmethod/latin/setup/SetupStepIndicatorView.java56
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java64
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java16
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSessionFactory.java16
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java72
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/DictAndProximity.java16
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java20
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerProximityInfo.java285
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsActivity.java18
-rw-r--r--java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java18
-rw-r--r--java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java27
-rw-r--r--java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java193
-rw-r--r--java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java274
-rw-r--r--java/src/com/android/inputmethod/research/BootBroadcastReceiver.java16
-rw-r--r--java/src/com/android/inputmethod/research/FeedbackActivity.java31
-rw-r--r--java/src/com/android/inputmethod/research/FeedbackFragment.java152
-rw-r--r--java/src/com/android/inputmethod/research/FeedbackLayout.java16
-rw-r--r--java/src/com/android/inputmethod/research/FixedLogBuffer.java162
-rw-r--r--java/src/com/android/inputmethod/research/JsonUtils.java157
-rw-r--r--java/src/com/android/inputmethod/research/LogBuffer.java120
-rw-r--r--java/src/com/android/inputmethod/research/LogStatement.java224
-rw-r--r--java/src/com/android/inputmethod/research/LogUnit.java456
-rw-r--r--java/src/com/android/inputmethod/research/LoggingUtils.java38
-rw-r--r--java/src/com/android/inputmethod/research/MainLogBuffer.java219
-rw-r--r--java/src/com/android/inputmethod/research/MotionEventReader.java332
-rw-r--r--java/src/com/android/inputmethod/research/Replayer.java149
-rw-r--r--java/src/com/android/inputmethod/research/ReplayerService.java65
-rw-r--r--java/src/com/android/inputmethod/research/ResearchLog.java178
-rw-r--r--java/src/com/android/inputmethod/research/ResearchLogger.java1761
-rw-r--r--java/src/com/android/inputmethod/research/Statistics.java140
-rw-r--r--java/src/com/android/inputmethod/research/UploaderService.java39
177 files changed, 13748 insertions, 7251 deletions
diff --git a/java/src/com/android/inputmethod/accessibility/AccessibilityEntityProvider.java b/java/src/com/android/inputmethod/accessibility/AccessibilityEntityProvider.java
index b9b6362fc..0576f666c 100644
--- a/java/src/com/android/inputmethod/accessibility/AccessibilityEntityProvider.java
+++ b/java/src/com/android/inputmethod/accessibility/AccessibilityEntityProvider.java
@@ -36,6 +36,7 @@ import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.CoordinateUtils;
/**
* Exposes a virtual view sub-tree for {@link KeyboardView} and generates
@@ -62,7 +63,7 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
private final Rect mTempBoundsInScreen = new Rect();
/** The parent view's cached on-screen location. */
- private final int[] mParentLocation = new int[2];
+ private final int[] mParentLocation = CoordinateUtils.newInstance();
/** The virtual view identifier for the focused node. */
private int mAccessibilityFocusedView = UNDEFINED;
@@ -70,12 +71,11 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
/** The current keyboard view. */
private KeyboardView mKeyboardView;
- public AccessibilityEntityProvider(KeyboardView keyboardView, InputMethodService inputMethod) {
+ public AccessibilityEntityProvider(final KeyboardView keyboardView,
+ final InputMethodService inputMethod) {
mInputMethodService = inputMethod;
-
mKeyCodeDescriptionMapper = KeyCodeDescriptionMapper.getInstance();
mAccessibilityUtils = AccessibilityUtils.getInstance();
-
setView(keyboardView);
}
@@ -84,21 +84,19 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
*
* @param keyboardView The keyboard view to represent.
*/
- public void setView(KeyboardView keyboardView) {
+ public void setView(final KeyboardView keyboardView) {
mKeyboardView = keyboardView;
updateParentLocation();
// Since this class is constructed lazily, we might not get a subsequent
// call to setKeyboard() and therefore need to call it now.
- setKeyboard(mKeyboardView.getKeyboard());
+ setKeyboard();
}
/**
* Sets the keyboard represented by this node provider.
- *
- * @param keyboard The keyboard to represent.
*/
- public void setKeyboard(Keyboard keyboard) {
+ public void setKeyboard() {
assignVirtualViewIds();
}
@@ -111,19 +109,16 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
* @return A populated {@link AccessibilityEvent} for the key.
* @see AccessibilityEvent
*/
- public AccessibilityEvent createAccessibilityEvent(Key key, int eventType) {
+ public AccessibilityEvent createAccessibilityEvent(final Key key, final int eventType) {
final int virtualViewId = generateVirtualViewIdForKey(key);
final String keyDescription = getKeyDescription(key);
-
final AccessibilityEvent event = AccessibilityEvent.obtain(eventType);
event.setPackageName(mKeyboardView.getContext().getPackageName());
event.setClassName(key.getClass().getName());
event.setContentDescription(keyDescription);
event.setEnabled(true);
-
final AccessibilityRecordCompat record = new AccessibilityRecordCompat(event);
record.setSource(mKeyboardView, virtualViewId);
-
return event;
}
@@ -144,67 +139,65 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
* </p>
*
* @param virtualViewId A client defined virtual view id.
- * @return A populated {@link AccessibilityNodeInfoCompat} for a virtual
- * descendant or the host View.
+ * @return A populated {@link AccessibilityNodeInfoCompat} for a virtual descendant or the host
+ * View.
* @see AccessibilityNodeInfoCompat
*/
@Override
- public AccessibilityNodeInfoCompat createAccessibilityNodeInfo(int virtualViewId) {
- AccessibilityNodeInfoCompat info = null;
-
+ public AccessibilityNodeInfoCompat createAccessibilityNodeInfo(final int virtualViewId) {
if (virtualViewId == UNDEFINED) {
return null;
- } else if (virtualViewId == View.NO_ID) {
+ }
+ if (virtualViewId == View.NO_ID) {
// We are requested to create an AccessibilityNodeInfo describing
// this View, i.e. the root of the virtual sub-tree.
- info = AccessibilityNodeInfoCompat.obtain(mKeyboardView);
- ViewCompat.onInitializeAccessibilityNodeInfo(mKeyboardView, info);
+ final AccessibilityNodeInfoCompat rootInfo =
+ AccessibilityNodeInfoCompat.obtain(mKeyboardView);
+ ViewCompat.onInitializeAccessibilityNodeInfo(mKeyboardView, rootInfo);
// Add the virtual children of the root View.
final Keyboard keyboard = mKeyboardView.getKeyboard();
final Key[] keys = keyboard.mKeys;
for (Key key : keys) {
final int childVirtualViewId = generateVirtualViewIdForKey(key);
- info.addChild(mKeyboardView, childVirtualViewId);
- }
- } else {
- // Find the view that corresponds to the given id.
- final Key key = mVirtualViewIdToKey.get(virtualViewId);
- if (key == null) {
- Log.e(TAG, "Invalid virtual view ID: " + virtualViewId);
- return null;
- }
-
- final String keyDescription = getKeyDescription(key);
- final Rect boundsInParent = key.mHitBox;
-
- // Calculate the key's in-screen bounds.
- mTempBoundsInScreen.set(boundsInParent);
- mTempBoundsInScreen.offset(mParentLocation[0], mParentLocation[1]);
-
- final Rect boundsInScreen = mTempBoundsInScreen;
-
- // Obtain and initialize an AccessibilityNodeInfo with
- // information about the virtual view.
- info = AccessibilityNodeInfoCompat.obtain();
- info.setPackageName(mKeyboardView.getContext().getPackageName());
- info.setClassName(key.getClass().getName());
- info.setContentDescription(keyDescription);
- info.setBoundsInParent(boundsInParent);
- info.setBoundsInScreen(boundsInScreen);
- info.setParent(mKeyboardView);
- info.setSource(mKeyboardView, virtualViewId);
- info.setBoundsInScreen(boundsInScreen);
- info.setEnabled(true);
- info.setVisibleToUser(true);
-
- if (mAccessibilityFocusedView == virtualViewId) {
- info.addAction(AccessibilityNodeInfoCompat.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
- } else {
- info.addAction(AccessibilityNodeInfoCompat.ACTION_ACCESSIBILITY_FOCUS);
+ rootInfo.addChild(mKeyboardView, childVirtualViewId);
}
+ return rootInfo;
}
+ // Find the view that corresponds to the given id.
+ final Key key = mVirtualViewIdToKey.get(virtualViewId);
+ if (key == null) {
+ Log.e(TAG, "Invalid virtual view ID: " + virtualViewId);
+ return null;
+ }
+ final String keyDescription = getKeyDescription(key);
+ final Rect boundsInParent = key.mHitBox;
+
+ // Calculate the key's in-screen bounds.
+ mTempBoundsInScreen.set(boundsInParent);
+ mTempBoundsInScreen.offset(
+ CoordinateUtils.x(mParentLocation), CoordinateUtils.y(mParentLocation));
+ final Rect boundsInScreen = mTempBoundsInScreen;
+
+ // Obtain and initialize an AccessibilityNodeInfo with information about the virtual view.
+ final AccessibilityNodeInfoCompat info = AccessibilityNodeInfoCompat.obtain();
+ info.setPackageName(mKeyboardView.getContext().getPackageName());
+ info.setClassName(key.getClass().getName());
+ info.setContentDescription(keyDescription);
+ info.setBoundsInParent(boundsInParent);
+ info.setBoundsInScreen(boundsInScreen);
+ info.setParent(mKeyboardView);
+ info.setSource(mKeyboardView, virtualViewId);
+ info.setBoundsInScreen(boundsInScreen);
+ info.setEnabled(true);
+ info.setVisibleToUser(true);
+
+ if (mAccessibilityFocusedView == virtualViewId) {
+ info.addAction(AccessibilityNodeInfoCompat.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
+ } else {
+ info.addAction(AccessibilityNodeInfoCompat.ACTION_ACCESSIBILITY_FOCUS);
+ }
return info;
}
@@ -214,7 +207,7 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
*
* @param key The key to press.
*/
- void simulateKeyPress(Key key) {
+ void simulateKeyPress(final Key key) {
final int x = key.mHitBox.centerX();
final int y = key.mHitBox.centerY();
final long downTime = SystemClock.uptimeMillis();
@@ -225,19 +218,17 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
mKeyboardView.onTouchEvent(downEvent);
mKeyboardView.onTouchEvent(upEvent);
-
downEvent.recycle();
upEvent.recycle();
}
@Override
- public boolean performAction(int virtualViewId, int action, Bundle arguments) {
+ public boolean performAction(final int virtualViewId, final int action,
+ final Bundle arguments) {
final Key key = mVirtualViewIdToKey.get(virtualViewId);
-
if (key == null) {
return false;
}
-
return performActionForKey(key, action, arguments);
}
@@ -247,10 +238,9 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
* @param key The on which to perform the action.
* @param action The action to perform.
* @param arguments The action's arguments.
- * @return The result of performing the action, or false if the action is
- * not supported.
+ * @return The result of performing the action, or false if the action is not supported.
*/
- boolean performActionForKey(Key key, int action, Bundle arguments) {
+ boolean performActionForKey(final Key key, final int action, final Bundle arguments) {
final int virtualViewId = generateVirtualViewIdForKey(key);
switch (action) {
@@ -270,9 +260,9 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
sendAccessibilityEventForKey(
key, AccessibilityEventCompat.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
return true;
+ default:
+ return false;
}
-
- return false;
}
/**
@@ -281,7 +271,7 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
* @param key The key that's sending the event.
* @param eventType The type of event to send.
*/
- void sendAccessibilityEventForKey(Key key, int eventType) {
+ void sendAccessibilityEventForKey(final Key key, final int eventType) {
final AccessibilityEvent event = createAccessibilityEvent(key, eventType);
mAccessibilityUtils.requestSendAccessibilityEvent(event);
}
@@ -292,12 +282,11 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
* @param key The key to describe.
* @return The context-specific description of the key.
*/
- private String getKeyDescription(Key key) {
+ private String getKeyDescription(final Key key) {
final EditorInfo editorInfo = mInputMethodService.getCurrentInputEditorInfo();
final boolean shouldObscure = mAccessibilityUtils.shouldObscureInput(editorInfo);
final String keyDescription = mKeyCodeDescriptionMapper.getDescriptionForKey(
mKeyboardView.getContext(), mKeyboardView.getKeyboard(), key, shouldObscure);
-
return keyDescription;
}
@@ -309,7 +298,6 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
if (keyboard == null) {
return;
}
-
mVirtualViewIdToKey.clear();
final Key[] keys = keyboard.mKeys;
@@ -333,7 +321,7 @@ public final class AccessibilityEntityProvider extends AccessibilityNodeProvider
* @param key The key to identify.
* @return A virtual view identifier.
*/
- private static int generateVirtualViewIdForKey(Key key) {
+ private static int generateVirtualViewIdForKey(final Key key) {
// The key x- and y-coordinates are stable between layout changes.
// Generate an identifier by bit-shifting the x-coordinate to the
// left-half of the integer and OR'ing with the y-coordinate.
diff --git a/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java b/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java
index 1eee1df87..ee52de1d1 100644
--- a/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java
+++ b/java/src/com/android/inputmethod/accessibility/AccessibilityUtils.java
@@ -32,7 +32,6 @@ import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.EditorInfo;
-import com.android.inputmethod.compat.AudioManagerCompatWrapper;
import com.android.inputmethod.compat.SettingsSecureCompatUtils;
import com.android.inputmethod.latin.InputTypeUtils;
import com.android.inputmethod.latin.R;
@@ -40,14 +39,14 @@ import com.android.inputmethod.latin.R;
public final class AccessibilityUtils {
private static final String TAG = AccessibilityUtils.class.getSimpleName();
private static final String CLASS = AccessibilityUtils.class.getClass().getName();
- private static final String PACKAGE = AccessibilityUtils.class.getClass().getPackage()
- .getName();
+ private static final String PACKAGE =
+ AccessibilityUtils.class.getClass().getPackage().getName();
private static final AccessibilityUtils sInstance = new AccessibilityUtils();
private Context mContext;
private AccessibilityManager mAccessibilityManager;
- private AudioManagerCompatWrapper mAudioManager;
+ private AudioManager mAudioManager;
/*
* Setting this constant to {@code false} will disable all keyboard
@@ -56,9 +55,8 @@ public final class AccessibilityUtils {
*/
private static final boolean ENABLE_ACCESSIBILITY = true;
- public static void init(InputMethodService inputMethod) {
- if (!ENABLE_ACCESSIBILITY)
- return;
+ public static void init(final InputMethodService inputMethod) {
+ if (!ENABLE_ACCESSIBILITY) return;
// These only need to be initialized if the kill switch is off.
sInstance.initInternal(inputMethod);
@@ -74,27 +72,32 @@ public final class AccessibilityUtils {
// This class is not publicly instantiable.
}
- private void initInternal(Context context) {
+ private void initInternal(final Context context) {
mContext = context;
- mAccessibilityManager = (AccessibilityManager) context
- .getSystemService(Context.ACCESSIBILITY_SERVICE);
+ mAccessibilityManager =
+ (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
+ mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
+ }
- final AudioManager audioManager = (AudioManager) context
- .getSystemService(Context.AUDIO_SERVICE);
- mAudioManager = new AudioManagerCompatWrapper(audioManager);
+ /**
+ * Returns {@code true} if accessibility is enabled. Currently, this means
+ * that the kill switch is off and system accessibility is turned on.
+ *
+ * @return {@code true} if accessibility is enabled.
+ */
+ public boolean isAccessibilityEnabled() {
+ return ENABLE_ACCESSIBILITY && mAccessibilityManager.isEnabled();
}
/**
* Returns {@code true} if touch exploration is enabled. Currently, this
* means that the kill switch is off, the device supports touch exploration,
- * and a spoken feedback service is turned on.
+ * and system accessibility is turned on.
*
* @return {@code true} if touch exploration is enabled.
*/
public boolean isTouchExplorationEnabled() {
- return ENABLE_ACCESSIBILITY
- && mAccessibilityManager.isEnabled()
- && mAccessibilityManager.isTouchExplorationEnabled();
+ return isAccessibilityEnabled() && mAccessibilityManager.isTouchExplorationEnabled();
}
/**
@@ -105,9 +108,8 @@ public final class AccessibilityUtils {
* @param event The event to check.
* @return {@true} is the event is a touch exploration event
*/
- public boolean isTouchExplorationEvent(MotionEvent event) {
+ public boolean isTouchExplorationEvent(final MotionEvent event) {
final int action = event.getAction();
-
return action == MotionEvent.ACTION_HOVER_ENTER
|| action == MotionEvent.ACTION_HOVER_EXIT
|| action == MotionEvent.ACTION_HOVER_MOVE;
@@ -119,21 +121,21 @@ public final class AccessibilityUtils {
*
* @return {@code true} if the device should obscure password characters.
*/
- public boolean shouldObscureInput(EditorInfo editorInfo) {
- if (editorInfo == null)
- return false;
+ @SuppressWarnings("deprecation")
+ public boolean shouldObscureInput(final EditorInfo editorInfo) {
+ if (editorInfo == null) return false;
// The user can optionally force speaking passwords.
if (SettingsSecureCompatUtils.ACCESSIBILITY_SPEAK_PASSWORD != null) {
final boolean speakPassword = Settings.Secure.getInt(mContext.getContentResolver(),
SettingsSecureCompatUtils.ACCESSIBILITY_SPEAK_PASSWORD, 0) != 0;
- if (speakPassword)
- return false;
+ if (speakPassword) return false;
}
// Always speak if the user is listening through headphones.
- if (mAudioManager.isWiredHeadsetOn() || mAudioManager.isBluetoothA2dpOn())
+ if (mAudioManager.isWiredHeadsetOn() || mAudioManager.isBluetoothA2dpOn()) {
return false;
+ }
// Don't speak if the IME is connected to a password field.
return InputTypeUtils.isPasswordInputType(editorInfo.inputType);
@@ -146,7 +148,7 @@ public final class AccessibilityUtils {
* @param view The source view.
* @param text The text to speak.
*/
- public void announceForAccessibility(View view, CharSequence text) {
+ public void announceForAccessibility(final View view, final CharSequence text) {
if (!mAccessibilityManager.isEnabled()) {
Log.e(TAG, "Attempted to speak when accessibility was disabled!");
return;
@@ -163,8 +165,9 @@ public final class AccessibilityUtils {
event.setEnabled(true);
event.getText().add(text);
- // Platforms starting at SDK 16 should use announce events.
- if (Build.VERSION.SDK_INT >= 16) {
+ // Platforms starting at SDK version 16 (Build.VERSION_CODES.JELLY_BEAN) should use
+ // announce events.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
event.setEventType(AccessibilityEventCompat.TYPE_ANNOUNCEMENT);
} else {
event.setEventType(AccessibilityEvent.TYPE_VIEW_FOCUSED);
@@ -187,7 +190,8 @@ public final class AccessibilityUtils {
* @param editorInfo The input connection's editor info attribute.
* @param restarting Whether the connection is being restarted.
*/
- public void onStartInputViewInternal(View view, EditorInfo editorInfo, boolean restarting) {
+ public void onStartInputViewInternal(final View view, final EditorInfo editorInfo,
+ final boolean restarting) {
if (shouldObscureInput(editorInfo)) {
final CharSequence text = mContext.getText(R.string.spoken_use_headphones);
announceForAccessibility(view, text);
@@ -200,7 +204,7 @@ public final class AccessibilityUtils {
*
* @param event The event to send.
*/
- public void requestSendAccessibilityEvent(AccessibilityEvent event) {
+ public void requestSendAccessibilityEvent(final AccessibilityEvent event) {
if (mAccessibilityManager.isEnabled()) {
mAccessibilityManager.sendAccessibilityEvent(event);
}
diff --git a/java/src/com/android/inputmethod/accessibility/AccessibleKeyboardViewProxy.java b/java/src/com/android/inputmethod/accessibility/AccessibleKeyboardViewProxy.java
index fcfa6d4e4..e6b44120f 100644
--- a/java/src/com/android/inputmethod/accessibility/AccessibleKeyboardViewProxy.java
+++ b/java/src/com/android/inputmethod/accessibility/AccessibleKeyboardViewProxy.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.accessibility;
@@ -22,8 +22,11 @@ import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
+import android.util.SparseIntArray;
import android.view.MotionEvent;
import android.view.View;
+import android.view.ViewParent;
+import android.view.accessibility.AccessibilityEvent;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
@@ -35,6 +38,21 @@ import com.android.inputmethod.latin.R;
public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateCompat {
private static final AccessibleKeyboardViewProxy sInstance = new AccessibleKeyboardViewProxy();
+ /** Map of keyboard modes to resource IDs. */
+ private static final SparseIntArray KEYBOARD_MODE_RES_IDS = new SparseIntArray();
+
+ static {
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_DATE, R.string.keyboard_mode_date);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_DATETIME, R.string.keyboard_mode_date_time);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_EMAIL, R.string.keyboard_mode_email);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_IM, R.string.keyboard_mode_im);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_NUMBER, R.string.keyboard_mode_number);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_PHONE, R.string.keyboard_mode_phone);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_TEXT, R.string.keyboard_mode_text);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_TIME, R.string.keyboard_mode_time);
+ KEYBOARD_MODE_RES_IDS.put(KeyboardId.MODE_URL, R.string.keyboard_mode_url);
+ }
+
private InputMethodService mInputMethod;
private MainKeyboardView mView;
private AccessibilityEntityProvider mAccessibilityNodeProvider;
@@ -42,12 +60,11 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
private Key mLastHoverKey = null;
/**
- * Inset in pixels to look for keys when the user's finger exits the
- * keyboard area.
+ * Inset in pixels to look for keys when the user's finger exits the keyboard area.
*/
private int mEdgeSlop;
- public static void init(InputMethodService inputMethod) {
+ public static void init(final InputMethodService inputMethod) {
sInstance.initInternal(inputMethod);
}
@@ -59,7 +76,7 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
// Not publicly instantiable.
}
- private void initInternal(InputMethodService inputMethod) {
+ private void initInternal(final InputMethodService inputMethod) {
mInputMethod = inputMethod;
mEdgeSlop = inputMethod.getResources().getDimensionPixelSize(
R.dimen.accessibility_edge_slop);
@@ -70,61 +87,125 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
*
* @param view The view to wrap.
*/
- public void setView(MainKeyboardView view) {
+ public void setView(final MainKeyboardView view) {
if (view == null) {
// Ignore null views.
return;
}
-
mView = view;
// Ensure that the view has an accessibility delegate.
ViewCompat.setAccessibilityDelegate(view, this);
- if (mAccessibilityNodeProvider != null) {
- mAccessibilityNodeProvider.setView(view);
+ if (mAccessibilityNodeProvider == null) {
+ return;
}
+ mAccessibilityNodeProvider.setView(view);
}
- public void setKeyboard(Keyboard keyboard) {
+ /**
+ * Called when the keyboard layout changes.
+ * <p>
+ * <b>Note:</b> This method will be called even if accessibility is not
+ * enabled.
+ */
+ public void setKeyboard() {
if (mAccessibilityNodeProvider != null) {
- mAccessibilityNodeProvider.setKeyboard(keyboard);
+ mAccessibilityNodeProvider.setKeyboard();
+ }
+
+ // Since this method is called even when accessibility is off, make sure
+ // to check the state before announcing anything.
+ if (AccessibilityUtils.getInstance().isAccessibilityEnabled()) {
+ announceKeyboardMode();
}
}
/**
- * Proxy method for View.getAccessibilityNodeProvider(). This method is
- * called in SDK version 15 and higher to obtain the virtual node hierarchy
- * provider.
+ * Called when the keyboard is hidden and accessibility is enabled.
+ */
+ public void onHideWindow() {
+ announceKeyboardHidden();
+ }
+
+ /**
+ * Announces which type of keyboard is being displayed. If the keyboard type
+ * is unknown, no announcement is made.
+ */
+ private void announceKeyboardMode() {
+ final Keyboard keyboard = mView.getKeyboard();
+ final int resId = KEYBOARD_MODE_RES_IDS.get(keyboard.mId.mMode);
+ if (resId == 0) {
+ return;
+ }
+
+ final Context context = mView.getContext();
+ final String keyboardMode = context.getString(resId);
+ final String text = context.getString(R.string.announce_keyboard_mode, keyboardMode);
+
+ sendWindowStateChanged(text);
+ }
+
+ /**
+ * Announces that the keyboard has been hidden.
+ */
+ private void announceKeyboardHidden() {
+ final Context context = mView.getContext();
+ final String text = context.getString(R.string.announce_keyboard_hidden);
+
+ sendWindowStateChanged(text);
+ }
+
+ /**
+ * Sends a window state change event with the specified text.
+ *
+ * @param text
+ */
+ private void sendWindowStateChanged(final String text) {
+ final AccessibilityEvent stateChange = AccessibilityEvent.obtain(
+ AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
+ mView.onInitializeAccessibilityEvent(stateChange);
+ stateChange.getText().add(text);
+ stateChange.setContentDescription(null);
+
+ final ViewParent parent = mView.getParent();
+ if (parent != null) {
+ parent.requestSendAccessibilityEvent(mView, stateChange);
+ }
+ }
+
+ /**
+ * Proxy method for View.getAccessibilityNodeProvider(). This method is called in SDK
+ * version 15 (Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) and higher to obtain the virtual
+ * node hierarchy provider.
*
* @return The accessibility node provider for the current keyboard.
*/
@Override
- public AccessibilityEntityProvider getAccessibilityNodeProvider(View host) {
+ public AccessibilityEntityProvider getAccessibilityNodeProvider(final View host) {
return getAccessibilityNodeProvider();
}
/**
- * Intercepts touch events before dispatch when touch exploration is turned
- * on in ICS and higher.
+ * Intercepts touch events before dispatch when touch exploration is turned on in ICS and
+ * higher.
*
* @param event The motion event being dispatched.
* @return {@code true} if the event is handled
*/
- public boolean dispatchTouchEvent(MotionEvent event) {
+ public boolean dispatchTouchEvent(final MotionEvent event) {
// To avoid accidental key presses during touch exploration, always drop
// touch events generated by the user.
return false;
}
/**
- * Receives hover events when touch exploration is turned on in SDK versions
- * ICS and higher.
+ * Receives hover events when touch exploration is turned on in SDK versions ICS and higher.
*
* @param event The hover event.
* @return {@code true} if the event is handled
*/
- public boolean dispatchHoverEvent(MotionEvent event, PointerTracker tracker) {
+ public boolean dispatchHoverEvent(final MotionEvent event, final PointerTracker tracker) {
final int x = (int) event.getX();
final int y = (int) event.getY();
final Key previousKey = mLastHoverKey;
@@ -135,7 +216,6 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
} else {
key = null;
}
-
mLastHoverKey = key;
switch (event.getAction()) {
@@ -173,30 +253,29 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
}
/**
- * Utility method to determine whether the given point, in local
- * coordinates, is inside the view, where the area of the view is contracted
- * by the edge slop factor.
+ * Utility method to determine whether the given point, in local coordinates, is inside the
+ * view, where the area of the view is contracted by the edge slop factor.
*
* @param localX The local x-coordinate.
* @param localY The local y-coordinate.
*/
- private boolean pointInView(int localX, int localY) {
+ private boolean pointInView(final int localX, final int localY) {
return (localX >= mEdgeSlop) && (localY >= mEdgeSlop)
&& (localX < (mView.getWidth() - mEdgeSlop))
&& (localY < (mView.getHeight() - mEdgeSlop));
}
/**
- * Simulates a transition between two {@link Key}s by sending a HOVER_EXIT
- * on the previous key, a HOVER_ENTER on the current key, and a HOVER_MOVE
- * on the current key.
+ * Simulates a transition between two {@link Key}s by sending a HOVER_EXIT on the previous key,
+ * a HOVER_ENTER on the current key, and a HOVER_MOVE on the current key.
*
* @param currentKey The currently hovered key.
* @param previousKey The previously hovered key.
* @param event The event that triggered the transition.
* @return {@code true} if the event was handled.
*/
- private boolean onTransitionKey(Key currentKey, Key previousKey, MotionEvent event) {
+ private boolean onTransitionKey(final Key currentKey, final Key previousKey,
+ final MotionEvent event) {
final int savedAction = event.getAction();
event.setAction(MotionEvent.ACTION_HOVER_EXIT);
@@ -214,19 +293,18 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
}
/**
- * Handles a hover event on a key. If {@link Key} extended View, this would
- * be analogous to calling View.onHoverEvent(MotionEvent).
+ * Handles a hover event on a key. If {@link Key} extended View, this would be analogous to
+ * calling View.onHoverEvent(MotionEvent).
*
* @param key The currently hovered key.
* @param event The hover event.
* @return {@code true} if the event was handled.
*/
- private boolean onHoverKey(Key key, MotionEvent event) {
+ private boolean onHoverKey(final Key key, final MotionEvent event) {
// Null keys can't receive events.
if (key == null) {
return false;
}
-
final AccessibilityEntityProvider provider = getAccessibilityNodeProvider();
switch (event.getAction()) {
@@ -241,7 +319,6 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
key, AccessibilityEventCompat.TYPE_VIEW_HOVER_EXIT);
break;
}
-
return true;
}
@@ -268,7 +345,6 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
default:
text = context.getText(R.string.spoken_description_shiftmode_off);
}
-
AccessibilityUtils.getInstance().announceForAccessibility(mView, text);
}
@@ -307,7 +383,6 @@ public final class AccessibleKeyboardViewProxy extends AccessibilityDelegateComp
if (resId < 0) {
return;
}
-
final String text = context.getString(resId);
AccessibilityUtils.getInstance().announceForAccessibility(mView, text);
}
diff --git a/java/src/com/android/inputmethod/accessibility/KeyCodeDescriptionMapper.java b/java/src/com/android/inputmethod/accessibility/KeyCodeDescriptionMapper.java
index 32618ad85..05d8269b7 100644
--- a/java/src/com/android/inputmethod/accessibility/KeyCodeDescriptionMapper.java
+++ b/java/src/com/android/inputmethod/accessibility/KeyCodeDescriptionMapper.java
@@ -26,6 +26,7 @@ import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.R;
import java.util.HashMap;
@@ -61,17 +62,19 @@ public final class KeyCodeDescriptionMapper {
mKeyLabelMap.put(":-)", R.string.spoken_description_smiley);
// Special non-character codes defined in Keyboard
- mKeyCodeMap.put(Keyboard.CODE_SPACE, R.string.spoken_description_space);
- mKeyCodeMap.put(Keyboard.CODE_DELETE, R.string.spoken_description_delete);
- mKeyCodeMap.put(Keyboard.CODE_ENTER, R.string.spoken_description_return);
- mKeyCodeMap.put(Keyboard.CODE_SETTINGS, R.string.spoken_description_settings);
- mKeyCodeMap.put(Keyboard.CODE_SHIFT, R.string.spoken_description_shift);
- mKeyCodeMap.put(Keyboard.CODE_SHORTCUT, R.string.spoken_description_mic);
- mKeyCodeMap.put(Keyboard.CODE_SWITCH_ALPHA_SYMBOL, R.string.spoken_description_to_symbol);
- mKeyCodeMap.put(Keyboard.CODE_TAB, R.string.spoken_description_tab);
- mKeyCodeMap.put(Keyboard.CODE_LANGUAGE_SWITCH, R.string.spoken_description_language_switch);
- mKeyCodeMap.put(Keyboard.CODE_ACTION_NEXT, R.string.spoken_description_action_next);
- mKeyCodeMap.put(Keyboard.CODE_ACTION_PREVIOUS, R.string.spoken_description_action_previous);
+ mKeyCodeMap.put(Constants.CODE_SPACE, R.string.spoken_description_space);
+ mKeyCodeMap.put(Constants.CODE_DELETE, R.string.spoken_description_delete);
+ mKeyCodeMap.put(Constants.CODE_ENTER, R.string.spoken_description_return);
+ mKeyCodeMap.put(Constants.CODE_SETTINGS, R.string.spoken_description_settings);
+ mKeyCodeMap.put(Constants.CODE_SHIFT, R.string.spoken_description_shift);
+ mKeyCodeMap.put(Constants.CODE_SHORTCUT, R.string.spoken_description_mic);
+ mKeyCodeMap.put(Constants.CODE_SWITCH_ALPHA_SYMBOL, R.string.spoken_description_to_symbol);
+ mKeyCodeMap.put(Constants.CODE_TAB, R.string.spoken_description_tab);
+ mKeyCodeMap.put(Constants.CODE_LANGUAGE_SWITCH,
+ R.string.spoken_description_language_switch);
+ mKeyCodeMap.put(Constants.CODE_ACTION_NEXT, R.string.spoken_description_action_next);
+ mKeyCodeMap.put(Constants.CODE_ACTION_PREVIOUS,
+ R.string.spoken_description_action_previous);
}
/**
@@ -90,24 +93,26 @@ public final class KeyCodeDescriptionMapper {
* @param keyboard The keyboard on which the key resides.
* @param key The key from which to obtain a description.
* @param shouldObscure {@true} if text (e.g. non-control) characters should be obscured.
- * @return a character sequence describing the action performed by pressing
- * the key
+ * @return a character sequence describing the action performed by pressing the key
*/
- public String getDescriptionForKey(Context context, Keyboard keyboard, Key key,
- boolean shouldObscure) {
+ public String getDescriptionForKey(final Context context, final Keyboard keyboard,
+ final Key key, final boolean shouldObscure) {
final int code = key.mCode;
- if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
+ if (code == Constants.CODE_SWITCH_ALPHA_SYMBOL) {
final String description = getDescriptionForSwitchAlphaSymbol(context, keyboard);
- if (description != null)
+ if (description != null) {
return description;
+ }
}
- if (code == Keyboard.CODE_SHIFT) {
+ if (code == Constants.CODE_SHIFT) {
return getDescriptionForShiftKey(context, keyboard);
}
- if (code == Keyboard.CODE_ACTION_ENTER) {
+ if (code == Constants.CODE_ENTER) {
+ // The following function returns the correct description in all action and
+ // regular enter cases, taking care of all modes.
return getDescriptionForActionKey(context, keyboard, key);
}
@@ -121,10 +126,9 @@ public final class KeyCodeDescriptionMapper {
}
// Just attempt to speak the description.
- if (key.mCode != Keyboard.CODE_UNSPECIFIED) {
+ if (key.mCode != Constants.CODE_UNSPECIFIED) {
return getDescriptionForKeyCode(context, keyboard, key, shouldObscure);
}
-
return null;
}
@@ -135,10 +139,10 @@ public final class KeyCodeDescriptionMapper {
*
* @param context The package's context.
* @param keyboard The keyboard on which the key resides.
- * @return a character sequence describing the action performed by pressing
- * the key
+ * @return a character sequence describing the action performed by pressing the key
*/
- private String getDescriptionForSwitchAlphaSymbol(Context context, Keyboard keyboard) {
+ private String getDescriptionForSwitchAlphaSymbol(final Context context,
+ final Keyboard keyboard) {
final KeyboardId keyboardId = keyboard.mId;
final int elementId = keyboardId.mElementId;
final int resId;
@@ -165,7 +169,6 @@ public final class KeyCodeDescriptionMapper {
Log.e(TAG, "Missing description for keyboard element ID:" + elementId);
return null;
}
-
return context.getString(resId);
}
@@ -176,7 +179,7 @@ public final class KeyCodeDescriptionMapper {
* @param keyboard The keyboard on which the key resides.
* @return A context-sensitive description of the "Shift" key.
*/
- private String getDescriptionForShiftKey(Context context, Keyboard keyboard) {
+ private String getDescriptionForShiftKey(final Context context, final Keyboard keyboard) {
final KeyboardId keyboardId = keyboard.mId;
final int elementId = keyboardId.mElementId;
final int resId;
@@ -194,7 +197,6 @@ public final class KeyCodeDescriptionMapper {
default:
resId = R.string.spoken_description_shift;
}
-
return context.getString(resId);
}
@@ -204,12 +206,12 @@ public final class KeyCodeDescriptionMapper {
* @param context The package's context.
* @param keyboard The keyboard on which the key resides.
* @param key The key to describe.
- * @return Returns a context-sensitive description of the "Enter" action
- * key.
+ * @return Returns a context-sensitive description of the "Enter" action key.
*/
- private String getDescriptionForActionKey(Context context, Keyboard keyboard, Key key) {
+ private String getDescriptionForActionKey(final Context context, final Keyboard keyboard,
+ final Key key) {
final KeyboardId keyboardId = keyboard.mId;
- final int actionId = keyboardId.imeActionId();
+ final int actionId = keyboardId.imeAction();
final int resId;
// Always use the label, if available.
@@ -240,7 +242,6 @@ public final class KeyCodeDescriptionMapper {
default:
resId = R.string.spoken_description_return;
}
-
return context.getString(resId);
}
@@ -262,11 +263,10 @@ public final class KeyCodeDescriptionMapper {
* @param keyboard The keyboard on which the key resides.
* @param key The key from which to obtain a description.
* @param shouldObscure {@true} if text (e.g. non-control) characters should be obscured.
- * @return a character sequence describing the action performed by pressing
- * the key
+ * @return a character sequence describing the action performed by pressing the key
*/
- private String getDescriptionForKeyCode(Context context, Keyboard keyboard, Key key,
- boolean shouldObscure) {
+ private String getDescriptionForKeyCode(final Context context, final Keyboard keyboard,
+ final Key key, final boolean shouldObscure) {
final int code = key.mCode;
// If the key description should be obscured, now is the time to do it.
@@ -274,15 +274,15 @@ public final class KeyCodeDescriptionMapper {
if (shouldObscure && isDefinedNonCtrl) {
return context.getString(OBSCURED_KEY_RES_ID);
}
-
if (mKeyCodeMap.indexOfKey(code) >= 0) {
return context.getString(mKeyCodeMap.get(code));
- } else if (isDefinedNonCtrl) {
+ }
+ if (isDefinedNonCtrl) {
return Character.toString((char) code);
- } else if (!TextUtils.isEmpty(key.mLabel)) {
+ }
+ if (!TextUtils.isEmpty(key.mLabel)) {
return key.mLabel;
- } else {
- return context.getString(R.string.spoken_description_unknown, code);
}
+ return context.getString(R.string.spoken_description_unknown, code);
}
}
diff --git a/java/src/com/android/inputmethod/annotations/ExternallyReferenced.java b/java/src/com/android/inputmethod/annotations/ExternallyReferenced.java
new file mode 100644
index 000000000..ea5f12ce2
--- /dev/null
+++ b/java/src/com/android/inputmethod/annotations/ExternallyReferenced.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2012 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.annotations;
+
+/**
+ * Denotes that the class, method or field should not be eliminated by ProGuard,
+ * because it is externally referenced. (See proguard.flags)
+ */
+public @interface ExternallyReferenced {
+}
diff --git a/java/src/com/android/inputmethod/annotations/UsedForTesting.java b/java/src/com/android/inputmethod/annotations/UsedForTesting.java
new file mode 100644
index 000000000..2ada091e4
--- /dev/null
+++ b/java/src/com/android/inputmethod/annotations/UsedForTesting.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2012 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.annotations;
+
+/**
+ * Denotes that the class, method or field should not be eliminated by ProGuard,
+ * so that unit tests can access it. (See proguard.flags)
+ */
+public @interface UsedForTesting {
+}
diff --git a/java/src/com/android/inputmethod/compat/AudioManagerCompatWrapper.java b/java/src/com/android/inputmethod/compat/AudioManagerCompatWrapper.java
deleted file mode 100644
index 40eed91f2..000000000
--- a/java/src/com/android/inputmethod/compat/AudioManagerCompatWrapper.java
+++ /dev/null
@@ -1,54 +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.compat;
-
-import android.media.AudioManager;
-
-import java.lang.reflect.Method;
-
-public final class AudioManagerCompatWrapper {
- private static final Method METHOD_isWiredHeadsetOn = CompatUtils.getMethod(
- AudioManager.class, "isWiredHeadsetOn");
- private static final Method METHOD_isBluetoothA2dpOn = CompatUtils.getMethod(
- AudioManager.class, "isBluetoothA2dpOn");
-
- private final AudioManager mManager;
-
- public AudioManagerCompatWrapper(AudioManager manager) {
- mManager = manager;
- }
-
- /**
- * Checks whether audio routing to the wired headset is on or off.
- *
- * @return true if audio is being routed to/from wired headset;
- * false if otherwise
- */
- public boolean isWiredHeadsetOn() {
- return (Boolean) CompatUtils.invoke(mManager, false, METHOD_isWiredHeadsetOn);
- }
-
- /**
- * Checks whether A2DP audio routing to the Bluetooth headset is on or off.
- *
- * @return true if A2DP audio is being routed to/from Bluetooth headset;
- * false if otherwise
- */
- public boolean isBluetoothA2dpOn() {
- return (Boolean) CompatUtils.invoke(mManager, false, METHOD_isBluetoothA2dpOn);
- }
-}
diff --git a/java/src/com/android/inputmethod/compat/CompatUtils.java b/java/src/com/android/inputmethod/compat/CompatUtils.java
index ffed6ecb1..660029baf 100644
--- a/java/src/com/android/inputmethod/compat/CompatUtils.java
+++ b/java/src/com/android/inputmethod/compat/CompatUtils.java
@@ -16,7 +16,6 @@
package com.android.inputmethod.compat;
-import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
@@ -26,26 +25,12 @@ import java.lang.reflect.Method;
public final 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";
- public static Intent getInputLanguageSelectionIntent(String inputMethodId,
- int flagsForSubtypeSettings) {
- // Refer to android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS
- final String action = INPUT_METHOD_SUBTYPE_SETTINGS;
- final Intent intent = new Intent(action);
- if (!TextUtils.isEmpty(inputMethodId)) {
- intent.putExtra(EXTRA_INPUT_METHOD_ID, inputMethodId);
- }
- if (flagsForSubtypeSettings > 0) {
- intent.setFlags(flagsForSubtypeSettings);
- }
- return intent;
+ private CompatUtils() {
+ // This utility class is not publicly instantiable.
}
- public static Class<?> getClass(String className) {
+ public static Class<?> getClass(final String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
@@ -53,8 +38,8 @@ public final class CompatUtils {
}
}
- public static Method getMethod(Class<?> targetClass, String name,
- Class<?>... parameterTypes) {
+ public static Method getMethod(final Class<?> targetClass, final String name,
+ final Class<?>... parameterTypes) {
if (targetClass == null || TextUtils.isEmpty(name)) return null;
try {
return targetClass.getMethod(name, parameterTypes);
@@ -66,7 +51,7 @@ public final class CompatUtils {
return null;
}
- public static Field getField(Class<?> targetClass, String name) {
+ public static Field getField(final Class<?> targetClass, final String name) {
if (targetClass == null || TextUtils.isEmpty(name)) return null;
try {
return targetClass.getField(name);
@@ -78,7 +63,8 @@ public final class CompatUtils {
return null;
}
- public static Constructor<?> getConstructor(Class<?> targetClass, Class<?> ... types) {
+ public static Constructor<?> getConstructor(final Class<?> targetClass,
+ final Class<?> ... types) {
if (targetClass == null || types == null) return null;
try {
return targetClass.getConstructor(types);
@@ -90,43 +76,44 @@ public final class CompatUtils {
return null;
}
- public static Object newInstance(Constructor<?> constructor, Object ... args) {
+ public static Object newInstance(final Constructor<?> constructor, final Object ... args) {
if (constructor == null) return null;
try {
return constructor.newInstance(args);
} catch (Exception e) {
- Log.e(TAG, "Exception in newInstance: " + e.getClass().getSimpleName());
+ Log.e(TAG, "Exception in newInstance", e);
}
return null;
}
- public static Object invoke(
- Object receiver, Object defaultValue, Method method, Object... args) {
+ public static Object invoke(final Object receiver, final Object defaultValue,
+ final Method method, final 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());
+ Log.e(TAG, "Exception in invoke", e);
}
return defaultValue;
}
- public static Object getFieldValue(Object receiver, Object defaultValue, Field field) {
+ public static Object getFieldValue(final Object receiver, final Object defaultValue,
+ final Field field) {
if (field == null) return defaultValue;
try {
return field.get(receiver);
} catch (Exception e) {
- Log.e(TAG, "Exception in getFieldValue: " + e.getClass().getSimpleName());
+ Log.e(TAG, "Exception in getFieldValue", e);
}
return defaultValue;
}
- public static void setFieldValue(Object receiver, Field field, Object value) {
+ public static void setFieldValue(final Object receiver, final Field field, final Object value) {
if (field == null) return;
try {
field.set(receiver, value);
} catch (Exception e) {
- Log.e(TAG, "Exception in setFieldValue: " + e.getClass().getSimpleName());
+ Log.e(TAG, "Exception in setFieldValue", e);
}
}
}
diff --git a/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java b/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java
index 210058bec..7eefa221a 100644
--- a/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java
+++ b/java/src/com/android/inputmethod/compat/EditorInfoCompatUtils.java
@@ -21,23 +21,23 @@ import android.view.inputmethod.EditorInfo;
import java.lang.reflect.Field;
public final class EditorInfoCompatUtils {
- // EditorInfo.IME_FLAG_FORCE_ASCII has been introduced since API#16 (JellyBean).
+ // Note that EditorInfo.IME_FLAG_FORCE_ASCII has been introduced
+ // in API level 16 (Build.VERSION_CODES.JELLY_BEAN).
private static final Field FIELD_IME_FLAG_FORCE_ASCII = CompatUtils.getField(
EditorInfo.class, "IME_FLAG_FORCE_ASCII");
- private static final Integer OBJ_IME_FLAG_FORCE_ASCII = (Integer) CompatUtils
- .getFieldValue(null, null, FIELD_IME_FLAG_FORCE_ASCII);
+ private static final Integer OBJ_IME_FLAG_FORCE_ASCII = (Integer) CompatUtils.getFieldValue(
+ null /* receiver */, null /* defaultValue */, FIELD_IME_FLAG_FORCE_ASCII);
private EditorInfoCompatUtils() {
// This utility class is not publicly instantiable.
}
- public static boolean hasFlagForceAscii(int imeOptions) {
- if (OBJ_IME_FLAG_FORCE_ASCII == null)
- return false;
+ public static boolean hasFlagForceAscii(final int imeOptions) {
+ if (OBJ_IME_FLAG_FORCE_ASCII == null) return false;
return (imeOptions & OBJ_IME_FLAG_FORCE_ASCII) != 0;
}
- public static String imeActionName(int imeOptions) {
+ public static String imeActionName(final int imeOptions) {
final int actionId = imeOptions & EditorInfo.IME_MASK_ACTION;
switch (actionId) {
case EditorInfo.IME_ACTION_UNSPECIFIED:
@@ -61,7 +61,7 @@ public final class EditorInfoCompatUtils {
}
}
- public static String imeOptionsName(int imeOptions) {
+ public static String imeOptionsName(final int imeOptions) {
final String action = imeActionName(imeOptions);
final StringBuilder flags = new StringBuilder();
if ((imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
diff --git a/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java b/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java
index ab7bd4914..a80c3fefe 100644
--- a/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java
+++ b/java/src/com/android/inputmethod/compat/InputMethodManagerCompatWrapper.java
@@ -19,61 +19,23 @@ package com.android.inputmethod.compat;
import android.content.Context;
import android.os.IBinder;
import android.view.inputmethod.InputMethodManager;
-import android.view.inputmethod.InputMethodSubtype;
-
-import com.android.inputmethod.latin.ImfUtils;
import java.lang.reflect.Method;
-// TODO: Override this class with the concrete implementation if we need to take care of the
-// performance.
public final class InputMethodManagerCompatWrapper {
- private static final String TAG = InputMethodManagerCompatWrapper.class.getSimpleName();
+ // Note that InputMethodManager.switchToNextInputMethod() has been introduced
+ // in API level 16 (Build.VERSION_CODES.JELLY_BEAN).
private static final Method METHOD_switchToNextInputMethod = CompatUtils.getMethod(
InputMethodManager.class, "switchToNextInputMethod", IBinder.class, Boolean.TYPE);
- private static final InputMethodManagerCompatWrapper sInstance =
- new InputMethodManagerCompatWrapper();
-
- private InputMethodManager mImm;
-
- private InputMethodManagerCompatWrapper() {
- // This wrapper class is not publicly instantiable.
- }
-
- public static InputMethodManagerCompatWrapper getInstance() {
- if (sInstance.mImm == null) {
- throw new RuntimeException(TAG + ".getInstance() is called before initialization");
- }
- return sInstance;
- }
-
- public static void init(Context context) {
- sInstance.mImm = ImfUtils.getInputMethodManager(context);
- }
-
- public InputMethodSubtype getCurrentInputMethodSubtype() {
- return mImm.getCurrentInputMethodSubtype();
- }
-
- public InputMethodSubtype getLastInputMethodSubtype() {
- return mImm.getLastInputMethodSubtype();
- }
-
- public boolean switchToLastInputMethod(IBinder token) {
- return mImm.switchToLastInputMethod(token);
- }
-
- public boolean switchToNextInputMethod(IBinder token, boolean onlyCurrentIme) {
- return (Boolean)CompatUtils.invoke(mImm, false, METHOD_switchToNextInputMethod, token,
- onlyCurrentIme);
- }
+ public final InputMethodManager mImm;
- public void setInputMethodAndSubtype(IBinder token, String id, InputMethodSubtype subtype) {
- mImm.setInputMethodAndSubtype(token, id, subtype);
+ public InputMethodManagerCompatWrapper(final Context context) {
+ mImm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
}
- public void showInputMethodPicker() {
- mImm.showInputMethodPicker();
+ public boolean switchToNextInputMethod(final IBinder token, final boolean onlyCurrentIme) {
+ return (Boolean)CompatUtils.invoke(mImm, false /* defaultValue */,
+ METHOD_switchToNextInputMethod, token, onlyCurrentIme);
}
}
diff --git a/java/src/com/android/inputmethod/compat/InputMethodServiceCompatUtils.java b/java/src/com/android/inputmethod/compat/InputMethodServiceCompatUtils.java
index 8eea31ed2..14ee654f3 100644
--- a/java/src/com/android/inputmethod/compat/InputMethodServiceCompatUtils.java
+++ b/java/src/com/android/inputmethod/compat/InputMethodServiceCompatUtils.java
@@ -21,6 +21,8 @@ import android.inputmethodservice.InputMethodService;
import java.lang.reflect.Method;
public final class InputMethodServiceCompatUtils {
+ // Note that InputMethodService.enableHardwareAcceleration() has been introduced
+ // in API level 17 (Build.VERSION_CODES.JELLY_BEAN_MR1).
private static final Method METHOD_enableHardwareAcceleration =
CompatUtils.getMethod(InputMethodService.class, "enableHardwareAcceleration");
@@ -28,7 +30,8 @@ public final class InputMethodServiceCompatUtils {
// This utility class is not publicly instantiable.
}
- public static boolean enableHardwareAcceleration(InputMethodService ims) {
- return (Boolean)CompatUtils.invoke(ims, false, METHOD_enableHardwareAcceleration);
+ public static boolean enableHardwareAcceleration(final InputMethodService ims) {
+ return (Boolean)CompatUtils.invoke(ims, false /* defaultValue */,
+ METHOD_enableHardwareAcceleration);
}
}
diff --git a/java/src/com/android/inputmethod/compat/IntentCompatUtils.java b/java/src/com/android/inputmethod/compat/IntentCompatUtils.java
new file mode 100644
index 000000000..df2e22fe8
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/IntentCompatUtils.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2013 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;
+
+public final class IntentCompatUtils {
+ // Note that Intent.ACTION_USER_INITIALIZE have been introduced in API level 17
+ // (Build.VERSION_CODE.JELLY_BEAN_MR1).
+ public static final String ACTION_USER_INITIALIZE =
+ (String)CompatUtils.getFieldValue(null, null,
+ CompatUtils.getField(Intent.class, "ACTION_USER_INITIALIZE"));
+
+ private IntentCompatUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static boolean has_ACTION_USER_INITIALIZE(final Intent intent) {
+ return ACTION_USER_INITIALIZE != null && intent != null
+ && ACTION_USER_INITIALIZE.equals(intent.getAction());
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/SettingsSecureCompatUtils.java b/java/src/com/android/inputmethod/compat/SettingsSecureCompatUtils.java
index db5abd0fe..cfaf7ec77 100644
--- a/java/src/com/android/inputmethod/compat/SettingsSecureCompatUtils.java
+++ b/java/src/com/android/inputmethod/compat/SettingsSecureCompatUtils.java
@@ -19,6 +19,8 @@ package com.android.inputmethod.compat;
import java.lang.reflect.Field;
public final class SettingsSecureCompatUtils {
+ // Note that Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD has been introduced
+ // in API level 15 (Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1).
private static final Field FIELD_ACCESSIBILITY_SPEAK_PASSWORD = CompatUtils.getField(
android.provider.Settings.Secure.class, "ACCESSIBILITY_SPEAK_PASSWORD");
@@ -30,5 +32,5 @@ public final class SettingsSecureCompatUtils {
* Whether to speak passwords while in accessibility mode.
*/
public static final String ACCESSIBILITY_SPEAK_PASSWORD = (String) CompatUtils.getFieldValue(
- null, null, FIELD_ACCESSIBILITY_SPEAK_PASSWORD);
+ null /* receiver */, null /* defaultValue */, FIELD_ACCESSIBILITY_SPEAK_PASSWORD);
}
diff --git a/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java b/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java
index 159f43650..141e08a8d 100644
--- a/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java
+++ b/java/src/com/android/inputmethod/compat/SuggestionSpanUtils.java
@@ -21,58 +21,29 @@ import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
-import android.util.Log;
+import android.text.style.SuggestionSpan;
import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.SuggestedWords;
import com.android.inputmethod.latin.SuggestionSpanPickedNotificationReceiver;
-import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
-import java.util.Locale;
public final class SuggestionSpanUtils {
private static final String TAG = SuggestionSpanUtils.class.getSimpleName();
- // TODO: Use reflection to get field values
- 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";
- public static final boolean SUGGESTION_SPAN_IS_SUPPORTED;
- 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 Field FIELD_FLAG_EASY_CORRECT =
- CompatUtils.getField(CLASS_SuggestionSpan, "FLAG_EASY_CORRECT");
- public static final Field FIELD_FLAG_MISSPELLED =
- CompatUtils.getField(CLASS_SuggestionSpan, "FLAG_MISSPELLED");
- public static final Field FIELD_FLAG_AUTO_CORRECTION =
- CompatUtils.getField(CLASS_SuggestionSpan, "FLAG_AUTO_CORRECTION");
- public static final Field FIELD_SUGGESTIONS_MAX_SIZE
- = CompatUtils.getField(CLASS_SuggestionSpan, "SUGGESTIONS_MAX_SIZE");
- public static final Integer OBJ_FLAG_EASY_CORRECT = (Integer) CompatUtils
- .getFieldValue(null, null, FIELD_FLAG_EASY_CORRECT);
- public static final Integer OBJ_FLAG_MISSPELLED = (Integer) CompatUtils
- .getFieldValue(null, null, FIELD_FLAG_MISSPELLED);
- public static final Integer OBJ_FLAG_AUTO_CORRECTION = (Integer) CompatUtils
- .getFieldValue(null, null, FIELD_FLAG_AUTO_CORRECTION);
- public static final Integer OBJ_SUGGESTIONS_MAX_SIZE = (Integer) CompatUtils
- .getFieldValue(null, null, FIELD_SUGGESTIONS_MAX_SIZE);
+ // Note that SuggestionSpan.FLAG_AUTO_CORRECTION has been introduced
+ // in API level 15 (Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1).
+ public static final Field FIELD_FLAG_AUTO_CORRECTION = CompatUtils.getField(
+ SuggestionSpan.class, "FLAG_AUTO_CORRECTION");
+ public static final Integer OBJ_FLAG_AUTO_CORRECTION = (Integer) CompatUtils.getFieldValue(
+ null /* receiver */, null /* defaultValue */, FIELD_FLAG_AUTO_CORRECTION);
static {
- SUGGESTION_SPAN_IS_SUPPORTED =
- CLASS_SuggestionSpan != null && CONSTRUCTOR_SuggestionSpan != null;
if (LatinImeLogger.sDBG) {
- if (SUGGESTION_SPAN_IS_SUPPORTED
- && (OBJ_FLAG_AUTO_CORRECTION == null || OBJ_SUGGESTIONS_MAX_SIZE == null
- || OBJ_FLAG_MISSPELLED == null || OBJ_FLAG_EASY_CORRECT == null)) {
+ if (OBJ_FLAG_AUTO_CORRECTION == null) {
throw new RuntimeException("Field is accidentially null.");
}
}
@@ -83,49 +54,34 @@ public final class SuggestionSpanUtils {
}
public static CharSequence getTextWithAutoCorrectionIndicatorUnderline(
- Context context, CharSequence text) {
- if (TextUtils.isEmpty(text) || CONSTRUCTOR_SuggestionSpan == null
- || OBJ_FLAG_AUTO_CORRECTION == null || OBJ_SUGGESTIONS_MAX_SIZE == null
- || OBJ_FLAG_MISSPELLED == null || OBJ_FLAG_EASY_CORRECT == null) {
+ final Context context, final String text) {
+ if (TextUtils.isEmpty(text) || OBJ_FLAG_AUTO_CORRECTION == null) {
return text;
}
- final Spannable spannable = text instanceof Spannable
- ? (Spannable) text : new SpannableString(text);
- final Object[] args =
- { context, null, new String[] {}, (int)OBJ_FLAG_AUTO_CORRECTION,
- (Class<?>) SuggestionSpanPickedNotificationReceiver.class };
- final Object ss = CompatUtils.newInstance(CONSTRUCTOR_SuggestionSpan, args);
- if (ss == null) {
- Log.w(TAG, "Suggestion span was not created.");
- return text;
- }
- spannable.setSpan(ss, 0, text.length(),
+ final Spannable spannable = new SpannableString(text);
+ final SuggestionSpan suggestionSpan = new SuggestionSpan(context, null /* locale */,
+ new String[] {} /* suggestions */, (int)OBJ_FLAG_AUTO_CORRECTION,
+ SuggestionSpanPickedNotificationReceiver.class);
+ spannable.setSpan(suggestionSpan, 0, text.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
return spannable;
}
- public static CharSequence getTextWithSuggestionSpan(Context context,
- CharSequence pickedWord, SuggestedWords suggestedWords, boolean dictionaryAvailable) {
- if (!dictionaryAvailable || TextUtils.isEmpty(pickedWord)
- || CONSTRUCTOR_SuggestionSpan == null
- || suggestedWords == null || suggestedWords.size() == 0
- || suggestedWords.mIsPrediction || suggestedWords.mIsPunctuationSuggestions
- || OBJ_SUGGESTIONS_MAX_SIZE == null) {
+ public static CharSequence getTextWithSuggestionSpan(final Context context,
+ final String pickedWord, final SuggestedWords suggestedWords,
+ final boolean dictionaryAvailable) {
+ if (!dictionaryAvailable || TextUtils.isEmpty(pickedWord) || suggestedWords.isEmpty()
+ || suggestedWords.mIsPrediction || suggestedWords.mIsPunctuationSuggestions) {
return pickedWord;
}
- final Spannable spannable;
- if (pickedWord instanceof Spannable) {
- spannable = (Spannable) pickedWord;
- } else {
- spannable = new SpannableString(pickedWord);
- }
+ final Spannable spannable = new SpannableString(pickedWord);
final ArrayList<String> suggestionsList = CollectionUtils.newArrayList();
for (int i = 0; i < suggestedWords.size(); ++i) {
- if (suggestionsList.size() >= OBJ_SUGGESTIONS_MAX_SIZE) {
+ if (suggestionsList.size() >= SuggestionSpan.SUGGESTIONS_MAX_SIZE) {
break;
}
- final CharSequence word = suggestedWords.getWord(i);
+ final String word = suggestedWords.getWord(i);
if (!TextUtils.equals(pickedWord, word)) {
suggestionsList.add(word.toString());
}
@@ -133,14 +89,10 @@ public final class SuggestionSpanUtils {
// TODO: We should avoid adding suggestion span candidates that came from the bigram
// prediction.
- final Object[] args =
- { context, null, suggestionsList.toArray(new String[suggestionsList.size()]), 0,
- (Class<?>) SuggestionSpanPickedNotificationReceiver.class };
- final Object ss = CompatUtils.newInstance(CONSTRUCTOR_SuggestionSpan, args);
- if (ss == null) {
- return pickedWord;
- }
- spannable.setSpan(ss, 0, pickedWord.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+ final SuggestionSpan suggestionSpan = new SuggestionSpan(context, null /* locale */,
+ suggestionsList.toArray(new String[suggestionsList.size()]), 0 /* flags */,
+ SuggestionSpanPickedNotificationReceiver.class);
+ spannable.setSpan(suggestionSpan, 0, pickedWord.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
}
diff --git a/java/src/com/android/inputmethod/compat/SuggestionsInfoCompatUtils.java b/java/src/com/android/inputmethod/compat/SuggestionsInfoCompatUtils.java
index 8314212c9..d8d2be04c 100644
--- a/java/src/com/android/inputmethod/compat/SuggestionsInfoCompatUtils.java
+++ b/java/src/com/android/inputmethod/compat/SuggestionsInfoCompatUtils.java
@@ -21,10 +21,13 @@ import android.view.textservice.SuggestionsInfo;
import java.lang.reflect.Field;
public final class SuggestionsInfoCompatUtils {
- private static final Field FIELD_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS = CompatUtils.getField(
- SuggestionsInfo.class, "RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS");
- private static final Integer OBJ_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS = (Integer) CompatUtils
- .getFieldValue(null, null, FIELD_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS);
+ // Note that SuggestionsInfo.RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS has been introduced
+ // in API level 15 (Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1).
+ private static final Field FIELD_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS =
+ CompatUtils.getField(SuggestionsInfo.class, "RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS");
+ private static final Integer OBJ_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS =
+ (Integer) CompatUtils.getFieldValue(null /* receiver */, null /* defaultValue */,
+ FIELD_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS);
private static final int RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS =
OBJ_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS != null
? OBJ_RESULT_ATTR_HAS_RECOMMENDED_SUGGESTIONS : 0;
diff --git a/java/src/com/android/inputmethod/compat/TextViewCompatUtils.java b/java/src/com/android/inputmethod/compat/TextViewCompatUtils.java
new file mode 100644
index 000000000..d4f1ea830
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/TextViewCompatUtils.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2013 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.graphics.drawable.Drawable;
+import android.widget.TextView;
+
+import java.lang.reflect.Method;
+
+public final class TextViewCompatUtils {
+ // Note that TextView.setCompoundDrawablesRelative(Drawable,Drawable,Drawable,Drawable) has
+ // been introduced in API level 17 (Build.VERSION_CODE.JELLY_BEAN_MR1).
+ private static final Method METHOD_setCompoundDrawablesRelative = CompatUtils.getMethod(
+ TextView.class, "setCompoundDrawablesRelative",
+ Drawable.class, Drawable.class, Drawable.class, Drawable.class);
+
+ private TextViewCompatUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static void setCompoundDrawablesRelative(final TextView textView, final Drawable start,
+ final Drawable top, final Drawable end, final Drawable bottom) {
+ if (METHOD_setCompoundDrawablesRelative == null) {
+ textView.setCompoundDrawables(start, top, end, bottom);
+ return;
+ }
+ CompatUtils.invoke(textView, null, METHOD_setCompoundDrawablesRelative,
+ start, top, end, bottom);
+ }
+}
diff --git a/java/src/com/android/inputmethod/compat/ViewCompatUtils.java b/java/src/com/android/inputmethod/compat/ViewCompatUtils.java
new file mode 100644
index 000000000..a8fab8855
--- /dev/null
+++ b/java/src/com/android/inputmethod/compat/ViewCompatUtils.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013 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.View;
+
+import java.lang.reflect.Method;
+
+public final class ViewCompatUtils {
+ // Note that View.LAYOUT_DIRECTION_LTR and View.LAYOUT_DIRECTION_RTL have been introduced in
+ // API level 17 (Build.VERSION_CODE.JELLY_BEAN_MR1).
+ public static final int LAYOUT_DIRECTION_LTR = (Integer)CompatUtils.getFieldValue(null, 0x0,
+ CompatUtils.getField(View.class, "LAYOUT_DIRECTION_LTR"));
+ public static final int LAYOUT_DIRECTION_RTL = (Integer)CompatUtils.getFieldValue(null, 0x1,
+ CompatUtils.getField(View.class, "LAYOUT_DIRECTION_RTL"));
+
+ // Note that View.getPaddingEnd(), View.setPaddingRelative(int,int,int,int), and
+ // View.getLayoutDirection() have been introduced in API level 17
+ // (Build.VERSION_CODE.JELLY_BEAN_MR1).
+ private static final Method METHOD_getPaddingEnd = CompatUtils.getMethod(
+ View.class, "getPaddingEnd");
+ private static final Method METHOD_setPaddingRelative = CompatUtils.getMethod(
+ View.class, "setPaddingRelative",
+ Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE);
+ private static final Method METHOD_getLayoutDirection = CompatUtils.getMethod(
+ View.class, "getLayoutDirection");
+
+ private ViewCompatUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static int getPaddingEnd(final View view) {
+ if (METHOD_getPaddingEnd == null) {
+ return view.getPaddingRight();
+ }
+ return (Integer)CompatUtils.invoke(view, 0, METHOD_getPaddingEnd);
+ }
+
+ public static void setPaddingRelative(final View view, final int start, final int top,
+ final int end, final int bottom) {
+ if (METHOD_setPaddingRelative == null) {
+ view.setPadding(start, top, end, bottom);
+ return;
+ }
+ CompatUtils.invoke(view, null, METHOD_setPaddingRelative, start, top, end, bottom);
+ }
+
+ public static int getLayoutDirection(final View view) {
+ if (METHOD_getLayoutDirection == null) {
+ return LAYOUT_DIRECTION_LTR;
+ }
+ return (Integer)CompatUtils.invoke(view, 0, METHOD_getLayoutDirection);
+ }
+}
diff --git a/java/src/com/android/inputmethod/event/Combiner.java b/java/src/com/android/inputmethod/event/Combiner.java
new file mode 100644
index 000000000..ab6b70c04
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/Combiner.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2013 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.event;
+
+/**
+ * A generic interface for combiners.
+ */
+public interface Combiner {
+ /**
+ * Combine an event with the existing state and return the new event.
+ * @param event the event to combine with the existing state.
+ * @return the resulting event.
+ */
+ Event combine(Event event);
+}
diff --git a/java/src/com/android/inputmethod/event/DeadKeyCombiner.java b/java/src/com/android/inputmethod/event/DeadKeyCombiner.java
new file mode 100644
index 000000000..52987d571
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/DeadKeyCombiner.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2013 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.event;
+
+import android.text.TextUtils;
+import android.view.KeyCharacterMap;
+
+import com.android.inputmethod.latin.Constants;
+
+/**
+ * A combiner that handles dead keys.
+ */
+public class DeadKeyCombiner implements Combiner {
+ final StringBuilder mDeadSequence = new StringBuilder();
+
+ @Override
+ public Event combine(final Event event) {
+ if (null == event) return null; // Just in case some combiner is broken
+ if (TextUtils.isEmpty(mDeadSequence)) {
+ if (event.isDead()) {
+ mDeadSequence.appendCodePoint(event.mCodePoint);
+ }
+ return event;
+ } else {
+ // TODO: Allow combining for several dead chars rather than only the first one.
+ // The framework doesn't know how to do this now.
+ final int deadCodePoint = mDeadSequence.codePointAt(0);
+ mDeadSequence.setLength(0);
+ final int resultingCodePoint =
+ KeyCharacterMap.getDeadChar(deadCodePoint, event.mCodePoint);
+ if (0 == resultingCodePoint) {
+ // We can't combine both characters. We need to commit the dead key as a committable
+ // character, and the next char too unless it's a space (because as a special case,
+ // dead key + space should result in only the dead key being committed - that's
+ // how dead keys work).
+ // If the event is a space, we should commit the dead char alone, but if it's
+ // not, we need to commit both.
+ return Event.createCommittableEvent(deadCodePoint,
+ Constants.CODE_SPACE == event.mCodePoint ? null : event /* next */);
+ } else {
+ // We could combine the characters.
+ return Event.createCommittableEvent(resultingCodePoint, null /* next */);
+ }
+ }
+ }
+
+}
diff --git a/java/src/com/android/inputmethod/event/Event.java b/java/src/com/android/inputmethod/event/Event.java
new file mode 100644
index 000000000..1f3320eb7
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/Event.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+/**
+ * Class representing a generic input event as handled by Latin IME.
+ *
+ * This contains information about the origin of the event, but it is generalized and should
+ * represent a software keypress, hardware keypress, or d-pad move alike.
+ * Very importantly, this does not necessarily result in inputting one character, or even anything
+ * at all - it may be a dead key, it may be a partial input, it may be a special key on the
+ * keyboard, it may be a cancellation of a keypress (e.g. in a soft keyboard the finger of the
+ * user has slid out of the key), etc. It may also be a batch input from a gesture or handwriting
+ * for example.
+ * The combiner should figure out what to do with this.
+ */
+public class Event {
+ // Should the types below be represented by separate classes instead? It would be cleaner
+ // but probably a bit too much
+ // An event we don't handle in Latin IME, for example pressing Ctrl on a hardware keyboard.
+ final public static int EVENT_NOT_HANDLED = 0;
+ // A character that is already final, for example pressing an alphabetic character on a
+ // hardware qwerty keyboard.
+ final public static int EVENT_COMMITTABLE = 1;
+ // A dead key, which means a character that should combine with what is coming next. Examples
+ // include the "^" character on an azerty keyboard which combines with "e" to make "ê", or
+ // AltGr+' on a dvorak international keyboard which combines with "e" to make "é". This is
+ // true regardless of the language or combining mode, and should be seen as a property of the
+ // key - a dead key followed by another key with which it can combine should be regarded as if
+ // the keyboard actually had such a key.
+ final public static int EVENT_DEAD = 2;
+ // A toggle event is triggered by a key that affects the previous character. An example would
+ // be a numeric key on a 10-key keyboard, which would toggle between 1 - a - b - c with
+ // repeated presses.
+ final public static int EVENT_TOGGLE = 3;
+ // A mode event instructs the combiner to change modes. The canonical example would be the
+ // hankaku/zenkaku key on a Japanese keyboard, or even the caps lock key on a qwerty keyboard
+ // if handled at the combiner level.
+ final public static int EVENT_MODE_KEY = 4;
+
+ final private static int NOT_A_CODE_POINT = 0;
+
+ final private int mType; // The type of event - one of the constants above
+ // The code point associated with the event, if relevant. This is a unicode code point, and
+ // has nothing to do with other representations of the key. It is only relevant if this event
+ // is the right type: COMMITTABLE or DEAD or TOGGLE, but for a mode key like hankaku/zenkaku or
+ // ctrl, there is no code point associated so this should be NOT_A_CODE_POINT to avoid
+ // unintentional use of its value when it's not relevant.
+ final public int mCodePoint;
+ // The next event, if any. Null if there is no next event yet.
+ final public Event mNextEvent;
+
+ // This method is private - to create a new event, use one of the create* utility methods.
+ private Event(final int type, final int codePoint, final Event next) {
+ mType = type;
+ mCodePoint = codePoint;
+ mNextEvent = next;
+ }
+
+ public static Event createDeadEvent(final int codePoint, final Event next) {
+ return new Event(EVENT_DEAD, codePoint, next);
+ }
+
+ public static Event createCommittableEvent(final int codePoint, final Event next) {
+ return new Event(EVENT_COMMITTABLE, codePoint, next);
+ }
+
+ public static Event createNotHandledEvent() {
+ return new Event(EVENT_NOT_HANDLED, NOT_A_CODE_POINT, null);
+ }
+
+ public boolean isCommittable() {
+ return EVENT_COMMITTABLE == mType;
+ }
+
+ public boolean isDead() {
+ return EVENT_DEAD == mType;
+ }
+}
diff --git a/java/src/com/android/inputmethod/event/EventDecoder.java b/java/src/com/android/inputmethod/event/EventDecoder.java
new file mode 100644
index 000000000..7ff0166a3
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/EventDecoder.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+/**
+ * A generic interface for event decoders.
+ */
+public interface EventDecoder {
+
+}
diff --git a/java/src/com/android/inputmethod/event/EventDecoderSpec.java b/java/src/com/android/inputmethod/event/EventDecoderSpec.java
new file mode 100644
index 000000000..303b4b4c9
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/EventDecoderSpec.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+/**
+ * Class describing a decoder chain. This will depend on the language and the input medium (soft
+ * or hard keyboard for example).
+ */
+public class EventDecoderSpec {
+ public EventDecoderSpec() {
+ }
+}
diff --git a/java/src/com/android/inputmethod/event/EventInterpreter.java b/java/src/com/android/inputmethod/event/EventInterpreter.java
new file mode 100644
index 000000000..6efe899bb
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/EventInterpreter.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+import android.util.SparseArray;
+import android.view.KeyEvent;
+
+import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
+import com.android.inputmethod.latin.LatinIME;
+
+import java.util.ArrayList;
+
+/**
+ * This class implements the logic between receiving events and generating code points.
+ *
+ * Event sources are multiple. It may be a hardware keyboard, a D-PAD, a software keyboard,
+ * or any exotic input source.
+ * This class will orchestrate the decoding chain that starts with an event and ends up with
+ * a stream of code points + decoding state.
+ */
+public class EventInterpreter {
+ // TODO: Implement an object pool for events, as we'll create a lot of them
+ // TODO: Create a combiner
+ // TODO: Create an object type to represent input material + visual feedback + decoding state
+ // TODO: Create an interface to call back to Latin IME through the above object
+
+ final EventDecoderSpec mDecoderSpec;
+ final SparseArray<HardwareEventDecoder> mHardwareEventDecoders;
+ final SoftwareEventDecoder mSoftwareEventDecoder;
+ final LatinIME mLatinIme;
+ final ArrayList<Combiner> mCombiners;
+
+ /**
+ * Create a default interpreter.
+ *
+ * This creates a default interpreter that does nothing. A default interpreter should normally
+ * only be used for fallback purposes, when we really don't know what we want to do with input.
+ *
+ * @param latinIme a reference to the ime.
+ */
+ public EventInterpreter(final LatinIME latinIme) {
+ this(null, latinIme);
+ }
+
+ /**
+ * Create an event interpreter according to a specification.
+ *
+ * The specification contains information about what to do with events. Typically, it will
+ * contain information about the type of keyboards - for example, if hardware keyboard(s) is/are
+ * attached, their type will be included here so that the decoder knows what to do with each
+ * keypress (a 10-key keyboard is not handled like a qwerty-ish keyboard).
+ * It also contains information for combining characters. For example, if the input language
+ * is Japanese, the specification will typically request kana conversion.
+ * Also note that the specification can be null. This means that we need to create a default
+ * interpreter that does no specific combining, and assumes the most common cases.
+ *
+ * @param specification the specification for event interpretation. null for default.
+ * @param latinIme a reference to the ime.
+ */
+ public EventInterpreter(final EventDecoderSpec specification, final LatinIME latinIme) {
+ mDecoderSpec = null != specification ? specification : new EventDecoderSpec();
+ // For both, we expect to have only one decoder in almost all cases, hence the default
+ // capacity of 1.
+ mHardwareEventDecoders = new SparseArray<HardwareEventDecoder>(1);
+ mSoftwareEventDecoder = new SoftwareKeyboardEventDecoder();
+ mCombiners = CollectionUtils.newArrayList();
+ mCombiners.add(new DeadKeyCombiner());
+ mLatinIme = latinIme;
+ }
+
+ // Helper method to decode a hardware key event into a generic event, and execute any
+ // necessary action.
+ public boolean onHardwareKeyEvent(final KeyEvent hardwareKeyEvent) {
+ final Event decodedEvent = getHardwareKeyEventDecoder(hardwareKeyEvent.getDeviceId())
+ .decodeHardwareKey(hardwareKeyEvent);
+ return onEvent(decodedEvent);
+ }
+
+ public boolean onSoftwareEvent() {
+ final Event decodedEvent = getSoftwareEventDecoder().decodeSoftwareEvent();
+ return onEvent(decodedEvent);
+ }
+
+ private HardwareEventDecoder getHardwareKeyEventDecoder(final int deviceId) {
+ final HardwareEventDecoder decoder = mHardwareEventDecoders.get(deviceId);
+ if (null != decoder) return decoder;
+ // TODO: create the decoder according to the specification
+ final HardwareEventDecoder newDecoder = new HardwareKeyboardEventDecoder(deviceId);
+ mHardwareEventDecoders.put(deviceId, newDecoder);
+ return newDecoder;
+ }
+
+ private SoftwareEventDecoder getSoftwareEventDecoder() {
+ // Within the context of Latin IME, since we never present several software interfaces
+ // at the time, we should never need multiple software event decoders at a time.
+ return mSoftwareEventDecoder;
+ }
+
+ private boolean onEvent(final Event event) {
+ Event currentlyProcessingEvent = event;
+ boolean processed = false;
+ for (int i = 0; i < mCombiners.size(); ++i) {
+ currentlyProcessingEvent = mCombiners.get(i).combine(event);
+ }
+ while (null != currentlyProcessingEvent) {
+ if (currentlyProcessingEvent.isCommittable()) {
+ mLatinIme.onCodeInput(currentlyProcessingEvent.mCodePoint,
+ Constants.EXTERNAL_KEYBOARD_COORDINATE,
+ Constants.EXTERNAL_KEYBOARD_COORDINATE);
+ processed = true;
+ } else if (event.isDead()) {
+ processed = true;
+ }
+ currentlyProcessingEvent = currentlyProcessingEvent.mNextEvent;
+ }
+ return processed;
+ }
+}
diff --git a/java/src/com/android/inputmethod/event/HardwareEventDecoder.java b/java/src/com/android/inputmethod/event/HardwareEventDecoder.java
new file mode 100644
index 000000000..6a6bd7bc5
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/HardwareEventDecoder.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+import android.view.KeyEvent;
+
+/**
+ * An event decoder for hardware events.
+ */
+public interface HardwareEventDecoder extends EventDecoder {
+ public Event decodeHardwareKey(final KeyEvent keyEvent);
+}
diff --git a/java/src/com/android/inputmethod/event/HardwareKeyboardEventDecoder.java b/java/src/com/android/inputmethod/event/HardwareKeyboardEventDecoder.java
new file mode 100644
index 000000000..720d07433
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/HardwareKeyboardEventDecoder.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+import android.view.KeyCharacterMap;
+import android.view.KeyEvent;
+
+import com.android.inputmethod.latin.Constants;
+
+/**
+ * A hardware event decoder for a hardware qwerty-ish keyboard.
+ *
+ * The events are always hardware keypresses, but they can be key down or key up events, they
+ * can be dead keys, they can be meta keys like shift or ctrl... This does not deal with
+ * 10-key like keyboards; a different decoder is used for this.
+ */
+public class HardwareKeyboardEventDecoder implements HardwareEventDecoder {
+ final int mDeviceId;
+
+ public HardwareKeyboardEventDecoder(final int deviceId) {
+ mDeviceId = deviceId;
+ // TODO: get the layout for this hardware keyboard
+ }
+
+ @Override
+ public Event decodeHardwareKey(final KeyEvent keyEvent) {
+ // KeyEvent#getUnicodeChar() does not exactly returns a unicode char, but rather a value
+ // that includes both the unicode char in the lower 21 bits and flags in the upper bits,
+ // hence the name "codePointAndFlags". {@see KeyEvent#getUnicodeChar()} for more info.
+ final int codePointAndFlags = keyEvent.getUnicodeChar();
+ // The keyCode is the abstraction used by the KeyEvent to represent different keys that
+ // do not necessarily map to a unicode character. This represents a physical key, like
+ // the key for 'A' or Space, but also Backspace or Ctrl or Caps Lock.
+ final int keyCode = keyEvent.getKeyCode();
+ if (KeyEvent.KEYCODE_DEL == keyCode) {
+ return Event.createCommittableEvent(Constants.CODE_DELETE, null /* next */);
+ }
+ if (keyEvent.isPrintingKey() || KeyEvent.KEYCODE_SPACE == keyCode
+ || KeyEvent.KEYCODE_ENTER == keyCode) {
+ if (0 != (codePointAndFlags & KeyCharacterMap.COMBINING_ACCENT)) {
+ // A dead key.
+ return Event.createDeadEvent(
+ codePointAndFlags & KeyCharacterMap.COMBINING_ACCENT_MASK, null /* next */);
+ }
+ if (KeyEvent.KEYCODE_ENTER == keyCode) {
+ // The Enter key. If the Shift key is not being pressed, this should send a
+ // CODE_ENTER to trigger the action if any, or a carriage return otherwise. If the
+ // Shift key is being pressed, this should send a CODE_SHIFT_ENTER and let
+ // Latin IME decide what to do with it.
+ return Event.createCommittableEvent(keyEvent.isShiftPressed()
+ ? Constants.CODE_SHIFT_ENTER : Constants.CODE_ENTER,
+ null /* next */);
+ }
+ // If not Enter, then we have a committable character. This should be committed
+ // right away, taking into account the current state.
+ return Event.createCommittableEvent(codePointAndFlags, null /* next */);
+ }
+ return Event.createNotHandledEvent();
+ }
+}
diff --git a/java/src/com/android/inputmethod/event/SoftwareEventDecoder.java b/java/src/com/android/inputmethod/event/SoftwareEventDecoder.java
new file mode 100644
index 000000000..d81ee0b37
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/SoftwareEventDecoder.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+/**
+ * An event decoder for events out of a software keyboard.
+ *
+ * This defines the interface for an event decoder that supports events out of a software keyboard.
+ * This differs significantly from hardware keyboard event decoders in several respects. First,
+ * a software keyboard does not have a scancode/layout system; the keypresses that insert
+ * characters output unicode characters directly.
+ */
+public interface SoftwareEventDecoder extends EventDecoder {
+ public Event decodeSoftwareEvent();
+}
diff --git a/java/src/com/android/inputmethod/event/SoftwareKeyboardEventDecoder.java b/java/src/com/android/inputmethod/event/SoftwareKeyboardEventDecoder.java
new file mode 100644
index 000000000..de91567c7
--- /dev/null
+++ b/java/src/com/android/inputmethod/event/SoftwareKeyboardEventDecoder.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2012 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.event;
+
+/**
+ * A decoder for events from software keyboard, like the ones displayed by Latin IME.
+ */
+public class SoftwareKeyboardEventDecoder implements SoftwareEventDecoder {
+ @Override
+ public Event decodeSoftwareEvent() {
+ return null;
+ }
+}
diff --git a/java/src/com/android/inputmethod/keyboard/Key.java b/java/src/com/android/inputmethod/keyboard/Key.java
index 30812e8c3..d160038ad 100644
--- a/java/src/com/android/inputmethod/keyboard/Key.java
+++ b/java/src/com/android/inputmethod/keyboard/Key.java
@@ -1,26 +1,26 @@
/*
* 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
+ * 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
+ * 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.
+ * 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 static com.android.inputmethod.keyboard.Keyboard.CODE_OUTPUT_TEXT;
-import static com.android.inputmethod.keyboard.Keyboard.CODE_SHIFT;
-import static com.android.inputmethod.keyboard.Keyboard.CODE_SWITCH_ALPHA_SYMBOL;
-import static com.android.inputmethod.keyboard.Keyboard.CODE_UNSPECIFIED;
import static com.android.inputmethod.keyboard.internal.KeyboardIconsSet.ICON_UNDEFINED;
+import static com.android.inputmethod.latin.Constants.CODE_OUTPUT_TEXT;
+import static com.android.inputmethod.latin.Constants.CODE_SHIFT;
+import static com.android.inputmethod.latin.Constants.CODE_SWITCH_ALPHA_SYMBOL;
+import static com.android.inputmethod.latin.Constants.CODE_UNSPECIFIED;
import android.content.res.Resources;
import android.content.res.TypedArray;
@@ -39,8 +39,8 @@ import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.keyboard.internal.KeyboardParams;
import com.android.inputmethod.keyboard.internal.KeyboardRow;
import com.android.inputmethod.keyboard.internal.MoreKeySpec;
+import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.R;
-import com.android.inputmethod.latin.ResourceUtils;
import com.android.inputmethod.latin.StringUtils;
import org.xmlpull.v1.XmlPullParser;
@@ -224,8 +224,8 @@ public class Key implements Comparable<Key> {
public Key(final Resources res, final KeyboardParams params, final KeyboardRow row,
final XmlPullParser parser) throws XmlPullParserException {
final float horizontalGap = isSpacer() ? 0 : params.mHorizontalGap;
- final int keyHeight = row.mRowHeight;
- mHeight = keyHeight - params.mVerticalGap;
+ final int rowHeight = row.mRowHeight;
+ mHeight = rowHeight - params.mVerticalGap;
final TypedArray keyAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
@@ -240,17 +240,18 @@ public class Key implements Comparable<Key> {
mY = keyYPos;
mWidth = Math.round(keyWidth - horizontalGap);
mHitBox.set(Math.round(keyXPos), keyYPos, Math.round(keyXPos + keyWidth) + 1,
- keyYPos + keyHeight);
+ keyYPos + rowHeight);
// Update row to have current x coordinate.
row.setXPos(keyXPos + keyWidth);
mBackgroundType = style.getInt(keyAttr,
R.styleable.Keyboard_Key_backgroundType, row.getDefaultBackgroundType());
- final int visualInsetsLeft = Math.round(ResourceUtils.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_visualInsetsLeft, params.mBaseWidth, 0));
- final int visualInsetsRight = Math.round(ResourceUtils.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_visualInsetsRight, params.mBaseWidth, 0));
+ final int baseWidth = params.mBaseWidth;
+ final int visualInsetsLeft = Math.round(keyAttr.getFraction(
+ R.styleable.Keyboard_Key_visualInsetsLeft, baseWidth, baseWidth, 0));
+ final int visualInsetsRight = Math.round(keyAttr.getFraction(
+ R.styleable.Keyboard_Key_visualInsetsRight, baseWidth, baseWidth, 0));
mIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIcon));
final int disabledIconId = KeySpecParser.getIconId(style.getString(keyAttr,
@@ -453,7 +454,7 @@ public class Key implements Comparable<Key> {
label = "/" + mLabel;
}
return String.format("%s%s %d,%d %dx%d %s/%s/%s",
- Keyboard.printableCode(mCode), label, mX, mY, mWidth, mHeight, mHintLabel,
+ Constants.printableCode(mCode), label, mX, mY, mWidth, mHeight, mHintLabel,
KeyboardIconsSet.getIconName(mIconId), backgroundName(mBackgroundType));
}
@@ -469,11 +470,11 @@ public class Key implements Comparable<Key> {
}
public void markAsLeftEdge(final KeyboardParams params) {
- mHitBox.left = params.mHorizontalEdgesPadding;
+ mHitBox.left = params.mLeftPadding;
}
public void markAsRightEdge(final KeyboardParams params) {
- mHitBox.right = params.mOccupiedWidth - params.mHorizontalEdgesPadding;
+ mHitBox.right = params.mOccupiedWidth - params.mRightPadding;
}
public void markAsTopEdge(final KeyboardParams params) {
@@ -518,11 +519,11 @@ public class Key implements Comparable<Key> {
// TODO: Handle "bold" here too?
if ((mLabelFlags & LABEL_FLAGS_FONT_NORMAL) != 0) {
return Typeface.DEFAULT;
- } else if ((mLabelFlags & LABEL_FLAGS_FONT_MONO_SPACE) != 0) {
+ }
+ if ((mLabelFlags & LABEL_FLAGS_FONT_MONO_SPACE) != 0) {
return Typeface.MONOSPACE;
- } else {
- return params.mTypeface;
}
+ return params.mTypeface;
}
public final int selectTextSize(final KeyDrawParams params) {
@@ -549,28 +550,51 @@ public class Key implements Comparable<Key> {
public final int selectHintTextSize(final KeyDrawParams params) {
if (hasHintLabel()) {
return params.mHintLabelSize;
- } else if (hasShiftedLetterHint()) {
+ }
+ if (hasShiftedLetterHint()) {
return params.mShiftedLetterHintSize;
- } else {
- return params.mHintLetterSize;
}
+ return params.mHintLetterSize;
}
public final int selectHintTextColor(final KeyDrawParams params) {
if (hasHintLabel()) {
return params.mHintLabelColor;
- } else if (hasShiftedLetterHint()) {
+ }
+ if (hasShiftedLetterHint()) {
return isShiftedLetterActivated() ? params.mShiftedLetterHintActivatedColor
: params.mShiftedLetterHintInactivatedColor;
- } else {
- return params.mHintLetterColor;
}
+ return params.mHintLetterColor;
}
public final int selectMoreKeyTextSize(final KeyDrawParams params) {
return hasLabelsInMoreKeys() ? params.mLabelSize : params.mLetterSize;
}
+ public final String getPreviewLabel() {
+ return isShiftedLetterActivated() ? mHintLabel : mLabel;
+ }
+
+ private boolean previewHasLetterSize() {
+ return (mLabelFlags & LABEL_FLAGS_FOLLOW_KEY_LETTER_RATIO) != 0
+ || StringUtils.codePointCount(getPreviewLabel()) == 1;
+ }
+
+ public final int selectPreviewTextSize(final KeyDrawParams params) {
+ if (previewHasLetterSize()) {
+ return params.mPreviewTextSize;
+ }
+ return params.mLetterSize;
+ }
+
+ public Typeface selectPreviewTypeface(final KeyDrawParams params) {
+ if (previewHasLetterSize()) {
+ return selectTypeface(params);
+ }
+ return Typeface.DEFAULT_BOLD;
+ }
+
public final boolean isAlignLeft() {
return (mLabelFlags & LABEL_FLAGS_ALIGN_LEFT) != 0;
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyDetector.java b/java/src/com/android/inputmethod/keyboard/KeyDetector.java
index aa683c1d7..17e707f95 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyDetector.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyDetector.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -118,7 +118,7 @@ public class KeyDetector {
}
public static String printableCode(Key key) {
- return key != null ? Keyboard.printableCode(key.mCode) : "none";
+ return key != null ? Constants.printableCode(key.mCode) : "none";
}
public static String printableCodes(int[] codes) {
@@ -127,7 +127,7 @@ public class KeyDetector {
for (final int code : codes) {
if (code == Constants.NOT_A_CODE) break;
if (addDelimiter) sb.append(", ");
- sb.append(Keyboard.printableCode(code));
+ sb.append(Constants.printableCode(code));
addDelimiter = true;
}
return "[" + sb + "]";
diff --git a/java/src/com/android/inputmethod/keyboard/Keyboard.java b/java/src/com/android/inputmethod/keyboard/Keyboard.java
index b7c7f415d..e87ecbc7e 100644
--- a/java/src/com/android/inputmethod/keyboard/Keyboard.java
+++ b/java/src/com/android/inputmethod/keyboard/Keyboard.java
@@ -1,30 +1,28 @@
/*
* 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
+ * 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
+ * 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.
+ * 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 android.util.SparseArray;
import com.android.inputmethod.keyboard.internal.KeyVisualAttributes;
import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.keyboard.internal.KeyboardParams;
import com.android.inputmethod.latin.CollectionUtils;
-
-
+import com.android.inputmethod.latin.Constants;
/**
* Loads an XML description of a keyboard and stores the attributes of the keys. A keyboard
@@ -32,11 +30,11 @@ import com.android.inputmethod.latin.CollectionUtils;
* <p>The layout file for a keyboard contains XML that looks like the following snippet:</p>
* <pre>
* &lt;Keyboard
- * latin:keyWidth="%10p"
- * latin:keyHeight="50px"
- * latin:horizontalGap="2px"
- * latin:verticalGap="2px" &gt;
- * &lt;Row latin:keyWidth="32px" &gt;
+ * latin:keyWidth="10%p"
+ * latin:rowHeight="50px"
+ * latin:horizontalGap="2%p"
+ * latin:verticalGap="2%p" &gt;
+ * &lt;Row latin:keyWidth="10%p" &gt;
* &lt;Key latin:keyLabel="A" /&gt;
* ...
* &lt;/Row&gt;
@@ -45,46 +43,6 @@ import com.android.inputmethod.latin.CollectionUtils;
* </pre>
*/
public class Keyboard {
- private static final String TAG = Keyboard.class.getSimpleName();
-
- /** Some common keys code. Must be positive.
- * These should be aligned with values/keycodes.xml
- */
- public static final int CODE_ENTER = '\n';
- 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 = '"';
- public static final int CODE_QUESTION_MARK = '?';
- public static final int CODE_EXCLAMATION_MARK = '!';
- // TODO: Check how this should work for right-to-left languages. It seems to stand
- // that for rtl languages, a closing parenthesis is a left parenthesis. Is this
- // managed by the font? Or is it a different char?
- public static final int CODE_CLOSING_PARENTHESIS = ')';
- public static final int CODE_CLOSING_SQUARE_BRACKET = ']';
- public static final int CODE_CLOSING_CURLY_BRACKET = '}';
- public static final int CODE_CLOSING_ANGLE_BRACKET = '>';
-
- /** Special keys code. Must be negative.
- * These should be aligned with KeyboardCodesSet.ID_TO_NAME[],
- * KeyboardCodesSet.DEFAULT[] and KeyboardCodesSet.RTL[]
- */
- public static final int CODE_SHIFT = -1;
- public static final int CODE_SWITCH_ALPHA_SYMBOL = -2;
- public static final int CODE_OUTPUT_TEXT = -3;
- public static final int CODE_DELETE = -4;
- public static final int CODE_SETTINGS = -5;
- public static final int CODE_SHORTCUT = -6;
- public static final int CODE_ACTION_ENTER = -7;
- public static final int CODE_ACTION_NEXT = -8;
- public static final int CODE_ACTION_PREVIOUS = -9;
- public static final int CODE_LANGUAGE_SWITCH = -10;
- public static final int CODE_RESEARCH = -11;
- // Code value representing the code is not specified.
- public static final int CODE_UNSPECIFIED = -12;
-
public final KeyboardId mId;
public final int mThemeId;
@@ -163,7 +121,7 @@ public class Keyboard {
}
public Key getKey(final int code) {
- if (code == CODE_UNSPECIFIED) {
+ if (code == Constants.CODE_UNSPECIFIED) {
return null;
}
synchronized (mKeyCache) {
@@ -197,10 +155,6 @@ public class Keyboard {
return false;
}
- public static boolean isLetterCode(final int code) {
- return code >= CODE_SPACE;
- }
-
@Override
public String toString() {
return mId.toString();
@@ -219,27 +173,4 @@ public class Keyboard {
final int adjustedY = Math.max(0, Math.min(y, mOccupiedHeight - 1));
return mProximityInfo.getNearestKeys(adjustedX, adjustedY);
}
-
- public static String printableCode(final int code) {
- switch (code) {
- case CODE_SHIFT: return "shift";
- case CODE_SWITCH_ALPHA_SYMBOL: return "symbol";
- case CODE_OUTPUT_TEXT: return "text";
- case CODE_DELETE: return "delete";
- case CODE_SETTINGS: return "settings";
- case CODE_SHORTCUT: return "shortcut";
- case CODE_ACTION_ENTER: return "actionEnter";
- case CODE_ACTION_NEXT: return "actionNext";
- case CODE_ACTION_PREVIOUS: return "actionPrevious";
- case CODE_LANGUAGE_SWITCH: return "languageSwitch";
- case CODE_UNSPECIFIED: return "unspec";
- case CODE_TAB: return "tab";
- case CODE_ENTER: return "enter";
- default:
- if (code <= 0) Log.w(TAG, "Unknown non-positive key code=" + code);
- if (code < CODE_SPACE) return String.format("'\\u%02x'", code);
- if (code < 0x100) return String.format("'%c'", code);
- return String.format("'\\u%04x'", code);
- }
- }
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java b/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java
index 5c8f78f5e..c76acd126 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -56,11 +56,11 @@ public interface KeyboardActionListener {
public void onCodeInput(int primaryCode, int x, int y);
/**
- * Sends a sequence of characters to the listener.
+ * Sends a string of characters to the listener.
*
- * @param text the sequence of characters to be displayed.
+ * @param text the string of characters to be registered.
*/
- public void onTextInput(CharSequence text);
+ public void onTextInput(String text);
/**
* Called when user started batch input.
@@ -80,6 +80,8 @@ public interface KeyboardActionListener {
*/
public void onEndBatchInput(InputPointers batchPointers);
+ public void onCancelBatchInput();
+
/**
* Called when user released a finger outside any key.
*/
@@ -99,7 +101,7 @@ public interface KeyboardActionListener {
@Override
public void onCodeInput(int primaryCode, int x, int y) {}
@Override
- public void onTextInput(CharSequence text) {}
+ public void onTextInput(String text) {}
@Override
public void onStartBatchInput() {}
@Override
@@ -107,18 +109,12 @@ public interface KeyboardActionListener {
@Override
public void onEndBatchInput(InputPointers batchPointers) {}
@Override
+ public void onCancelBatchInput() {}
+ @Override
public void onCancelInput() {}
@Override
public boolean onCustomRequest(int requestCode) {
return false;
}
-
- // TODO: Remove this method when the vertical correction is removed.
- public static boolean isInvalidCoordinate(int coordinate) {
- // Detect {@link Constants#NOT_A_COORDINATE},
- // {@link Constants#SUGGESTION_STRIP_COORDINATE}, and
- // {@link Constants#SPELL_CHECKER_COORDINATE}.
- return coordinate < 0;
- }
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardId.java b/java/src/com/android/inputmethod/keyboard/KeyboardId.java
index 5e8a8f6bb..ee8ee9a4f 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardId.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardId.java
@@ -1,23 +1,24 @@
/*
* 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
+ * 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
+ * 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.
+ * 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 static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.KEYBOARD_LAYOUT_SET;
+import android.content.res.Configuration;
import android.text.InputType;
import android.text.TextUtils;
import android.view.inputmethod.EditorInfo;
@@ -59,56 +60,63 @@ public final class KeyboardId {
public static final int FORM_FACTOR_TABLET7 = 1;
public static final int FORM_FACTOR_TABLET10 = 2;
- private static final int IME_ACTION_CUSTOM_LABEL = EditorInfo.IME_MASK_ACTION + 1;
-
public final InputMethodSubtype mSubtype;
public final Locale mLocale;
public final int mDeviceFormFactor;
+ // TODO: Remove this member. It is used only for logging purpose.
public final int mOrientation;
public final int mWidth;
+ public final int mHeight;
public final int mMode;
public final int mElementId;
private final EditorInfo mEditorInfo;
public final boolean mClobberSettingsKey;
public final boolean mShortcutKeyEnabled;
- public final boolean mHasShortcutKey;
+ public final boolean mShortcutKeyOnSymbols;
public final boolean mLanguageSwitchKeyEnabled;
public final String mCustomActionLabel;
+ public final boolean mHasShortcutKey;
private final int mHashCode;
- public KeyboardId(int elementId, InputMethodSubtype subtype, int deviceFormFactor,
- int orientation, int width, int mode, EditorInfo editorInfo, boolean clobberSettingsKey,
- boolean shortcutKeyEnabled, boolean hasShortcutKey, boolean languageSwitchKeyEnabled) {
- mSubtype = subtype;
- mLocale = SubtypeLocale.getSubtypeLocale(subtype);
- mDeviceFormFactor = deviceFormFactor;
- mOrientation = orientation;
- mWidth = width;
- mMode = mode;
+ public KeyboardId(final int elementId, final KeyboardLayoutSet.Params params) {
+ mSubtype = params.mSubtype;
+ mLocale = SubtypeLocale.getSubtypeLocale(mSubtype);
+ mDeviceFormFactor = params.mDeviceFormFactor;
+ mOrientation = params.mOrientation;
+ mWidth = params.mKeyboardWidth;
+ mHeight = params.mKeyboardHeight;
+ mMode = params.mMode;
mElementId = elementId;
- mEditorInfo = editorInfo;
- mClobberSettingsKey = clobberSettingsKey;
- mShortcutKeyEnabled = shortcutKeyEnabled;
- mHasShortcutKey = hasShortcutKey;
- mLanguageSwitchKeyEnabled = languageSwitchKeyEnabled;
- mCustomActionLabel = (editorInfo.actionLabel != null)
- ? editorInfo.actionLabel.toString() : null;
+ mEditorInfo = params.mEditorInfo;
+ mClobberSettingsKey = params.mNoSettingsKey;
+ mShortcutKeyEnabled = params.mVoiceKeyEnabled;
+ mShortcutKeyOnSymbols = mShortcutKeyEnabled && !params.mVoiceKeyOnMain;
+ mLanguageSwitchKeyEnabled = params.mLanguageSwitchKeyEnabled;
+ mCustomActionLabel = (mEditorInfo.actionLabel != null)
+ ? mEditorInfo.actionLabel.toString() : null;
+ final boolean alphabetMayHaveShortcutKey = isAlphabetKeyboard(elementId)
+ && !mShortcutKeyOnSymbols;
+ final boolean symbolsMayHaveShortcutKey = (elementId == KeyboardId.ELEMENT_SYMBOLS)
+ && mShortcutKeyOnSymbols;
+ mHasShortcutKey = mShortcutKeyEnabled
+ && (alphabetMayHaveShortcutKey || symbolsMayHaveShortcutKey);
mHashCode = computeHashCode(this);
}
- private static int computeHashCode(KeyboardId id) {
+ private static int computeHashCode(final KeyboardId id) {
return Arrays.hashCode(new Object[] {
id.mDeviceFormFactor,
id.mOrientation,
id.mElementId,
id.mMode,
id.mWidth,
+ id.mHeight,
id.passwordInput(),
id.mClobberSettingsKey,
id.mShortcutKeyEnabled,
- id.mHasShortcutKey,
+ id.mShortcutKeyOnSymbols,
id.mLanguageSwitchKeyEnabled,
id.isMultiLine(),
id.imeAction(),
@@ -119,7 +127,7 @@ public final class KeyboardId {
});
}
- private boolean equals(KeyboardId other) {
+ private boolean equals(final KeyboardId other) {
if (other == this)
return true;
return other.mDeviceFormFactor == mDeviceFormFactor
@@ -127,10 +135,11 @@ public final class KeyboardId {
&& other.mElementId == mElementId
&& other.mMode == mMode
&& other.mWidth == mWidth
+ && other.mHeight == mHeight
&& other.passwordInput() == passwordInput()
&& other.mClobberSettingsKey == mClobberSettingsKey
&& other.mShortcutKeyEnabled == mShortcutKeyEnabled
- && other.mHasShortcutKey == mHasShortcutKey
+ && other.mShortcutKeyOnSymbols == mShortcutKeyOnSymbols
&& other.mLanguageSwitchKeyEnabled == mLanguageSwitchKeyEnabled
&& other.isMultiLine() == isMultiLine()
&& other.imeAction() == imeAction()
@@ -140,8 +149,12 @@ public final class KeyboardId {
&& other.mSubtype.equals(mSubtype);
}
+ private static boolean isAlphabetKeyboard(final int elementId) {
+ return elementId < ELEMENT_SYMBOLS;
+ }
+
public boolean isAlphabetKeyboard() {
- return mElementId < ELEMENT_SYMBOLS;
+ return isAlphabetKeyboard(mElementId);
}
public boolean navigateNext() {
@@ -165,23 +178,11 @@ public final class KeyboardId {
}
public int imeAction() {
- final int actionId = mEditorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
- if ((mEditorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
- return EditorInfo.IME_ACTION_NONE;
- } else if (mEditorInfo.actionLabel != null) {
- return IME_ACTION_CUSTOM_LABEL;
- } else {
- return actionId;
- }
- }
-
- public int imeActionId() {
- final int actionId = imeAction();
- return actionId == IME_ACTION_CUSTOM_LABEL ? mEditorInfo.actionId : actionId;
+ return InputTypeUtils.getImeOptionsActionIdFromEditorInfo(mEditorInfo);
}
@Override
- public boolean equals(Object other) {
+ public boolean equals(final Object other) {
return other instanceof KeyboardId && equals((KeyboardId) other);
}
@@ -192,11 +193,13 @@ public final class KeyboardId {
@Override
public String toString() {
- return String.format("[%s %s:%s %s-%s:%d %s %s %s%s%s%s%s%s%s%s]",
+ final String orientation = (mOrientation == Configuration.ORIENTATION_PORTRAIT)
+ ? "port" : "land";
+ return String.format("[%s %s:%s %s-%s:%dx%d %s %s %s%s%s%s%s%s%s%s%s]",
elementIdToName(mElementId),
mLocale,
mSubtype.getExtraValueOf(KEYBOARD_LAYOUT_SET),
- deviceFormFactor(mDeviceFormFactor), (mOrientation == 1 ? "port" : "land"), mWidth,
+ deviceFormFactor(mDeviceFormFactor), orientation, mWidth, mHeight,
modeName(mMode),
imeAction(),
(navigateNext() ? "navigateNext" : ""),
@@ -204,13 +207,14 @@ public final class KeyboardId {
(mClobberSettingsKey ? " clobberSettingsKey" : ""),
(passwordInput() ? " passwordInput" : ""),
(mShortcutKeyEnabled ? " shortcutKeyEnabled" : ""),
+ (mShortcutKeyOnSymbols ? " shortcutKeyOnSymbols" : ""),
(mHasShortcutKey ? " hasShortcutKey" : ""),
(mLanguageSwitchKeyEnabled ? " languageSwitchKeyEnabled" : ""),
(isMultiLine() ? "isMultiLine" : "")
);
}
- public static boolean equivalentEditorInfoForKeyboard(EditorInfo a, EditorInfo b) {
+ public static boolean equivalentEditorInfoForKeyboard(final EditorInfo a, final EditorInfo b) {
if (a == null && b == null) return true;
if (a == null || b == null) return false;
return a.inputType == b.inputType
@@ -218,7 +222,7 @@ public final class KeyboardId {
&& TextUtils.equals(a.privateImeOptions, b.privateImeOptions);
}
- public static String elementIdToName(int elementId) {
+ public static String elementIdToName(final int elementId) {
switch (elementId) {
case ELEMENT_ALPHABET: return "alphabet";
case ELEMENT_ALPHABET_MANUAL_SHIFTED: return "alphabetManualShifted";
@@ -234,8 +238,8 @@ public final class KeyboardId {
}
}
- public static String deviceFormFactor(int devoceFormFactor) {
- switch (devoceFormFactor) {
+ public static String deviceFormFactor(final int deviceFormFactor) {
+ switch (deviceFormFactor) {
case FORM_FACTOR_PHONE: return "phone";
case FORM_FACTOR_TABLET7: return "tablet7";
case FORM_FACTOR_TABLET10: return "tablet10";
@@ -243,7 +247,7 @@ public final class KeyboardId {
}
}
- public static String modeName(int mode) {
+ public static String modeName(final int mode) {
switch (mode) {
case MODE_TEXT: return "text";
case MODE_URL: return "url";
@@ -258,8 +262,8 @@ public final class KeyboardId {
}
}
- public static String actionName(int actionId) {
- return (actionId == IME_ACTION_CUSTOM_LABEL) ? "actionCustomLabel"
+ public static String actionName(final int actionId) {
+ return (actionId == InputTypeUtils.IME_ACTION_CUSTOM_LABEL) ? "actionCustomLabel"
: EditorInfoCompatUtils.imeActionName(actionId);
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java b/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java
index c7813ab02..fd9edec70 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -28,12 +28,14 @@ import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.text.InputType;
+import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.Xml;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodSubtype;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.compat.EditorInfoCompatUtils;
import com.android.inputmethod.keyboard.internal.KeyboardBuilder;
import com.android.inputmethod.keyboard.internal.KeyboardParams;
@@ -43,6 +45,7 @@ import com.android.inputmethod.latin.InputAttributes;
import com.android.inputmethod.latin.InputTypeUtils;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.ResourceUtils;
import com.android.inputmethod.latin.SubtypeLocale;
import com.android.inputmethod.latin.SubtypeSwitcher;
import com.android.inputmethod.latin.XmlParseUtils;
@@ -77,6 +80,7 @@ public final class KeyboardLayoutSet {
CollectionUtils.newHashMap();
private static final KeysCache sKeysCache = new KeysCache();
+ @SuppressWarnings("serial")
public static final class KeyboardLayoutSetException extends RuntimeException {
public final KeyboardId mKeyboardId;
@@ -92,7 +96,7 @@ public final class KeyboardLayoutSet {
public ElementParams() {}
}
- private static final class Params {
+ public static final class Params {
String mKeyboardLayoutSetName;
int mMode;
EditorInfo mEditorInfo;
@@ -104,11 +108,11 @@ public final class KeyboardLayoutSet {
InputMethodSubtype mSubtype;
int mDeviceFormFactor;
int mOrientation;
- int mWidth;
+ int mKeyboardWidth;
+ int mKeyboardHeight;
// Sparse array of KeyboardLayoutSet element parameters indexed by element's id.
final SparseArray<ElementParams> mKeyboardLayoutSetElementIdToParamsMap =
CollectionUtils.newSparseArray();
- public Params() {}
}
public static void clearKeyboardCache() {
@@ -148,7 +152,11 @@ public final class KeyboardLayoutSet {
elementParams = mParams.mKeyboardLayoutSetElementIdToParamsMap.get(
KeyboardId.ELEMENT_ALPHABET);
}
- final KeyboardId id = getKeyboardId(keyboardLayoutSetElementId);
+ // Note: The keyboard for each shift state, and mode are represented as an elementName
+ // attribute in a keyboard_layout_set XML file. Also each keyboard layout XML resource is
+ // specified as an elementKeyboard attribute in the file.
+ // The KeyboardId is an internal key for a Keyboard object.
+ final KeyboardId id = new KeyboardId(keyboardLayoutSetElementId, mParams);
try {
return getKeyboard(elementParams, id);
} catch (RuntimeException e) {
@@ -186,23 +194,6 @@ public final class KeyboardLayoutSet {
return keyboard;
}
- // Note: The keyboard for each locale, shift state, and mode are represented as
- // KeyboardLayoutSet element id that is a key in keyboard_set.xml. Also that file specifies
- // which XML layout should be used for each keyboard. The KeyboardId is an internal key for
- // Keyboard object.
- private KeyboardId getKeyboardId(final int keyboardLayoutSetElementId) {
- final Params params = mParams;
- final boolean isSymbols = (keyboardLayoutSetElementId == KeyboardId.ELEMENT_SYMBOLS
- || keyboardLayoutSetElementId == KeyboardId.ELEMENT_SYMBOLS_SHIFTED);
- final boolean noLanguage = SubtypeLocale.isNoLanguage(params.mSubtype);
- final boolean voiceKeyEnabled = params.mVoiceKeyEnabled && !noLanguage;
- final boolean hasShortcutKey = voiceKeyEnabled && (isSymbols != params.mVoiceKeyOnMain);
- return new KeyboardId(keyboardLayoutSetElementId, params.mSubtype, params.mDeviceFormFactor,
- params.mOrientation, params.mWidth, params.mMode, params.mEditorInfo,
- params.mNoSettingsKey, voiceKeyEnabled, hasShortcutKey,
- params.mLanguageSwitchKeyEnabled);
- }
-
public static final class Builder {
private final Context mContext;
private final String mPackageName;
@@ -226,15 +217,43 @@ public final class KeyboardLayoutSet {
mPackageName, NO_SETTINGS_KEY, mEditorInfo);
}
- public Builder setScreenGeometry(final int deviceFormFactor, final int orientation,
- final int widthPixels) {
+ public Builder setScreenGeometry(final int deviceFormFactor, final int widthPixels,
+ final int heightPixels) {
final Params params = mParams;
params.mDeviceFormFactor = deviceFormFactor;
- params.mOrientation = orientation;
- params.mWidth = widthPixels;
+ params.mOrientation = (heightPixels > widthPixels)
+ ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
+ setDefaultKeyboardSize(widthPixels, heightPixels);
return this;
}
+ private void setDefaultKeyboardSize(final int widthPixels, final int heightPixels) {
+ final String keyboardHeightString = ResourceUtils.getDeviceOverrideValue(
+ mResources, R.array.keyboard_heights);
+ final float keyboardHeight;
+ if (TextUtils.isEmpty(keyboardHeightString)) {
+ keyboardHeight = mResources.getDimension(R.dimen.keyboardHeight);
+ } else {
+ keyboardHeight = Float.parseFloat(keyboardHeightString)
+ * mResources.getDisplayMetrics().density;
+ }
+ final float maxKeyboardHeight = mResources.getFraction(
+ R.fraction.maxKeyboardHeight, heightPixels, heightPixels);
+ float minKeyboardHeight = mResources.getFraction(
+ R.fraction.minKeyboardHeight, heightPixels, heightPixels);
+ if (minKeyboardHeight < 0.0f) {
+ // Specified fraction was negative, so it should be calculated against display
+ // width.
+ minKeyboardHeight = -mResources.getFraction(
+ R.fraction.minKeyboardHeight, widthPixels, widthPixels);
+ }
+ // Keyboard height will not exceed maxKeyboardHeight and will not be less than
+ // minKeyboardHeight.
+ mParams.mKeyboardHeight = (int)Math.max(
+ Math.min(keyboardHeight, maxKeyboardHeight), minKeyboardHeight);
+ mParams.mKeyboardWidth = widthPixels;
+ }
+
public Builder setSubtype(final InputMethodSubtype subtype) {
final boolean asciiCapable = subtype.containsExtraValueKey(ASCII_CAPABLE);
@SuppressWarnings("deprecation")
@@ -266,7 +285,7 @@ public final class KeyboardLayoutSet {
return this;
}
- // For test only
+ @UsedForTesting
public void disableTouchPositionCorrectionDataForTest() {
mParams.mDisableTouchPositionCorrectionDataForTest = true;
}
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
index de8097b55..d15f14f88 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2008 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
+ * 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
+ * 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.
+ * 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;
@@ -19,6 +19,8 @@ package com.android.inputmethod.keyboard;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
+import android.preference.PreferenceManager;
+import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
@@ -29,12 +31,13 @@ import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
import com.android.inputmethod.keyboard.KeyboardLayoutSet.KeyboardLayoutSetException;
import com.android.inputmethod.keyboard.PointerTracker.TimerProxy;
import com.android.inputmethod.keyboard.internal.KeyboardState;
-import com.android.inputmethod.latin.DebugSettings;
-import com.android.inputmethod.latin.ImfUtils;
+import com.android.inputmethod.latin.AudioAndHapticFeedbackManager;
import com.android.inputmethod.latin.InputView;
import com.android.inputmethod.latin.LatinIME;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.RichInputMethodManager;
+import com.android.inputmethod.latin.Settings;
import com.android.inputmethod.latin.SettingsValues;
import com.android.inputmethod.latin.SubtypeSwitcher;
import com.android.inputmethod.latin.WordComposer;
@@ -50,7 +53,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
// Note: The themeId should be aligned with "themeId" attribute of Keyboard style
// in values/style.xml.
- public KeyboardTheme(int themeId, int styleId) {
+ public KeyboardTheme(final int themeId, final int styleId) {
mThemeId = themeId;
mStyleId = styleId;
}
@@ -65,9 +68,10 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
new KeyboardTheme(5, R.style.KeyboardTheme_IceCreamSandwich),
};
+ private final AudioAndHapticFeedbackManager mFeedbackManager =
+ AudioAndHapticFeedbackManager.getInstance();
private SubtypeSwitcher mSubtypeSwitcher;
private SharedPreferences mPrefs;
- private boolean mForceNonDistinctMultitouch;
private InputView mCurrentInputView;
private MainKeyboardView mKeyboardView;
@@ -95,22 +99,22 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
// Intentional empty constructor for singleton.
}
- public static void init(LatinIME latinIme, SharedPreferences prefs) {
+ public static void init(final LatinIME latinIme) {
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(latinIme);
sInstance.initInternal(latinIme, prefs);
}
- private void initInternal(LatinIME latinIme, SharedPreferences prefs) {
+ private void initInternal(final LatinIME latinIme, final SharedPreferences prefs) {
mLatinIME = latinIme;
mResources = latinIme.getResources();
mPrefs = prefs;
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mState = new KeyboardState(this);
setContextThemeWrapper(latinIme, getKeyboardTheme(latinIme, prefs));
- mForceNonDistinctMultitouch = prefs.getBoolean(
- DebugSettings.FORCE_NON_DISTINCT_MULTITOUCH_KEY, false);
}
- private static KeyboardTheme getKeyboardTheme(Context context, SharedPreferences prefs) {
+ private static KeyboardTheme getKeyboardTheme(final Context context,
+ final SharedPreferences prefs) {
final String defaultIndex = context.getString(R.string.config_default_keyboard_theme_index);
final String themeIndex = prefs.getString(PREF_KEYBOARD_LAYOUT, defaultIndex);
try {
@@ -125,28 +129,30 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
return KEYBOARD_THEMES[0];
}
- private void setContextThemeWrapper(Context context, KeyboardTheme keyboardTheme) {
- if (mKeyboardTheme.mThemeId != keyboardTheme.mThemeId) {
+ private void setContextThemeWrapper(final Context context, final KeyboardTheme keyboardTheme) {
+ if (mThemeContext == null || mKeyboardTheme.mThemeId != keyboardTheme.mThemeId) {
mKeyboardTheme = keyboardTheme;
mThemeContext = new ContextThemeWrapper(context, keyboardTheme.mStyleId);
KeyboardLayoutSet.clearKeyboardCache();
}
}
- public void loadKeyboard(EditorInfo editorInfo, SettingsValues settingsValues) {
+ public void loadKeyboard(final EditorInfo editorInfo, final SettingsValues settingsValues) {
final KeyboardLayoutSet.Builder builder = new KeyboardLayoutSet.Builder(
mThemeContext, editorInfo);
final Resources res = mThemeContext.getResources();
+ final DisplayMetrics dm = res.getDisplayMetrics();
builder.setScreenGeometry(res.getInteger(R.integer.config_device_form_factor),
- res.getConfiguration().orientation, res.getDisplayMetrics().widthPixels);
+ dm.widthPixels, dm.heightPixels);
builder.setSubtype(mSubtypeSwitcher.getCurrentSubtype());
builder.setOptions(
settingsValues.isVoiceKeyEnabled(editorInfo),
settingsValues.isVoiceKeyOnMain(),
- settingsValues.isLanguageSwitchKeyEnabled(mThemeContext));
+ settingsValues.isLanguageSwitchKeyEnabled());
mKeyboardLayoutSet = builder.build();
try {
- mState.onLoadKeyboard(mResources.getString(R.string.layout_switch_back_symbols));
+ mState.onLoadKeyboard();
+ mFeedbackManager.onSettingsChanged(settingsValues);
} catch (KeyboardLayoutSetException e) {
Log.w(TAG, "loading keyboard failed: " + e.mKeyboardId, e.getCause());
LatinImeLogger.logOnException(e.mKeyboardId.toString(), e.getCause());
@@ -154,6 +160,10 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
}
}
+ public void onRingerModeChanged() {
+ mFeedbackManager.onRingerModeChanged();
+ }
+
public void saveKeyboardState() {
if (getKeyboard() != null) {
mState.onSaveKeyboardState();
@@ -174,8 +184,8 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
keyboardView.setKeyboard(keyboard);
mCurrentInputView.setKeyboardGeometry(keyboard.mTopPadding);
keyboardView.setKeyPreviewPopupEnabled(
- SettingsValues.isKeyPreviewPopupEnabled(mPrefs, mResources),
- SettingsValues.getKeyPreviewPopupDismissDelay(mPrefs, mResources));
+ Settings.readKeyPreviewPopupEnabled(mPrefs, mResources),
+ Settings.readKeyPreviewPopupDismissDelay(mPrefs, mResources));
keyboardView.updateAutoCorrectionState(mIsAutoCorrectionActive);
keyboardView.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady());
final boolean subtypeChanged = (oldKeyboard == null)
@@ -183,7 +193,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
final boolean needsToDisplayLanguage = mSubtypeSwitcher.needsToDisplayLanguage(
keyboard.mId.mLocale);
keyboardView.startDisplayLanguageOnSpacebar(subtypeChanged, needsToDisplayLanguage,
- ImfUtils.hasMultipleEnabledIMEsOrSubtypes(mLatinIME, true));
+ RichInputMethodManager.getInstance().hasMultipleEnabledIMEsOrSubtypes(true));
}
public Keyboard getKeyboard() {
@@ -206,14 +216,14 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
mState.onResetKeyboardStateToAlphabet();
}
- public void onPressKey(int code) {
+ public void onPressKey(final int code) {
if (isVibrateAndSoundFeedbackRequired()) {
- mLatinIME.hapticAndAudioFeedback(code);
+ mFeedbackManager.hapticAndAudioFeedback(code, mKeyboardView);
}
mState.onPressKey(code, isSinglePointer(), mLatinIME.getCurrentAutoCapsState());
}
- public void onReleaseKey(int code, boolean withSliding) {
+ public void onReleaseKey(final int code, final boolean withSliding) {
mState.onReleaseKey(code, withSliding);
}
@@ -299,7 +309,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
// Implements {@link KeyboardState.SwitchActions}.
@Override
- public void startLongPressTimer(int code) {
+ public void startLongPressTimer(final int code) {
final MainKeyboardView keyboardView = getMainKeyboardView();
if (keyboardView != null) {
final TimerProxy timer = keyboardView.getTimerProxy();
@@ -319,11 +329,11 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
// Implements {@link KeyboardState.SwitchActions}.
@Override
- public void hapticAndAudioFeedback(int code) {
- mLatinIME.hapticAndAudioFeedback(code);
+ public void hapticAndAudioFeedback(final int code) {
+ mFeedbackManager.hapticAndAudioFeedback(code, mKeyboardView);
}
- public void onLongPressTimeout(int code) {
+ public void onLongPressTimeout(final int code) {
mState.onLongPressTimeout(code);
}
@@ -339,14 +349,10 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
return mKeyboardView != null && mKeyboardView.getPointerCount() == 1;
}
- public boolean hasDistinctMultitouch() {
- return mKeyboardView != null && mKeyboardView.hasDistinctMultitouch();
- }
-
/**
* Updates state machine to figure out when to automatically switch back to the previous mode.
*/
- public void onCodeInput(int code) {
+ public void onCodeInput(final int code) {
mState.onCodeInput(code, isSinglePointer(), mLatinIME.getCurrentAutoCapsState());
}
@@ -354,7 +360,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
return mKeyboardView;
}
- public View onCreateInputView(boolean isHardwareAcceleratedDrawingEnabled) {
+ public View onCreateInputView(final boolean isHardwareAcceleratedDrawingEnabled) {
if (mKeyboardView != null) {
mKeyboardView.closing();
}
@@ -369,9 +375,6 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
// TODO: Should use LAYER_TYPE_SOFTWARE when hardware acceleration is off?
}
mKeyboardView.setKeyboardActionListener(mLatinIME);
- if (mForceNonDistinctMultitouch) {
- mKeyboardView.setDistinctMultitouch(false);
- }
// This always needs to be set since the accessibility state can
// potentially change without the input view being re-created.
@@ -386,7 +389,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
}
}
- public void onAutoCorrectionStateChanged(boolean isAutoCorrection) {
+ public void onAutoCorrectionStateChanged(final boolean isAutoCorrection) {
if (mIsAutoCorrectionActive != isAutoCorrection) {
mIsAutoCorrectionActive = isAutoCorrection;
if (mKeyboardView != null) {
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardView.java b/java/src/com/android/inputmethod/keyboard/KeyboardView.java
index 472f74b12..350dc69b2 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardView.java
@@ -28,27 +28,16 @@ import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
-import android.os.Message;
import android.util.AttributeSet;
-import android.util.DisplayMetrics;
-import android.util.Log;
import android.util.SparseArray;
-import android.util.TypedValue;
-import android.view.LayoutInflater;
import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
import com.android.inputmethod.keyboard.internal.KeyDrawParams;
-import com.android.inputmethod.keyboard.internal.KeyPreviewDrawParams;
import com.android.inputmethod.keyboard.internal.KeyVisualAttributes;
-import com.android.inputmethod.keyboard.internal.PreviewPlacerView;
import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
-import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
-import com.android.inputmethod.latin.StringUtils;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.research.ResearchLogger;
@@ -58,30 +47,11 @@ import java.util.HashSet;
* A view that renders a virtual {@link Keyboard}.
*
* @attr ref R.styleable#KeyboardView_keyBackground
- * @attr ref R.styleable#KeyboardView_moreKeysLayout
- * @attr ref R.styleable#KeyboardView_keyPreviewLayout
- * @attr ref R.styleable#KeyboardView_keyPreviewOffset
- * @attr ref R.styleable#KeyboardView_keyPreviewHeight
- * @attr ref R.styleable#KeyboardView_keyPreviewLingerTimeout
* @attr ref R.styleable#KeyboardView_keyLabelHorizontalPadding
* @attr ref R.styleable#KeyboardView_keyHintLetterPadding
* @attr ref R.styleable#KeyboardView_keyPopupHintLetterPadding
* @attr ref R.styleable#KeyboardView_keyShiftedLetterHintPadding
* @attr ref R.styleable#KeyboardView_keyTextShadowRadius
- * @attr ref R.styleable#KeyboardView_backgroundDimAlpha
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextSize
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextColor
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextOffset
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewColor
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewHorizontalPadding
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewVerticalPadding
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewRoundRadius
- * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextLingerTimeout
- * @attr ref R.styleable#KeyboardView_gesturePreviewTrailFadeoutStartDelay
- * @attr ref R.styleable#KeyboardView_gesturePreviewTrailFadeoutDuration
- * @attr ref R.styleable#KeyboardView_gesturePreviewTrailUpdateInterval
- * @attr ref R.styleable#KeyboardView_gesturePreviewTrailColor
- * @attr ref R.styleable#KeyboardView_gesturePreviewTrailWidth
* @attr ref R.styleable#KeyboardView_verticalCorrection
* @attr ref R.styleable#Keyboard_Key_keyTypeface
* @attr ref R.styleable#Keyboard_Key_keyLetterSize
@@ -101,9 +71,7 @@ import java.util.HashSet;
* @attr ref R.styleable#Keyboard_Key_keyShiftedLetterHintActivatedColor
* @attr ref R.styleable#Keyboard_Key_keyPreviewTextColor
*/
-public class KeyboardView extends View implements PointerTracker.DrawingProxy {
- private static final String TAG = KeyboardView.class.getSimpleName();
-
+public class KeyboardView extends View {
// XML attributes
protected final KeyVisualAttributes mKeyVisualAttributes;
private final int mKeyLabelHorizontalPadding;
@@ -112,10 +80,8 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
private final float mKeyShiftedLetterHintPadding;
private final float mKeyTextShadowRadius;
protected final float mVerticalCorrection;
- protected final int mMoreKeysLayout;
protected final Drawable mKeyBackground;
protected final Rect mKeyBackgroundPadding = new Rect();
- private final int mBackgroundDimAlpha;
// HORIZONTAL ELLIPSIS "...", character for popup hint.
private static final String POPUP_HINT_CHAR = "\u2026";
@@ -132,46 +98,7 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
private Keyboard mKeyboard;
protected final KeyDrawParams mKeyDrawParams = new KeyDrawParams();
- // Preview placer view
- private final PreviewPlacerView mPreviewPlacerView;
- private final int[] mCoordinates = new int[2];
-
- // Key preview
- private static final int PREVIEW_ALPHA = 240;
- private final int mKeyPreviewLayoutId;
- private final int mPreviewOffset;
- private final int mPreviewHeight;
- private final int mPreviewLingerTimeout;
- private final SparseArray<TextView> mKeyPreviewTexts = CollectionUtils.newSparseArray();
- protected final KeyPreviewDrawParams mKeyPreviewDrawParams = new KeyPreviewDrawParams();
- private boolean mShowKeyPreviewPopup = true;
- private int mDelayAfterPreview;
- // Background state set
- private static final int[][][] KEY_PREVIEW_BACKGROUND_STATE_TABLE = {
- { // STATE_MIDDLE
- EMPTY_STATE_SET,
- { R.attr.state_has_morekeys }
- },
- { // STATE_LEFT
- { R.attr.state_left_edge },
- { R.attr.state_left_edge, R.attr.state_has_morekeys }
- },
- { // STATE_RIGHT
- { R.attr.state_right_edge },
- { R.attr.state_right_edge, R.attr.state_has_morekeys }
- }
- };
- private static final int STATE_MIDDLE = 0;
- private static final int STATE_LEFT = 1;
- private static final int STATE_RIGHT = 2;
- private static final int STATE_NORMAL = 0;
- private static final int STATE_HAS_MOREKEYS = 1;
- private static final int[] KEY_PREVIEW_BACKGROUND_DEFAULT_STATE =
- KEY_PREVIEW_BACKGROUND_STATE_TABLE[STATE_MIDDLE][STATE_NORMAL];
-
// Drawing
- /** True if the entire keyboard needs to be dimmed. */
- private boolean mNeedsToDimEntireKeyboard;
/** True if all keys should be drawn */
private boolean mInvalidateAllKeys;
/** The keys that should be drawn */
@@ -193,47 +120,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
private static final char[] KEY_LABEL_REFERENCE_CHAR = { 'M' };
private static final char[] KEY_NUMERIC_HINT_LABEL_REFERENCE_CHAR = { '8' };
- private final DrawingHandler mDrawingHandler = new DrawingHandler(this);
-
- public static class DrawingHandler extends StaticInnerHandlerWrapper<KeyboardView> {
- private static final int MSG_DISMISS_KEY_PREVIEW = 0;
-
- public DrawingHandler(final KeyboardView outerInstance) {
- super(outerInstance);
- }
-
- @Override
- public void handleMessage(final Message msg) {
- final KeyboardView keyboardView = getOuterInstance();
- if (keyboardView == null) return;
- final PointerTracker tracker = (PointerTracker) msg.obj;
- switch (msg.what) {
- case MSG_DISMISS_KEY_PREVIEW:
- final TextView previewText = keyboardView.mKeyPreviewTexts.get(tracker.mPointerId);
- if (previewText != null) {
- previewText.setVisibility(INVISIBLE);
- }
- break;
- }
- }
-
- public void dismissKeyPreview(final long delay, final PointerTracker tracker) {
- sendMessageDelayed(obtainMessage(MSG_DISMISS_KEY_PREVIEW, tracker), delay);
- }
-
- public void cancelDismissKeyPreview(final PointerTracker tracker) {
- removeMessages(MSG_DISMISS_KEY_PREVIEW, tracker);
- }
-
- private void cancelAllDismissKeyPreviews() {
- removeMessages(MSG_DISMISS_KEY_PREVIEW);
- }
-
- public void cancelAllMessages() {
- cancelAllDismissKeyPreviews();
- }
- }
-
public KeyboardView(final Context context, final AttributeSet attrs) {
this(context, attrs, R.attr.keyboardViewStyle);
}
@@ -245,13 +131,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
R.styleable.KeyboardView, defStyle, R.style.KeyboardView);
mKeyBackground = keyboardViewAttr.getDrawable(R.styleable.KeyboardView_keyBackground);
mKeyBackground.getPadding(mKeyBackgroundPadding);
- mPreviewOffset = keyboardViewAttr.getDimensionPixelOffset(
- R.styleable.KeyboardView_keyPreviewOffset, 0);
- mPreviewHeight = keyboardViewAttr.getDimensionPixelSize(
- R.styleable.KeyboardView_keyPreviewHeight, 80);
- mPreviewLingerTimeout = keyboardViewAttr.getInt(
- R.styleable.KeyboardView_keyPreviewLingerTimeout, 0);
- mDelayAfterPreview = mPreviewLingerTimeout;
mKeyLabelHorizontalPadding = keyboardViewAttr.getDimensionPixelOffset(
R.styleable.KeyboardView_keyLabelHorizontalPadding, 0);
mKeyHintLetterPadding = keyboardViewAttr.getDimension(
@@ -262,17 +141,8 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
R.styleable.KeyboardView_keyShiftedLetterHintPadding, 0);
mKeyTextShadowRadius = keyboardViewAttr.getFloat(
R.styleable.KeyboardView_keyTextShadowRadius, 0.0f);
- mKeyPreviewLayoutId = keyboardViewAttr.getResourceId(
- R.styleable.KeyboardView_keyPreviewLayout, 0);
- if (mKeyPreviewLayoutId == 0) {
- mShowKeyPreviewPopup = false;
- }
mVerticalCorrection = keyboardViewAttr.getDimension(
R.styleable.KeyboardView_verticalCorrection, 0);
- mMoreKeysLayout = keyboardViewAttr.getResourceId(
- R.styleable.KeyboardView_moreKeysLayout, 0);
- mBackgroundDimAlpha = keyboardViewAttr.getInt(
- R.styleable.KeyboardView_backgroundDimAlpha, 0);
keyboardViewAttr.recycle();
final TypedArray keyAttr = context.obtainStyledAttributes(attrs,
@@ -280,7 +150,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
mKeyVisualAttributes = KeyVisualAttributes.newInstance(keyAttr);
keyAttr.recycle();
- mPreviewPlacerView = new PreviewPlacerView(context, attrs);
mPaint.setAntiAlias(true);
}
@@ -300,11 +169,11 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
public void setKeyboard(final Keyboard keyboard) {
mKeyboard = keyboard;
LatinImeLogger.onSetKeyboard(keyboard);
- requestLayout();
- invalidateAllKeys();
final int keyHeight = keyboard.mMostCommonKeyHeight - keyboard.mVerticalGap;
mKeyDrawParams.updateParams(keyHeight, mKeyVisualAttributes);
mKeyDrawParams.updateParams(keyHeight, keyboard.mKeyVisualAttributes);
+ invalidateAllKeys();
+ requestLayout();
}
/**
@@ -316,33 +185,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
return mKeyboard;
}
- /**
- * 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 preview
- * @param delay the delay after which the preview is dismissed
- * @see #isKeyPreviewPopupEnabled()
- */
- public void setKeyPreviewPopupEnabled(final boolean previewEnabled, final int delay) {
- mShowKeyPreviewPopup = previewEnabled;
- mDelayAfterPreview = delay;
- }
-
- /**
- * 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 isKeyPreviewPopupEnabled() {
- return mShowKeyPreviewPopup;
- }
-
- public void setGesturePreviewMode(final boolean drawsGesturePreviewTrail,
- final boolean drawsGestureFloatingPreviewText) {
- mPreviewPlacerView.setGesturePreviewMode(
- drawsGesturePreviewTrail, drawsGestureFloatingPreviewText);
- }
-
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
if (mKeyboard != null) {
@@ -355,7 +197,7 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
}
@Override
- public void onDraw(final Canvas canvas) {
+ protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
if (canvas.isHardwareAccelerated()) {
onDrawKeyboard(canvas);
@@ -445,14 +287,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
}
}
- // Overlay a dark rectangle to dim.
- if (mNeedsToDimEntireKeyboard) {
- paint.setColor(Color.BLACK);
- paint.setAlpha(mBackgroundDimAlpha);
- // Note: clipRegion() above is in effect if it was called.
- canvas.drawRect(0, 0, width, height, paint);
- }
-
// ResearchLogging indicator.
// TODO: Reimplement using a keyboard background image specific to the ResearchLogger,
// and remove this call.
@@ -464,14 +298,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
mInvalidateAllKeys = false;
}
- public void dimEntireKeyboard(final boolean dimmed) {
- final boolean needsRedrawing = mNeedsToDimEntireKeyboard != dimmed;
- mNeedsToDimEntireKeyboard = dimmed;
- if (needsRedrawing) {
- invalidateAllKeys();
- }
- }
-
private void onDrawKey(final Key key, final Canvas canvas, final Paint paint) {
final int keyDrawX = key.getDrawX() + getPaddingLeft();
final int keyDrawY = key.mY + getPaddingTop();
@@ -781,188 +607,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
return paint;
}
- public void cancelAllMessages() {
- mDrawingHandler.cancelAllMessages();
- }
-
- private TextView getKeyPreviewText(final int pointerId) {
- TextView previewText = mKeyPreviewTexts.get(pointerId);
- if (previewText != null) {
- return previewText;
- }
- final Context context = getContext();
- if (mKeyPreviewLayoutId != 0) {
- previewText = (TextView)LayoutInflater.from(context).inflate(mKeyPreviewLayoutId, null);
- } else {
- previewText = new TextView(context);
- }
- mKeyPreviewTexts.put(pointerId, previewText);
- return previewText;
- }
-
- private void dismissAllKeyPreviews() {
- final int pointerCount = mKeyPreviewTexts.size();
- for (int id = 0; id < pointerCount; id++) {
- final TextView previewText = mKeyPreviewTexts.get(id);
- if (previewText != null) {
- previewText.setVisibility(INVISIBLE);
- }
- }
- PointerTracker.setReleasedKeyGraphicsToAllKeys();
- }
-
- @Override
- public void dismissKeyPreview(final PointerTracker tracker) {
- mDrawingHandler.dismissKeyPreview(mDelayAfterPreview, tracker);
- }
-
- private void addKeyPreview(final TextView keyPreview) {
- locatePreviewPlacerView();
- mPreviewPlacerView.addView(
- keyPreview, ViewLayoutUtils.newLayoutParam(mPreviewPlacerView, 0, 0));
- }
-
- private void locatePreviewPlacerView() {
- if (mPreviewPlacerView.getParent() != null) {
- return;
- }
- final int width = getWidth();
- final int height = getHeight();
- if (width == 0 || height == 0) {
- // In transient state.
- return;
- }
- final int[] viewOrigin = new int[2];
- getLocationInWindow(viewOrigin);
- final DisplayMetrics dm = getResources().getDisplayMetrics();
- if (viewOrigin[1] < dm.heightPixels / 4) {
- // In transient state.
- return;
- }
- final View rootView = getRootView();
- if (rootView == null) {
- Log.w(TAG, "Cannot find root view");
- return;
- }
- final ViewGroup windowContentView = (ViewGroup)rootView.findViewById(android.R.id.content);
- // Note: It'd be very weird if we get null by android.R.id.content.
- if (windowContentView == null) {
- Log.w(TAG, "Cannot find android.R.id.content view to add PreviewPlacerView");
- } else {
- windowContentView.addView(mPreviewPlacerView);
- mPreviewPlacerView.setKeyboardViewGeometry(viewOrigin[0], viewOrigin[1], width, height);
- }
- }
-
- public void showGestureFloatingPreviewText(final String gestureFloatingPreviewText) {
- locatePreviewPlacerView();
- mPreviewPlacerView.setGestureFloatingPreviewText(gestureFloatingPreviewText);
- }
-
- public void dismissGestureFloatingPreviewText() {
- locatePreviewPlacerView();
- mPreviewPlacerView.dismissGestureFloatingPreviewText();
- }
-
- @Override
- public void showGesturePreviewTrail(final PointerTracker tracker,
- final boolean isOldestTracker) {
- locatePreviewPlacerView();
- mPreviewPlacerView.invalidatePointer(tracker, isOldestTracker);
- }
-
- @Override
- public void showKeyPreview(final PointerTracker tracker) {
- final KeyPreviewDrawParams previewParams = mKeyPreviewDrawParams;
- if (!mShowKeyPreviewPopup) {
- previewParams.mPreviewVisibleOffset = -mKeyboard.mVerticalGap;
- return;
- }
-
- final TextView previewText = getKeyPreviewText(tracker.mPointerId);
- // 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);
- }
-
- mDrawingHandler.cancelDismissKeyPreview(tracker);
- final Key key = tracker.getKey();
- // If key is invalid or IME is already closed, we must not show key preview.
- // Trying to show key preview while root window is closed causes
- // WindowManager.BadTokenException.
- if (key == null) {
- return;
- }
-
- final KeyDrawParams drawParams = mKeyDrawParams;
- previewText.setTextColor(drawParams.mPreviewTextColor);
- final Drawable background = previewText.getBackground();
- if (background != null) {
- background.setState(KEY_PREVIEW_BACKGROUND_DEFAULT_STATE);
- background.setAlpha(PREVIEW_ALPHA);
- }
- final String label = key.isShiftedLetterActivated() ? key.mHintLabel : key.mLabel;
- // What we show as preview should match what we show on a key top in onDraw().
- if (label != null) {
- // TODO Should take care of temporaryShiftLabel here.
- previewText.setCompoundDrawables(null, null, null, null);
- if (StringUtils.codePointCount(label) > 1) {
- previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, drawParams.mLetterSize);
- previewText.setTypeface(Typeface.DEFAULT_BOLD);
- } else {
- previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, drawParams.mPreviewTextSize);
- previewText.setTypeface(key.selectTypeface(drawParams));
- }
- previewText.setText(label);
- } else {
- previewText.setCompoundDrawables(null, null, null,
- key.getPreviewIcon(mKeyboard.mIconsSet));
- previewText.setText(null);
- }
-
- previewText.measure(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- final int keyDrawWidth = key.getDrawWidth();
- final int previewWidth = previewText.getMeasuredWidth();
- final int previewHeight = mPreviewHeight;
- // The width and height of visible part of the key preview background. The content marker
- // of the background 9-patch have to cover the visible part of the background.
- previewParams.mPreviewVisibleWidth = previewWidth - previewText.getPaddingLeft()
- - previewText.getPaddingRight();
- previewParams.mPreviewVisibleHeight = previewHeight - previewText.getPaddingTop()
- - previewText.getPaddingBottom();
- // The distance between the top edge of the parent key and the bottom of the visible part
- // of the key preview background.
- previewParams.mPreviewVisibleOffset = mPreviewOffset - previewText.getPaddingBottom();
- getLocationInWindow(mCoordinates);
- // The key preview is horizontally aligned with the center of the visible part of the
- // parent key. If it doesn't fit in this {@link KeyboardView}, it is moved inward to fit and
- // the left/right background is used if such background is specified.
- final int statePosition;
- int previewX = key.getDrawX() - (previewWidth - keyDrawWidth) / 2 + mCoordinates[0];
- if (previewX < 0) {
- previewX = 0;
- statePosition = STATE_LEFT;
- } else if (previewX > getWidth() - previewWidth) {
- previewX = getWidth() - previewWidth;
- statePosition = STATE_RIGHT;
- } else {
- statePosition = STATE_MIDDLE;
- }
- // The key preview is placed vertically above the top edge of the parent key with an
- // arbitrary offset.
- final int previewY = key.mY - previewHeight + mPreviewOffset + mCoordinates[1];
-
- if (background != null) {
- final int hasMoreKeys = (key.mMoreKeys != null) ? STATE_HAS_MOREKEYS : STATE_NORMAL;
- background.setState(KEY_PREVIEW_BACKGROUND_STATE_TABLE[statePosition][hasMoreKeys]);
- }
- ViewLayoutUtils.placeViewAt(
- previewText, previewX, previewY, previewWidth, previewHeight);
- previewText.setVisibility(VISIBLE);
- }
-
/**
* Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient
* because the keyboard renders the keys to an off-screen buffer and an invalidate() only
@@ -982,7 +626,6 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
* @param key key in the attached {@link Keyboard}.
* @see #invalidateAllKeys
*/
- @Override
public void invalidateKey(final Key key) {
if (mInvalidateAllKeys) return;
if (key == null) return;
@@ -992,29 +635,9 @@ public class KeyboardView extends View implements PointerTracker.DrawingProxy {
invalidate(x, y, x + key.mWidth, y + key.mHeight);
}
- public void closing() {
- dismissAllKeyPreviews();
- cancelAllMessages();
-
- mInvalidateAllKeys = true;
- requestLayout();
- }
-
- @Override
- public boolean dismissMoreKeysPanel() {
- return false;
- }
-
- public void purgeKeyboardAndClosing() {
- mKeyboard = null;
- closing();
- }
-
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
- closing();
- mPreviewPlacerView.removeAllViews();
freeOffscreenBuffer();
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
index 3e6f92c2a..d37b69b00 100644
--- a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
@@ -19,40 +19,57 @@ package com.android.inputmethod.keyboard;
import android.animation.AnimatorInflater;
import android.animation.ObjectAnimator;
import android.content.Context;
+import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
+import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Message;
-import android.text.TextUtils;
+import android.os.SystemClock;
+import android.preference.PreferenceManager;
import android.util.AttributeSet;
+import android.util.DisplayMetrics;
import android.util.Log;
+import android.util.SparseArray;
+import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodSubtype;
-import android.widget.PopupWindow;
+import android.widget.TextView;
import com.android.inputmethod.accessibility.AccessibilityUtils;
import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
+import com.android.inputmethod.annotations.ExternallyReferenced;
import com.android.inputmethod.keyboard.PointerTracker.DrawingProxy;
import com.android.inputmethod.keyboard.PointerTracker.TimerProxy;
+import com.android.inputmethod.keyboard.internal.GestureFloatingPreviewText;
+import com.android.inputmethod.keyboard.internal.GestureTrailsPreview;
import com.android.inputmethod.keyboard.internal.KeyDrawParams;
-import com.android.inputmethod.keyboard.internal.SuddenJumpingTouchEventHandler;
+import com.android.inputmethod.keyboard.internal.KeyPreviewDrawParams;
+import com.android.inputmethod.keyboard.internal.PreviewPlacerView;
+import com.android.inputmethod.keyboard.internal.SlidingKeyInputPreview;
+import com.android.inputmethod.keyboard.internal.TouchScreenRegulator;
+import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.Constants;
+import com.android.inputmethod.latin.CoordinateUtils;
+import com.android.inputmethod.latin.DebugSettings;
import com.android.inputmethod.latin.LatinIME;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.ResourceUtils;
+import com.android.inputmethod.latin.Settings;
import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
import com.android.inputmethod.latin.StringUtils;
import com.android.inputmethod.latin.SubtypeLocale;
+import com.android.inputmethod.latin.SuggestedWords;
import com.android.inputmethod.latin.Utils.UsabilityStudyLogUtils;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.research.ResearchLogger;
@@ -81,7 +98,14 @@ import java.util.WeakHashMap;
* @attr ref R.styleable#MainKeyboardView_longPressKeyTimeout
* @attr ref R.styleable#MainKeyboardView_longPressShiftKeyTimeout
* @attr ref R.styleable#MainKeyboardView_ignoreAltCodeKeyTimeout
+ * @attr ref R.styleable#MainKeyboardView_keyPreviewLayout
+ * @attr ref R.styleable#MainKeyboardView_keyPreviewOffset
+ * @attr ref R.styleable#MainKeyboardView_keyPreviewHeight
+ * @attr ref R.styleable#MainKeyboardView_keyPreviewLingerTimeout
+ * @attr ref R.styleable#MainKeyboardView_moreKeysKeyboardLayout
+ * @attr ref R.styleable#MainKeyboardView_backgroundDimAlpha
* @attr ref R.styleable#MainKeyboardView_showMoreKeysKeyboardAtTouchPoint
+ * @attr ref R.styleable#MainKeyboardView_gestureFloatingPreviewTextLingerTimeout
* @attr ref R.styleable#MainKeyboardView_gestureStaticTimeThresholdAfterFastTyping
* @attr ref R.styleable#MainKeyboardView_gestureDetectFastMoveSpeedThreshold
* @attr ref R.styleable#MainKeyboardView_gestureDynamicThresholdDecayDuration
@@ -95,7 +119,8 @@ import java.util.WeakHashMap;
* @attr ref R.styleable#MainKeyboardView_suppressKeyPreviewAfterBatchInputDuration
*/
public final class MainKeyboardView extends KeyboardView implements PointerTracker.KeyEventHandler,
- SuddenJumpingTouchEventHandler.ProcessMotionEvent {
+ PointerTracker.DrawingProxy, MoreKeysPanel.Controller,
+ TouchScreenRegulator.ProcessMotionEvent {
private static final String TAG = MainKeyboardView.class.getSimpleName();
// TODO: Kill process when the usability study mode was changed.
@@ -130,18 +155,42 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
private ObjectAnimator mAltCodeKeyWhileTypingFadeinAnimator;
private int mAltCodeKeyWhileTypingAnimAlpha = Constants.Color.ALPHA_OPAQUE;
+ // Preview placer view
+ private final PreviewPlacerView mPreviewPlacerView;
+ private final int[] mOriginCoords = CoordinateUtils.newInstance();
+ private final GestureFloatingPreviewText mGestureFloatingPreviewText;
+ private final GestureTrailsPreview mGestureTrailsPreview;
+ private final SlidingKeyInputPreview mSlidingKeyInputPreview;
+
+ // Key preview
+ private static final int PREVIEW_ALPHA = 240;
+ private final int mKeyPreviewLayoutId;
+ private final int mKeyPreviewOffset;
+ private final int mKeyPreviewHeight;
+ private final SparseArray<TextView> mKeyPreviewTexts = CollectionUtils.newSparseArray();
+ private final KeyPreviewDrawParams mKeyPreviewDrawParams = new KeyPreviewDrawParams();
+ private boolean mShowKeyPreviewPopup = true;
+ private int mKeyPreviewLingerTimeout;
+
// More keys keyboard
- private PopupWindow mMoreKeysWindow;
- private MoreKeysPanel mMoreKeysPanel;
- private int mMoreKeysPanelPointerTrackerId;
- private final WeakHashMap<Key, MoreKeysPanel> mMoreKeysPanelCache =
- new WeakHashMap<Key, MoreKeysPanel>();
+ private final Paint mBackgroundDimAlphaPaint = new Paint();
+ private boolean mNeedsToDimEntireKeyboard;
+ private final View mMoreKeysKeyboardContainer;
+ private final WeakHashMap<Key, Keyboard> mMoreKeysKeyboardCache =
+ CollectionUtils.newWeakHashMap();
private final boolean mConfigShowMoreKeysKeyboardAtTouchedPoint;
+ // More keys panel (used by both more keys keyboard and more suggestions view)
+ // TODO: Consider extending to support multiple more keys panels
+ private MoreKeysPanel mMoreKeysPanel;
+
+ // Gesture floating preview text
+ // TODO: Make this parameter customizable by user via settings.
+ private int mGestureFloatingPreviewTextLingerTimeout;
- private final SuddenJumpingTouchEventHandler mTouchScreenRegulator;
+ private final TouchScreenRegulator mTouchScreenRegulator;
- protected KeyDetector mKeyDetector;
- private boolean mHasDistinctMultitouch;
+ private KeyDetector mKeyDetector;
+ private final boolean mHasDistinctMultitouch;
private int mOldPointerCount = 1;
private Key mOldKey;
@@ -153,12 +202,13 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
private static final int MSG_REPEAT_KEY = 1;
private static final int MSG_LONGPRESS_KEY = 2;
private static final int MSG_DOUBLE_TAP = 3;
+ private static final int MSG_UPDATE_BATCH_INPUT = 4;
private final int mKeyRepeatStartTimeout;
private final int mKeyRepeatInterval;
- private final int mLongPressKeyTimeout;
- private final int mLongPressShiftKeyTimeout;
+ private final int mLongPressShiftLockTimeout;
private final int mIgnoreAltCodeKeyTimeout;
+ private final int mGestureRecognitionUpdateTime;
public KeyTimerHandler(final MainKeyboardView outerInstance,
final TypedArray mainKeyboardViewAttr) {
@@ -168,12 +218,12 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
R.styleable.MainKeyboardView_keyRepeatStartTimeout, 0);
mKeyRepeatInterval = mainKeyboardViewAttr.getInt(
R.styleable.MainKeyboardView_keyRepeatInterval, 0);
- mLongPressKeyTimeout = mainKeyboardViewAttr.getInt(
- R.styleable.MainKeyboardView_longPressKeyTimeout, 0);
- mLongPressShiftKeyTimeout = mainKeyboardViewAttr.getInt(
- R.styleable.MainKeyboardView_longPressShiftKeyTimeout, 0);
+ mLongPressShiftLockTimeout = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_longPressShiftLockTimeout, 0);
mIgnoreAltCodeKeyTimeout = mainKeyboardViewAttr.getInt(
R.styleable.MainKeyboardView_ignoreAltCodeKeyTimeout, 0);
+ mGestureRecognitionUpdateTime = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_gestureRecognitionUpdateTime, 0);
}
@Override
@@ -193,17 +243,23 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
break;
case MSG_LONGPRESS_KEY:
if (tracker != null) {
- keyboardView.openMoreKeysKeyboardIfRequired(tracker.getKey(), tracker);
+ keyboardView.onLongPress(tracker);
} else {
KeyboardSwitcher.getInstance().onLongPressTimeout(msg.arg1);
}
break;
+ case MSG_UPDATE_BATCH_INPUT:
+ tracker.updateBatchInputByTimer(SystemClock.uptimeMillis());
+ startUpdateBatchInputTimer(tracker);
+ break;
}
}
private void startKeyRepeatTimer(final PointerTracker tracker, final long delay) {
final Key key = tracker.getKey();
- if (key == null) return;
+ if (key == null) {
+ return;
+ }
sendMessageDelayed(obtainMessage(MSG_REPEAT_KEY, key.mCode, 0, tracker), delay);
}
@@ -226,8 +282,8 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
cancelLongPressTimer();
final int delay;
switch (code) {
- case Keyboard.CODE_SHIFT:
- delay = mLongPressShiftKeyTimeout;
+ case Constants.CODE_SHIFT:
+ delay = mLongPressShiftLockTimeout;
break;
default:
delay = 0;
@@ -247,16 +303,18 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
final Key key = tracker.getKey();
final int delay;
switch (key.mCode) {
- case Keyboard.CODE_SHIFT:
- delay = mLongPressShiftKeyTimeout;
+ case Constants.CODE_SHIFT:
+ delay = mLongPressShiftLockTimeout;
break;
default:
+ final int longpressTimeout =
+ Settings.getInstance().getCurrent().mKeyLongpressTimeout;
if (KeyboardSwitcher.getInstance().isInMomentarySwitchState()) {
// We use longer timeout for sliding finger input started from the symbols
// mode key.
- delay = mLongPressKeyTimeout * 3;
+ delay = longpressTimeout * 3;
} else {
- delay = mLongPressKeyTimeout;
+ delay = longpressTimeout;
}
break;
}
@@ -304,7 +362,7 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
// When user hits the space or the enter key, just cancel the while-typing timer.
final int typedCode = typedKey.mCode;
- if (typedCode == Keyboard.CODE_SPACE || typedCode == Keyboard.CODE_ENTER) {
+ if (typedCode == Constants.CODE_SPACE || typedCode == Constants.CODE_ENTER) {
startWhileTypingFadeinAnimation(keyboardView);
return;
}
@@ -344,8 +402,79 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
cancelLongPressTimer();
}
+ @Override
+ public void startUpdateBatchInputTimer(final PointerTracker tracker) {
+ if (mGestureRecognitionUpdateTime <= 0) {
+ return;
+ }
+ removeMessages(MSG_UPDATE_BATCH_INPUT, tracker);
+ sendMessageDelayed(obtainMessage(MSG_UPDATE_BATCH_INPUT, tracker),
+ mGestureRecognitionUpdateTime);
+ }
+
+ @Override
+ public void cancelUpdateBatchInputTimer(final PointerTracker tracker) {
+ removeMessages(MSG_UPDATE_BATCH_INPUT, tracker);
+ }
+
+ @Override
+ public void cancelAllUpdateBatchInputTimers() {
+ removeMessages(MSG_UPDATE_BATCH_INPUT);
+ }
+
public void cancelAllMessages() {
cancelKeyTimers();
+ cancelAllUpdateBatchInputTimers();
+ }
+ }
+
+ private final DrawingHandler mDrawingHandler = new DrawingHandler(this);
+
+ public static class DrawingHandler extends StaticInnerHandlerWrapper<MainKeyboardView> {
+ private static final int MSG_DISMISS_KEY_PREVIEW = 0;
+ private static final int MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1;
+
+ public DrawingHandler(final MainKeyboardView outerInstance) {
+ super(outerInstance);
+ }
+
+ @Override
+ public void handleMessage(final Message msg) {
+ final MainKeyboardView mainKeyboardView = getOuterInstance();
+ if (mainKeyboardView == null) return;
+ final PointerTracker tracker = (PointerTracker) msg.obj;
+ switch (msg.what) {
+ case MSG_DISMISS_KEY_PREVIEW:
+ final TextView previewText = mainKeyboardView.mKeyPreviewTexts.get(
+ tracker.mPointerId);
+ if (previewText != null) {
+ previewText.setVisibility(INVISIBLE);
+ }
+ break;
+ case MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT:
+ mainKeyboardView.showGestureFloatingPreviewText(SuggestedWords.EMPTY);
+ break;
+ }
+ }
+
+ public void dismissKeyPreview(final long delay, final PointerTracker tracker) {
+ sendMessageDelayed(obtainMessage(MSG_DISMISS_KEY_PREVIEW, tracker), delay);
+ }
+
+ public void cancelDismissKeyPreview(final PointerTracker tracker) {
+ removeMessages(MSG_DISMISS_KEY_PREVIEW, tracker);
+ }
+
+ private void cancelAllDismissKeyPreviews() {
+ removeMessages(MSG_DISMISS_KEY_PREVIEW);
+ }
+
+ public void dismissGestureFloatingPreviewText(final long delay) {
+ sendMessageDelayed(obtainMessage(MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT), delay);
+ }
+
+ public void cancelAllMessages() {
+ cancelAllDismissKeyPreviews();
}
}
@@ -356,49 +485,89 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
public MainKeyboardView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
- mTouchScreenRegulator = new SuddenJumpingTouchEventHandler(getContext(), this);
+ mTouchScreenRegulator = new TouchScreenRegulator(context, this);
- mHasDistinctMultitouch = context.getPackageManager()
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ final boolean forceNonDistinctMultitouch = prefs.getBoolean(
+ DebugSettings.PREF_FORCE_NON_DISTINCT_MULTITOUCH, false);
+ final boolean hasDistinctMultitouch = context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT);
+ mHasDistinctMultitouch = hasDistinctMultitouch && !forceNonDistinctMultitouch;
final Resources res = getResources();
final boolean needsPhantomSuddenMoveEventHack = Boolean.parseBoolean(
- ResourceUtils.getDeviceOverrideValue(res,
- R.array.phantom_sudden_move_event_device_list, "false"));
- PointerTracker.init(mHasDistinctMultitouch, needsPhantomSuddenMoveEventHack);
+ ResourceUtils.getDeviceOverrideValue(
+ res, R.array.phantom_sudden_move_event_device_list));
+ PointerTracker.init(needsPhantomSuddenMoveEventHack);
+ mPreviewPlacerView = new PreviewPlacerView(context, attrs);
- final TypedArray a = context.obtainStyledAttributes(
+ final TypedArray mainKeyboardViewAttr = context.obtainStyledAttributes(
attrs, R.styleable.MainKeyboardView, defStyle, R.style.MainKeyboardView);
- mAutoCorrectionSpacebarLedEnabled = a.getBoolean(
+ final int backgroundDimAlpha = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_backgroundDimAlpha, 0);
+ mBackgroundDimAlphaPaint.setColor(Color.BLACK);
+ mBackgroundDimAlphaPaint.setAlpha(backgroundDimAlpha);
+ mAutoCorrectionSpacebarLedEnabled = mainKeyboardViewAttr.getBoolean(
R.styleable.MainKeyboardView_autoCorrectionSpacebarLedEnabled, false);
- mAutoCorrectionSpacebarLedIcon = a.getDrawable(
+ mAutoCorrectionSpacebarLedIcon = mainKeyboardViewAttr.getDrawable(
R.styleable.MainKeyboardView_autoCorrectionSpacebarLedIcon);
- mSpacebarTextRatio = a.getFraction(
+ mSpacebarTextRatio = mainKeyboardViewAttr.getFraction(
R.styleable.MainKeyboardView_spacebarTextRatio, 1, 1, 1.0f);
- mSpacebarTextColor = a.getColor(R.styleable.MainKeyboardView_spacebarTextColor, 0);
- mSpacebarTextShadowColor = a.getColor(
+ mSpacebarTextColor = mainKeyboardViewAttr.getColor(
+ R.styleable.MainKeyboardView_spacebarTextColor, 0);
+ mSpacebarTextShadowColor = mainKeyboardViewAttr.getColor(
R.styleable.MainKeyboardView_spacebarTextShadowColor, 0);
- mLanguageOnSpacebarFinalAlpha = a.getInt(
+ mLanguageOnSpacebarFinalAlpha = mainKeyboardViewAttr.getInt(
R.styleable.MainKeyboardView_languageOnSpacebarFinalAlpha,
Constants.Color.ALPHA_OPAQUE);
- final int languageOnSpacebarFadeoutAnimatorResId = a.getResourceId(
+ final int languageOnSpacebarFadeoutAnimatorResId = mainKeyboardViewAttr.getResourceId(
R.styleable.MainKeyboardView_languageOnSpacebarFadeoutAnimator, 0);
- final int altCodeKeyWhileTypingFadeoutAnimatorResId = a.getResourceId(
+ final int altCodeKeyWhileTypingFadeoutAnimatorResId = mainKeyboardViewAttr.getResourceId(
R.styleable.MainKeyboardView_altCodeKeyWhileTypingFadeoutAnimator, 0);
- final int altCodeKeyWhileTypingFadeinAnimatorResId = a.getResourceId(
+ final int altCodeKeyWhileTypingFadeinAnimatorResId = mainKeyboardViewAttr.getResourceId(
R.styleable.MainKeyboardView_altCodeKeyWhileTypingFadeinAnimator, 0);
- final float keyHysteresisDistance = a.getDimension(
+ final float keyHysteresisDistance = mainKeyboardViewAttr.getDimension(
R.styleable.MainKeyboardView_keyHysteresisDistance, 0);
- final float keyHysteresisDistanceForSlidingModifier = a.getDimension(
+ final float keyHysteresisDistanceForSlidingModifier = mainKeyboardViewAttr.getDimension(
R.styleable.MainKeyboardView_keyHysteresisDistanceForSlidingModifier, 0);
mKeyDetector = new KeyDetector(
keyHysteresisDistance, keyHysteresisDistanceForSlidingModifier);
- mKeyTimerHandler = new KeyTimerHandler(this, a);
- mConfigShowMoreKeysKeyboardAtTouchedPoint = a.getBoolean(
+ mKeyTimerHandler = new KeyTimerHandler(this, mainKeyboardViewAttr);
+ mKeyPreviewOffset = mainKeyboardViewAttr.getDimensionPixelOffset(
+ R.styleable.MainKeyboardView_keyPreviewOffset, 0);
+ mKeyPreviewHeight = mainKeyboardViewAttr.getDimensionPixelSize(
+ R.styleable.MainKeyboardView_keyPreviewHeight, 0);
+ mKeyPreviewLingerTimeout = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_keyPreviewLingerTimeout, 0);
+ mKeyPreviewLayoutId = mainKeyboardViewAttr.getResourceId(
+ R.styleable.MainKeyboardView_keyPreviewLayout, 0);
+ if (mKeyPreviewLayoutId == 0) {
+ mShowKeyPreviewPopup = false;
+ }
+ final int moreKeysKeyboardLayoutId = mainKeyboardViewAttr.getResourceId(
+ R.styleable.MainKeyboardView_moreKeysKeyboardLayout, 0);
+ mConfigShowMoreKeysKeyboardAtTouchedPoint = mainKeyboardViewAttr.getBoolean(
R.styleable.MainKeyboardView_showMoreKeysKeyboardAtTouchedPoint, false);
- PointerTracker.setParameters(a);
- a.recycle();
+ mGestureFloatingPreviewTextLingerTimeout = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewTextLingerTimeout, 0);
+ PointerTracker.setParameters(mainKeyboardViewAttr);
+
+ mGestureFloatingPreviewText = new GestureFloatingPreviewText(
+ mPreviewPlacerView, mainKeyboardViewAttr);
+ mPreviewPlacerView.addPreview(mGestureFloatingPreviewText);
+
+ mGestureTrailsPreview = new GestureTrailsPreview(
+ mPreviewPlacerView, mainKeyboardViewAttr);
+ mPreviewPlacerView.addPreview(mGestureTrailsPreview);
+
+ mSlidingKeyInputPreview = new SlidingKeyInputPreview(
+ mPreviewPlacerView, mainKeyboardViewAttr);
+ mPreviewPlacerView.addPreview(mSlidingKeyInputPreview);
+ mainKeyboardViewAttr.recycle();
+
+ mMoreKeysKeyboardContainer = LayoutInflater.from(getContext())
+ .inflate(moreKeysKeyboardLayoutId, null);
mLanguageOnSpacebarFadeoutAnimator = loadObjectAnimator(
languageOnSpacebarFadeoutAnimatorResId, this);
mAltCodeKeyWhileTypingFadeoutAnimator = loadObjectAnimator(
@@ -408,7 +577,9 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
}
private ObjectAnimator loadObjectAnimator(final int resId, final Object target) {
- if (resId == 0) return null;
+ if (resId == 0) {
+ return null;
+ }
final ObjectAnimator animator = (ObjectAnimator)AnimatorInflater.loadAnimator(
getContext(), resId);
if (animator != null) {
@@ -417,20 +588,23 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
return animator;
}
- // Getter/setter methods for {@link ObjectAnimator}.
+ @ExternallyReferenced
public int getLanguageOnSpacebarAnimAlpha() {
return mLanguageOnSpacebarAnimAlpha;
}
+ @ExternallyReferenced
public void setLanguageOnSpacebarAnimAlpha(final int alpha) {
mLanguageOnSpacebarAnimAlpha = alpha;
invalidateKey(mSpaceKey);
}
+ @ExternallyReferenced
public int getAltCodeKeyWhileTypingAnimAlpha() {
return mAltCodeKeyWhileTypingAnimAlpha;
}
+ @ExternallyReferenced
public void setAltCodeKeyWhileTypingAnimAlpha(final int alpha) {
mAltCodeKeyWhileTypingAnimAlpha = alpha;
updateAltCodeKeyWhileTyping();
@@ -480,10 +654,10 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
mKeyDetector.setKeyboard(
keyboard, -getPaddingLeft(), -getPaddingTop() + mVerticalCorrection);
PointerTracker.setKeyDetector(mKeyDetector);
- mTouchScreenRegulator.setKeyboard(keyboard);
- mMoreKeysPanelCache.clear();
+ mTouchScreenRegulator.setKeyboardGeometry(keyboard.mOccupiedWidth);
+ mMoreKeysKeyboardCache.clear();
- mSpaceKey = keyboard.getKey(Keyboard.CODE_SPACE);
+ mSpaceKey = keyboard.getKey(Constants.CODE_SPACE);
mSpaceIcon = (mSpaceKey != null)
? mSpaceKey.getIcon(keyboard.mIconsSet, Constants.Color.ALPHA_OPAQUE) : null;
final int keyHeight = keyboard.mMostCommonKeyHeight - keyboard.mVerticalGap;
@@ -494,28 +668,258 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
// This always needs to be set since the accessibility state can
// potentially change without the keyboard being set again.
- AccessibleKeyboardViewProxy.getInstance().setKeyboard(keyboard);
+ AccessibleKeyboardViewProxy.getInstance().setKeyboard();
}
- // Note that this method is called from a non-UI thread.
- public void setMainDictionaryAvailability(final boolean mainDictionaryAvailable) {
- PointerTracker.setMainDictionaryAvailability(mainDictionaryAvailable);
+ /**
+ * 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 preview
+ * @param delay the delay after which the preview is dismissed
+ * @see #isKeyPreviewPopupEnabled()
+ */
+ public void setKeyPreviewPopupEnabled(final boolean previewEnabled, final int delay) {
+ mShowKeyPreviewPopup = previewEnabled;
+ mKeyPreviewLingerTimeout = delay;
}
- public void setGestureHandlingEnabledByUser(final boolean gestureHandlingEnabledByUser) {
- PointerTracker.setGestureHandlingEnabledByUser(gestureHandlingEnabledByUser);
+
+ private void locatePreviewPlacerView() {
+ if (mPreviewPlacerView.getParent() != null) {
+ return;
+ }
+ final int width = getWidth();
+ final int height = getHeight();
+ if (width == 0 || height == 0) {
+ // In transient state.
+ return;
+ }
+ getLocationInWindow(mOriginCoords);
+ final DisplayMetrics dm = getResources().getDisplayMetrics();
+ if (CoordinateUtils.y(mOriginCoords) < dm.heightPixels / 4) {
+ // In transient state.
+ return;
+ }
+ final View rootView = getRootView();
+ if (rootView == null) {
+ Log.w(TAG, "Cannot find root view");
+ return;
+ }
+ final ViewGroup windowContentView = (ViewGroup)rootView.findViewById(android.R.id.content);
+ // Note: It'd be very weird if we get null by android.R.id.content.
+ if (windowContentView == null) {
+ Log.w(TAG, "Cannot find android.R.id.content view to add PreviewPlacerView");
+ } else {
+ windowContentView.addView(mPreviewPlacerView);
+ mPreviewPlacerView.setKeyboardViewGeometry(mOriginCoords, width, height);
+ }
}
/**
- * Returns whether the device has distinct multi-touch panel.
- * @return true if the device has distinct multi-touch panel.
+ * 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 hasDistinctMultitouch() {
- return mHasDistinctMultitouch;
+ public boolean isKeyPreviewPopupEnabled() {
+ return mShowKeyPreviewPopup;
+ }
+
+ private void addKeyPreview(final TextView keyPreview) {
+ locatePreviewPlacerView();
+ mPreviewPlacerView.addView(
+ keyPreview, ViewLayoutUtils.newLayoutParam(mPreviewPlacerView, 0, 0));
+ }
+
+ private TextView getKeyPreviewText(final int pointerId) {
+ TextView previewText = mKeyPreviewTexts.get(pointerId);
+ if (previewText != null) {
+ return previewText;
+ }
+ final Context context = getContext();
+ if (mKeyPreviewLayoutId != 0) {
+ previewText = (TextView)LayoutInflater.from(context).inflate(mKeyPreviewLayoutId, null);
+ } else {
+ previewText = new TextView(context);
+ }
+ mKeyPreviewTexts.put(pointerId, previewText);
+ return previewText;
+ }
+
+ private void dismissAllKeyPreviews() {
+ final int pointerCount = mKeyPreviewTexts.size();
+ for (int id = 0; id < pointerCount; id++) {
+ final TextView previewText = mKeyPreviewTexts.get(id);
+ if (previewText != null) {
+ previewText.setVisibility(INVISIBLE);
+ }
+ }
+ PointerTracker.setReleasedKeyGraphicsToAllKeys();
+ }
+
+ // Background state set
+ private static final int[][][] KEY_PREVIEW_BACKGROUND_STATE_TABLE = {
+ { // STATE_MIDDLE
+ EMPTY_STATE_SET,
+ { R.attr.state_has_morekeys }
+ },
+ { // STATE_LEFT
+ { R.attr.state_left_edge },
+ { R.attr.state_left_edge, R.attr.state_has_morekeys }
+ },
+ { // STATE_RIGHT
+ { R.attr.state_right_edge },
+ { R.attr.state_right_edge, R.attr.state_has_morekeys }
+ }
+ };
+ private static final int STATE_MIDDLE = 0;
+ private static final int STATE_LEFT = 1;
+ private static final int STATE_RIGHT = 2;
+ private static final int STATE_NORMAL = 0;
+ private static final int STATE_HAS_MOREKEYS = 1;
+ private static final int[] KEY_PREVIEW_BACKGROUND_DEFAULT_STATE =
+ KEY_PREVIEW_BACKGROUND_STATE_TABLE[STATE_MIDDLE][STATE_NORMAL];
+
+ @Override
+ public void showKeyPreview(final PointerTracker tracker) {
+ final KeyPreviewDrawParams previewParams = mKeyPreviewDrawParams;
+ final Keyboard keyboard = getKeyboard();
+ if (!mShowKeyPreviewPopup) {
+ previewParams.mPreviewVisibleOffset = -keyboard.mVerticalGap;
+ return;
+ }
+
+ final TextView previewText = getKeyPreviewText(tracker.mPointerId);
+ // 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);
+ }
+
+ mDrawingHandler.cancelDismissKeyPreview(tracker);
+ final Key key = tracker.getKey();
+ // If key is invalid or IME is already closed, we must not show key preview.
+ // Trying to show key preview while root window is closed causes
+ // WindowManager.BadTokenException.
+ if (key == null) {
+ return;
+ }
+
+ final KeyDrawParams drawParams = mKeyDrawParams;
+ previewText.setTextColor(drawParams.mPreviewTextColor);
+ final Drawable background = previewText.getBackground();
+ if (background != null) {
+ background.setState(KEY_PREVIEW_BACKGROUND_DEFAULT_STATE);
+ background.setAlpha(PREVIEW_ALPHA);
+ }
+ final String label = key.getPreviewLabel();
+ // What we show as preview should match what we show on a key top in onDraw().
+ if (label != null) {
+ // TODO Should take care of temporaryShiftLabel here.
+ previewText.setCompoundDrawables(null, null, null, null);
+ previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX,
+ key.selectPreviewTextSize(drawParams));
+ previewText.setTypeface(key.selectPreviewTypeface(drawParams));
+ previewText.setText(label);
+ } else {
+ previewText.setCompoundDrawables(null, null, null,
+ key.getPreviewIcon(keyboard.mIconsSet));
+ previewText.setText(null);
+ }
+
+ previewText.measure(
+ ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+ final int keyDrawWidth = key.getDrawWidth();
+ final int previewWidth = previewText.getMeasuredWidth();
+ final int previewHeight = mKeyPreviewHeight;
+ // The width and height of visible part of the key preview background. The content marker
+ // of the background 9-patch have to cover the visible part of the background.
+ previewParams.mPreviewVisibleWidth = previewWidth - previewText.getPaddingLeft()
+ - previewText.getPaddingRight();
+ previewParams.mPreviewVisibleHeight = previewHeight - previewText.getPaddingTop()
+ - previewText.getPaddingBottom();
+ // The distance between the top edge of the parent key and the bottom of the visible part
+ // of the key preview background.
+ previewParams.mPreviewVisibleOffset = mKeyPreviewOffset - previewText.getPaddingBottom();
+ getLocationInWindow(mOriginCoords);
+ // The key preview is horizontally aligned with the center of the visible part of the
+ // parent key. If it doesn't fit in this {@link KeyboardView}, it is moved inward to fit and
+ // the left/right background is used if such background is specified.
+ final int statePosition;
+ int previewX = key.getDrawX() - (previewWidth - keyDrawWidth) / 2
+ + CoordinateUtils.x(mOriginCoords);
+ if (previewX < 0) {
+ previewX = 0;
+ statePosition = STATE_LEFT;
+ } else if (previewX > getWidth() - previewWidth) {
+ previewX = getWidth() - previewWidth;
+ statePosition = STATE_RIGHT;
+ } else {
+ statePosition = STATE_MIDDLE;
+ }
+ // The key preview is placed vertically above the top edge of the parent key with an
+ // arbitrary offset.
+ final int previewY = key.mY - previewHeight + mKeyPreviewOffset
+ + CoordinateUtils.y(mOriginCoords);
+
+ if (background != null) {
+ final int hasMoreKeys = (key.mMoreKeys != null) ? STATE_HAS_MOREKEYS : STATE_NORMAL;
+ background.setState(KEY_PREVIEW_BACKGROUND_STATE_TABLE[statePosition][hasMoreKeys]);
+ }
+ ViewLayoutUtils.placeViewAt(
+ previewText, previewX, previewY, previewWidth, previewHeight);
+ previewText.setVisibility(VISIBLE);
+ }
+
+ @Override
+ public void dismissKeyPreview(final PointerTracker tracker) {
+ mDrawingHandler.dismissKeyPreview(mKeyPreviewLingerTimeout, tracker);
}
- public void setDistinctMultitouch(final boolean hasDistinctMultitouch) {
- mHasDistinctMultitouch = hasDistinctMultitouch;
+ public void setSlidingKeyInputPreviewEnabled(final boolean enabled) {
+ mSlidingKeyInputPreview.setPreviewEnabled(enabled);
+ }
+
+ @Override
+ public void showSlidingKeyInputPreview(final PointerTracker tracker) {
+ locatePreviewPlacerView();
+ mSlidingKeyInputPreview.setPreviewPosition(tracker);
+ }
+
+ @Override
+ public void dismissSlidingKeyInputPreview() {
+ mSlidingKeyInputPreview.dismissSlidingKeyInputPreview();
+ }
+
+ public void setGesturePreviewMode(final boolean drawsGesturePreviewTrail,
+ final boolean drawsGestureFloatingPreviewText) {
+ mGestureFloatingPreviewText.setPreviewEnabled(drawsGestureFloatingPreviewText);
+ mGestureTrailsPreview.setPreviewEnabled(drawsGesturePreviewTrail);
+ }
+
+ public void showGestureFloatingPreviewText(final SuggestedWords suggestedWords) {
+ locatePreviewPlacerView();
+ mGestureFloatingPreviewText.setSuggetedWords(suggestedWords);
+ }
+
+ public void dismissGestureFloatingPreviewText() {
+ locatePreviewPlacerView();
+ mDrawingHandler.dismissGestureFloatingPreviewText(mGestureFloatingPreviewTextLingerTimeout);
+ }
+
+ @Override
+ public void showGesturePreviewTrail(final PointerTracker tracker) {
+ locatePreviewPlacerView();
+ mGestureFloatingPreviewText.setPreviewPosition(tracker);
+ mGestureTrailsPreview.setPreviewPosition(tracker);
+ }
+
+ // Note that this method is called from a non-UI thread.
+ public void setMainDictionaryAvailability(final boolean mainDictionaryAvailable) {
+ PointerTracker.setMainDictionaryAvailability(mainDictionaryAvailable);
+ }
+
+ public void setGestureHandlingEnabledByUser(final boolean gestureHandlingEnabledByUser) {
+ PointerTracker.setGestureHandlingEnabledByUser(gestureHandlingEnabledByUser);
}
@Override
@@ -532,6 +936,7 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
+ mPreviewPlacerView.removeAllViews();
// Notify the research logger that the keyboard view has been detached. This is needed
// to invalidate the reference of {@link MainKeyboardView} to null.
if (ProductionFlag.IS_EXPERIMENTAL) {
@@ -539,135 +944,138 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
}
}
- @Override
- public void cancelAllMessages() {
- mKeyTimerHandler.cancelAllMessages();
- super.cancelAllMessages();
- }
-
- private boolean openMoreKeysKeyboardIfRequired(final Key parentKey,
- final PointerTracker tracker) {
- // Check if we have a popup layout specified first.
- if (mMoreKeysLayout == 0) {
- return false;
- }
-
- // Check if we are already displaying popup panel.
- if (mMoreKeysPanel != null)
- return false;
- if (parentKey == null)
- return false;
- return onLongPress(parentKey, tracker);
- }
-
- // This default implementation returns a more keys panel.
- protected MoreKeysPanel onCreateMoreKeysPanel(final Key parentKey) {
- if (parentKey.mMoreKeys == null)
+ private MoreKeysPanel onCreateMoreKeysPanel(final Key key, final Context context) {
+ if (key.mMoreKeys == null) {
return null;
+ }
+ Keyboard moreKeysKeyboard = mMoreKeysKeyboardCache.get(key);
+ if (moreKeysKeyboard == null) {
+ moreKeysKeyboard = new MoreKeysKeyboard.Builder(
+ context, key, this, mKeyPreviewDrawParams).build();
+ mMoreKeysKeyboardCache.put(key, moreKeysKeyboard);
+ }
- final View container = LayoutInflater.from(getContext()).inflate(mMoreKeysLayout, null);
- if (container == null)
- throw new NullPointerException();
-
+ final View container = mMoreKeysKeyboardContainer;
final MoreKeysKeyboardView moreKeysKeyboardView =
(MoreKeysKeyboardView)container.findViewById(R.id.more_keys_keyboard_view);
- final Keyboard moreKeysKeyboard = new MoreKeysKeyboard.Builder(container, parentKey, this)
- .build();
moreKeysKeyboardView.setKeyboard(moreKeysKeyboard);
container.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
-
return moreKeysKeyboardView;
}
/**
- * Called when a key is long pressed. By default this will open more keys keyboard associated
- * with this key.
- * @param parentKey the key that was long pressed
+ * Called when a key is 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(final Key parentKey, final PointerTracker tracker) {
+ private boolean onLongPress(final PointerTracker tracker) {
+ if (isShowingMoreKeysPanel()) {
+ return false;
+ }
+ final Key key = tracker.getKey();
+ if (key == null) {
+ return false;
+ }
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.mainKeyboardView_onLongPress();
}
- final int primaryCode = parentKey.mCode;
- if (parentKey.hasEmbeddedMoreKey()) {
- final int embeddedCode = parentKey.mMoreKeys[0].mCode;
+ final int code = key.mCode;
+ if (key.hasEmbeddedMoreKey()) {
+ final int embeddedCode = key.mMoreKeys[0].mCode;
tracker.onLongPressed();
invokeCodeInput(embeddedCode);
- invokeReleaseKey(primaryCode);
- KeyboardSwitcher.getInstance().hapticAndAudioFeedback(primaryCode);
+ invokeReleaseKey(code);
+ KeyboardSwitcher.getInstance().hapticAndAudioFeedback(code);
return true;
}
- if (primaryCode == Keyboard.CODE_SPACE || primaryCode == Keyboard.CODE_LANGUAGE_SWITCH) {
+ if (code == Constants.CODE_SPACE || code == Constants.CODE_LANGUAGE_SWITCH) {
// Long pressing the space key invokes IME switcher dialog.
if (invokeCustomRequest(LatinIME.CODE_SHOW_INPUT_METHOD_PICKER)) {
tracker.onLongPressed();
- invokeReleaseKey(primaryCode);
+ invokeReleaseKey(code);
return true;
}
}
- return openMoreKeysPanel(parentKey, tracker);
+ return openMoreKeysPanel(key, tracker);
}
- private boolean invokeCustomRequest(final int code) {
- return mKeyboardActionListener.onCustomRequest(code);
+ private boolean invokeCustomRequest(final int requestCode) {
+ return mKeyboardActionListener.onCustomRequest(requestCode);
}
- private void invokeCodeInput(final int primaryCode) {
+ private void invokeCodeInput(final int code) {
mKeyboardActionListener.onCodeInput(
- primaryCode, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
+ code, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
- private void invokeReleaseKey(final int primaryCode) {
- mKeyboardActionListener.onReleaseKey(primaryCode, false);
+ private void invokeReleaseKey(final int code) {
+ mKeyboardActionListener.onReleaseKey(code, false);
}
- private boolean openMoreKeysPanel(final Key parentKey, final PointerTracker tracker) {
- MoreKeysPanel moreKeysPanel = mMoreKeysPanelCache.get(parentKey);
+ private boolean openMoreKeysPanel(final Key key, final PointerTracker tracker) {
+ final MoreKeysPanel moreKeysPanel = onCreateMoreKeysPanel(key, getContext());
if (moreKeysPanel == null) {
- moreKeysPanel = onCreateMoreKeysPanel(parentKey);
- if (moreKeysPanel == null)
- return false;
- mMoreKeysPanelCache.put(parentKey, moreKeysPanel);
- }
- if (mMoreKeysWindow == null) {
- mMoreKeysWindow = new PopupWindow(getContext());
- mMoreKeysWindow.setBackgroundDrawable(null);
- mMoreKeysWindow.setAnimationStyle(R.style.MoreKeysKeyboardAnimation);
+ return false;
}
- mMoreKeysPanel = moreKeysPanel;
- mMoreKeysPanelPointerTrackerId = tracker.mPointerId;
- final boolean keyPreviewEnabled = isKeyPreviewPopupEnabled() && !parentKey.noKeyPreview();
+ final int[] lastCoords = CoordinateUtils.newInstance();
+ tracker.getLastCoordinates(lastCoords);
+ final boolean keyPreviewEnabled = isKeyPreviewPopupEnabled() && !key.noKeyPreview();
// The more keys keyboard is usually horizontally aligned with the center of the parent key.
// If showMoreKeysKeyboardAtTouchedPoint is true and the key preview is disabled, the more
// keys keyboard is placed at the touch point of the parent key.
final int pointX = (mConfigShowMoreKeysKeyboardAtTouchedPoint && !keyPreviewEnabled)
- ? tracker.getLastX()
- : parentKey.mX + parentKey.mWidth / 2;
+ ? CoordinateUtils.x(lastCoords)
+ : key.mX + key.mWidth / 2;
// The more keys keyboard is usually vertically aligned with the top edge of the parent key
// (plus vertical gap). If the key preview is enabled, the more keys keyboard is vertically
// aligned with the bottom edge of the visible part of the key preview.
// {@code mPreviewVisibleOffset} has been set appropriately in
// {@link KeyboardView#showKeyPreview(PointerTracker)}.
- final int pointY = parentKey.mY + mKeyPreviewDrawParams.mPreviewVisibleOffset;
- moreKeysPanel.showMoreKeysPanel(
- this, this, pointX, pointY, mMoreKeysWindow, mKeyboardActionListener);
- final int translatedX = moreKeysPanel.translateX(tracker.getLastX());
- final int translatedY = moreKeysPanel.translateY(tracker.getLastY());
+ final int pointY = key.mY + mKeyPreviewDrawParams.mPreviewVisibleOffset;
+ moreKeysPanel.showMoreKeysPanel(this, this, pointX, pointY, mKeyboardActionListener);
+ final int translatedX = moreKeysPanel.translateX(CoordinateUtils.x(lastCoords));
+ final int translatedY = moreKeysPanel.translateY(CoordinateUtils.y(lastCoords));
tracker.onShowMoreKeysPanel(translatedX, translatedY, moreKeysPanel);
- dimEntireKeyboard(true);
return true;
}
public boolean isInSlidingKeyInput() {
- if (mMoreKeysPanel != null) {
+ if (isShowingMoreKeysPanel()) {
return true;
- } else {
- return PointerTracker.isAnyInSlidingKeyInput();
}
+ return PointerTracker.isAnyInSlidingKeyInput();
+ }
+
+ @Override
+ public void onShowMoreKeysPanel(final MoreKeysPanel panel) {
+ if (isShowingMoreKeysPanel()) {
+ onDismissMoreKeysPanel();
+ }
+ mPreviewPlacerView.addView(panel.getContainerView());
+ mMoreKeysPanel = panel;
+ dimEntireKeyboard(true /* dimmed */);
+ }
+
+ public boolean isShowingMoreKeysPanel() {
+ return mMoreKeysPanel != null && mMoreKeysPanel.isShowingInParent();
+ }
+
+ @Override
+ public void onCancelMoreKeysPanel() {
+ PointerTracker.dismissAllMoreKeysPanels();
+ }
+
+ @Override
+ public boolean onDismissMoreKeysPanel() {
+ dimEntireKeyboard(false /* dimmed */);
+ if (isShowingMoreKeysPanel()) {
+ mPreviewPlacerView.removeView(mMoreKeysPanel.getContainerView());
+ mMoreKeysPanel = null;
+ return true;
+ }
+ return false;
}
public int getPointerCount() {
@@ -708,47 +1116,18 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
final long eventTime = me.getEventTime();
final int index = me.getActionIndex();
final int id = me.getPointerId(index);
- final int x, y;
- if (mMoreKeysPanel != null && id == mMoreKeysPanelPointerTrackerId) {
- x = mMoreKeysPanel.translateX((int)me.getX(index));
- y = mMoreKeysPanel.translateY((int)me.getY(index));
- } else {
- x = (int)me.getX(index);
- y = (int)me.getY(index);
- }
- if (ENABLE_USABILITY_STUDY_LOG) {
- final String eventTag;
- switch (action) {
- case MotionEvent.ACTION_UP:
- eventTag = "[Up]";
- break;
- case MotionEvent.ACTION_DOWN:
- eventTag = "[Down]";
- break;
- case MotionEvent.ACTION_POINTER_UP:
- eventTag = "[PointerUp]";
- break;
- case MotionEvent.ACTION_POINTER_DOWN:
- eventTag = "[PointerDown]";
- break;
- case MotionEvent.ACTION_MOVE: // Skip this as being logged below
- eventTag = "";
- break;
- default:
- eventTag = "[Action" + action + "]";
- break;
- }
- if (!TextUtils.isEmpty(eventTag)) {
- final float size = me.getSize(index);
- final float pressure = me.getPressure(index);
- UsabilityStudyLogUtils.getInstance().write(
- eventTag + eventTime + "," + id + "," + x + "," + y + ","
- + size + "," + pressure);
- }
+ final int x = (int)me.getX(index);
+ final int y = (int)me.getY(index);
+
+ // TODO: This might be moved to the tracker.processMotionEvent() call below.
+ if (ENABLE_USABILITY_STUDY_LOG && action != MotionEvent.ACTION_MOVE) {
+ writeUsabilityStudyLog(me, action, eventTime, index, id, x, y);
}
+ // TODO: This should be moved to the tracker.processMotionEvent() call below.
+ // Currently the same "move" event is being logged twice.
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.mainKeyboardView_processMotionEvent(me, action, eventTime, index, id,
- x, y);
+ ResearchLogger.mainKeyboardView_processMotionEvent(
+ me, action, eventTime, index, id, x, y);
}
if (mKeyTimerHandler.isInKeyRepeat()) {
@@ -774,16 +1153,18 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
final Key newKey = tracker.getKeyOn(x, y);
if (mOldKey != newKey) {
tracker.onDownEvent(x, y, eventTime, this);
- if (action == MotionEvent.ACTION_UP)
+ if (action == MotionEvent.ACTION_UP) {
tracker.onUpEvent(x, y, eventTime);
+ }
}
} else if (pointerCount == 2 && oldPointerCount == 1) {
// Single-touch to multi-touch transition.
// Send an up event for the last pointer.
- final int lastX = tracker.getLastX();
- final int lastY = tracker.getLastY();
- mOldKey = tracker.getKeyOn(lastX, lastY);
- tracker.onUpEvent(lastX, lastY, eventTime);
+ final int[] lastCoords = CoordinateUtils.newInstance();
+ mOldKey = tracker.getKeyOn(
+ CoordinateUtils.x(lastCoords), CoordinateUtils.y(lastCoords));
+ tracker.onUpEvent(
+ CoordinateUtils.x(lastCoords), CoordinateUtils.y(lastCoords), eventTime);
} else if (pointerCount == 1 && oldPointerCount == 1) {
tracker.processMotionEvent(action, x, y, eventTime, this);
} else {
@@ -798,29 +1179,15 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
final int pointerId = me.getPointerId(i);
final PointerTracker tracker = PointerTracker.getPointerTracker(
pointerId, this);
- final int px, py;
- final MotionEvent motionEvent;
- if (mMoreKeysPanel != null
- && tracker.mPointerId == mMoreKeysPanelPointerTrackerId) {
- px = mMoreKeysPanel.translateX((int)me.getX(i));
- py = mMoreKeysPanel.translateY((int)me.getY(i));
- motionEvent = null;
- } else {
- px = (int)me.getX(i);
- py = (int)me.getY(i);
- motionEvent = me;
- }
- tracker.onMoveEvent(px, py, eventTime, motionEvent);
+ final int px = (int)me.getX(i);
+ final int py = (int)me.getY(i);
+ tracker.onMoveEvent(px, py, eventTime, me);
if (ENABLE_USABILITY_STUDY_LOG) {
- final float pointerSize = me.getSize(i);
- final float pointerPressure = me.getPressure(i);
- UsabilityStudyLogUtils.getInstance().write("[Move]" + eventTime + ","
- + pointerId + "," + px + "," + py + ","
- + pointerSize + "," + pointerPressure);
+ writeUsabilityStudyLog(me, action, eventTime, i, pointerId, px, py);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.mainKeyboardView_processMotionEvent(me, action, eventTime,
- i, pointerId, px, py);
+ ResearchLogger.mainKeyboardView_processMotionEvent(
+ me, action, eventTime, i, pointerId, px, py);
}
}
} else {
@@ -831,23 +1198,45 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
return true;
}
- @Override
- public void closing() {
- super.closing();
- dismissMoreKeysPanel();
- mMoreKeysPanelCache.clear();
+ private static void writeUsabilityStudyLog(final MotionEvent me, final int action,
+ final long eventTime, final int index, final int id, final int x, final int y) {
+ final String eventTag;
+ switch (action) {
+ case MotionEvent.ACTION_UP:
+ eventTag = "[Up]";
+ break;
+ case MotionEvent.ACTION_DOWN:
+ eventTag = "[Down]";
+ break;
+ case MotionEvent.ACTION_POINTER_UP:
+ eventTag = "[PointerUp]";
+ break;
+ case MotionEvent.ACTION_POINTER_DOWN:
+ eventTag = "[PointerDown]";
+ break;
+ case MotionEvent.ACTION_MOVE:
+ eventTag = "[Move]";
+ break;
+ default:
+ eventTag = "[Action" + action + "]";
+ break;
+ }
+ final float size = me.getSize(index);
+ final float pressure = me.getPressure(index);
+ UsabilityStudyLogUtils.getInstance().write(
+ eventTag + eventTime + "," + id + "," + x + "," + y + "," + size + "," + pressure);
}
- @Override
- public boolean dismissMoreKeysPanel() {
- if (mMoreKeysWindow != null && mMoreKeysWindow.isShowing()) {
- mMoreKeysWindow.dismiss();
- mMoreKeysPanel = null;
- mMoreKeysPanelPointerTrackerId = -1;
- dimEntireKeyboard(false);
- return true;
- }
- return false;
+ public void cancelAllMessages() {
+ mKeyTimerHandler.cancelAllMessages();
+ mDrawingHandler.cancelAllMessages();
+ }
+
+ public void closing() {
+ dismissAllKeyPreviews();
+ cancelAllMessages();
+ onDismissMoreKeysPanel();
+ mMoreKeysKeyboardCache.clear();
}
/**
@@ -870,16 +1259,22 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
public void updateShortcutKey(final boolean available) {
final Keyboard keyboard = getKeyboard();
- if (keyboard == null) return;
- final Key shortcutKey = keyboard.getKey(Keyboard.CODE_SHORTCUT);
- if (shortcutKey == null) return;
+ if (keyboard == null) {
+ return;
+ }
+ final Key shortcutKey = keyboard.getKey(Constants.CODE_SHORTCUT);
+ if (shortcutKey == null) {
+ return;
+ }
shortcutKey.setEnabled(available);
invalidateKey(shortcutKey);
}
private void updateAltCodeKeyWhileTyping() {
final Keyboard keyboard = getKeyboard();
- if (keyboard == null) return;
+ if (keyboard == null) {
+ return;
+ }
for (final Key key : keyboard.mAltCodeKeysWhileTyping) {
invalidateKey(key);
}
@@ -909,24 +1304,44 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
}
public void updateAutoCorrectionState(final boolean isAutoCorrection) {
- if (!mAutoCorrectionSpacebarLedEnabled) return;
+ if (!mAutoCorrectionSpacebarLedEnabled) {
+ return;
+ }
mAutoCorrectionSpacebarLedOn = isAutoCorrection;
invalidateKey(mSpaceKey);
}
+ private void dimEntireKeyboard(final boolean dimmed) {
+ final boolean needsRedrawing = mNeedsToDimEntireKeyboard != dimmed;
+ mNeedsToDimEntireKeyboard = dimmed;
+ if (needsRedrawing) {
+ invalidateAllKeys();
+ }
+ }
+
+ @Override
+ protected void onDraw(final Canvas canvas) {
+ super.onDraw(canvas);
+
+ // Overlay a dark rectangle to dim.
+ if (mNeedsToDimEntireKeyboard) {
+ canvas.drawRect(0, 0, getWidth(), getHeight(), mBackgroundDimAlphaPaint);
+ }
+ }
+
@Override
protected void onDrawKeyTopVisuals(final Key key, final Canvas canvas, final Paint paint,
final KeyDrawParams params) {
if (key.altCodeWhileTyping() && key.isEnabled()) {
params.mAnimAlpha = mAltCodeKeyWhileTypingAnimAlpha;
}
- if (key.mCode == Keyboard.CODE_SPACE) {
+ if (key.mCode == Constants.CODE_SPACE) {
drawSpacebar(key, canvas, paint);
// Whether space key needs to show the "..." popup hint for special purposes
if (key.isLongPressEnabled() && mHasMultipleEnabledIMEsOrSubtypes) {
drawKeyPopupHint(key, canvas, paint, params);
}
- } else if (key.mCode == Keyboard.CODE_LANGUAGE_SWITCH) {
+ } else if (key.mCode == Constants.CODE_LANGUAGE_SWITCH) {
super.onDrawKeyTopVisuals(key, canvas, paint, params);
drawKeyPopupHint(key, canvas, paint, params);
} else {
@@ -937,10 +1352,14 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
private boolean fitsTextIntoWidth(final int width, final String text, final Paint paint) {
paint.setTextScaleX(1.0f);
final float textWidth = getLabelWidth(text, paint);
- if (textWidth < width) return true;
+ if (textWidth < width) {
+ return true;
+ }
final float scaleX = width / textWidth;
- if (scaleX < MINIMUM_XSCALE_OF_LANGUAGE_NAME) return false;
+ if (scaleX < MINIMUM_XSCALE_OF_LANGUAGE_NAME) {
+ return false;
+ }
paint.setTextScaleX(scaleX);
return getLabelWidth(text, paint) < width;
@@ -950,19 +1369,19 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
private String layoutLanguageOnSpacebar(final Paint paint, final InputMethodSubtype subtype,
final int width) {
// Choose appropriate language name to fit into the width.
- String text = getFullDisplayName(subtype, getResources());
- if (fitsTextIntoWidth(width, text, paint)) {
- return text;
+ final String fullText = getFullDisplayName(subtype);
+ if (fitsTextIntoWidth(width, fullText, paint)) {
+ return fullText;
}
- text = getMiddleDisplayName(subtype);
- if (fitsTextIntoWidth(width, text, paint)) {
- return text;
+ final String middleText = getMiddleDisplayName(subtype);
+ if (fitsTextIntoWidth(width, middleText, paint)) {
+ return middleText;
}
- text = getShortDisplayName(subtype);
- if (fitsTextIntoWidth(width, text, paint)) {
- return text;
+ final String shortText = getShortDisplayName(subtype);
+ if (fitsTextIntoWidth(width, shortText, paint)) {
+ return shortText;
}
return "";
@@ -1009,26 +1428,26 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
// InputMethodSubtype's display name for spacebar text in its locale.
// isAdditionalSubtype (T=true, F=false)
- // locale layout | Short Middle Full
- // ------ ------ - ---- --------- ----------------------
- // en_US qwerty F En English English (US) exception
- // en_GB qwerty F En English English (UK) exception
- // fr azerty F Fr Français Français
- // fr_CA qwerty F Fr Français Français (Canada)
- // de qwertz F De Deutsch Deutsch
- // zz qwerty F QWERTY QWERTY
- // fr qwertz T Fr Français Français (QWERTZ)
- // de qwerty T De Deutsch Deutsch (QWERTY)
- // en_US azerty T En English English (US) (AZERTY)
- // zz azerty T AZERTY AZERTY
+ // locale layout | Short Middle Full
+ // ------ ------- - ---- --------- ----------------------
+ // en_US qwerty F En English English (US) exception
+ // en_GB qwerty F En English English (UK) exception
+ // es_US spanish F Es Español Español (EE.UU.) exception
+ // fr azerty F Fr Français Français
+ // fr_CA qwerty F Fr Français Français (Canada)
+ // de qwertz F De Deutsch Deutsch
+ // zz qwerty F QWERTY QWERTY
+ // fr qwertz T Fr Français Français
+ // de qwerty T De Deutsch Deutsch
+ // en_US azerty T En English English (US)
+ // zz azerty T AZERTY AZERTY
// Get InputMethodSubtype's full display name in its locale.
- static String getFullDisplayName(final InputMethodSubtype subtype, final Resources res) {
+ static String getFullDisplayName(final InputMethodSubtype subtype) {
if (SubtypeLocale.isNoLanguage(subtype)) {
return SubtypeLocale.getKeyboardLayoutSetDisplayName(subtype);
}
-
- return SubtypeLocale.getSubtypeDisplayName(subtype, res);
+ return SubtypeLocale.getSubtypeLocaleDisplayName(subtype.getLocale());
}
// Get InputMethodSubtype's short display name in its locale.
@@ -1046,6 +1465,6 @@ public final class MainKeyboardView extends KeyboardView implements PointerTrack
return SubtypeLocale.getKeyboardLayoutSetDisplayName(subtype);
}
final Locale locale = SubtypeLocale.getSubtypeLocale(subtype);
- return StringUtils.toTitleCase(locale.getDisplayLanguage(locale), locale);
+ return SubtypeLocale.getSubtypeLocaleDisplayName(locale.getLanguage());
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboard.java b/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboard.java
index d7d4be40b..66c30149c 100644
--- a/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboard.java
+++ b/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboard.java
@@ -1,25 +1,27 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.graphics.Paint;
import android.graphics.drawable.Drawable;
-import android.view.View;
+import com.android.inputmethod.annotations.UsedForTesting;
+import com.android.inputmethod.keyboard.internal.KeyPreviewDrawParams;
import com.android.inputmethod.keyboard.internal.KeyboardBuilder;
import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.keyboard.internal.KeyboardParams;
@@ -39,7 +41,7 @@ public final class MoreKeysKeyboard extends Keyboard {
return mDefaultKeyCoordX;
}
- /* package for test */
+ @UsedForTesting
static class MoreKeysKeyboardParams extends KeyboardParams {
public boolean mIsFixedOrder;
/* package */int mTopRowAdjustment;
@@ -258,13 +260,15 @@ public final class MoreKeysKeyboard extends Keyboard {
/**
* The builder of MoreKeysKeyboard.
- * @param containerView the container of {@link MoreKeysKeyboardView}.
+ * @param context the context of {@link MoreKeysKeyboardView}.
* @param parentKey the {@link Key} that invokes more keys keyboard.
* @param parentKeyboardView the {@link KeyboardView} that contains the parentKey.
+ * @param keyPreviewDrawParams the parameter to place key preview.
*/
- public Builder(final View containerView, final Key parentKey,
- final KeyboardView parentKeyboardView) {
- super(containerView.getContext(), new MoreKeysKeyboardParams());
+ public Builder(final Context context, final Key parentKey,
+ final MainKeyboardView parentKeyboardView,
+ final KeyPreviewDrawParams keyPreviewDrawParams) {
+ super(context, new MoreKeysKeyboardParams());
final Keyboard parentKeyboard = parentKeyboardView.getKeyboard();
load(parentKeyboard.mMoreKeysTemplate, parentKeyboard.mId);
@@ -284,8 +288,8 @@ public final class MoreKeysKeyboard extends Keyboard {
// left/right/top paddings. The bottom paddings of both backgrounds don't need to
// be considered because the vertical positions of both backgrounds were already
// adjusted with their bottom paddings deducted.
- width = parentKeyboardView.mKeyPreviewDrawParams.mPreviewVisibleWidth;
- height = parentKeyboardView.mKeyPreviewDrawParams.mPreviewVisibleHeight
+ width = keyPreviewDrawParams.mPreviewVisibleWidth;
+ height = keyPreviewDrawParams.mPreviewVisibleHeight
+ mParams.mVerticalGap;
} else {
width = getMaxKeyWidth(parentKeyboardView, parentKey, mParams.mDefaultKeyWidth);
diff --git a/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboardView.java b/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboardView.java
index a50617693..0d42ab2fe 100644
--- a/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/MoreKeysKeyboardView.java
@@ -19,93 +19,44 @@ package com.android.inputmethod.keyboard;
import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
-import android.view.Gravity;
+import android.view.MotionEvent;
import android.view.View;
-import android.widget.PopupWindow;
-import com.android.inputmethod.keyboard.PointerTracker.DrawingProxy;
-import com.android.inputmethod.keyboard.PointerTracker.TimerProxy;
import com.android.inputmethod.latin.Constants;
-import com.android.inputmethod.latin.InputPointers;
+import com.android.inputmethod.latin.CoordinateUtils;
import com.android.inputmethod.latin.R;
/**
* A view that renders a virtual {@link MoreKeysKeyboard}. It handles rendering of keys and
* detecting key presses and touch movements.
*/
-public final class MoreKeysKeyboardView extends KeyboardView implements MoreKeysPanel {
- private final int[] mCoordinates = new int[2];
+public class MoreKeysKeyboardView extends KeyboardView implements MoreKeysPanel {
+ private final int[] mCoordinates = CoordinateUtils.newInstance();
private final KeyDetector mKeyDetector;
-
private Controller mController;
- private KeyboardActionListener mListener;
+ protected KeyboardActionListener mListener;
private int mOriginX;
private int mOriginY;
+ private Key mCurrentKey;
- private static final TimerProxy EMPTY_TIMER_PROXY = new TimerProxy.Adapter();
-
- private final KeyboardActionListener mMoreKeysKeyboardListener =
- new KeyboardActionListener.Adapter() {
- @Override
- public void onCodeInput(int primaryCode, int x, int y) {
- // Because a more keys keyboard doesn't need proximity characters correction, we don't
- // send touch event coordinates.
- mListener.onCodeInput(
- primaryCode, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
- }
-
- @Override
- public void onTextInput(CharSequence text) {
- mListener.onTextInput(text);
- }
-
- @Override
- public void onStartBatchInput() {
- mListener.onStartBatchInput();
- }
-
- @Override
- public void onUpdateBatchInput(InputPointers batchPointers) {
- mListener.onUpdateBatchInput(batchPointers);
- }
-
- @Override
- public void onEndBatchInput(InputPointers batchPointers) {
- mListener.onEndBatchInput(batchPointers);
- }
-
- @Override
- public void onCancelInput() {
- mListener.onCancelInput();
- }
-
- @Override
- public void onPressKey(int primaryCode) {
- mListener.onPressKey(primaryCode);
- }
-
- @Override
- public void onReleaseKey(int primaryCode, boolean withSliding) {
- mListener.onReleaseKey(primaryCode, withSliding);
- }
- };
+ private int mActivePointerId;
- public MoreKeysKeyboardView(Context context, AttributeSet attrs) {
+ public MoreKeysKeyboardView(final Context context, final AttributeSet attrs) {
this(context, attrs, R.attr.moreKeysKeyboardViewStyle);
}
- public MoreKeysKeyboardView(Context context, AttributeSet attrs, int defStyle) {
+ public MoreKeysKeyboardView(final Context context, final AttributeSet attrs,
+ final int defStyle) {
super(context, attrs, defStyle);
final Resources res = context.getResources();
mKeyDetector = new MoreKeysDetector(
res.getDimension(R.dimen.more_keys_keyboard_slide_allowance));
- setKeyPreviewPopupEnabled(false, 0);
}
@Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final Keyboard keyboard = getKeyboard();
if (keyboard != null) {
final int width = keyboard.mOccupiedWidth + getPaddingLeft() + getPaddingRight();
@@ -117,80 +68,162 @@ public final class MoreKeysKeyboardView extends KeyboardView implements MoreKeys
}
@Override
- public void setKeyboard(Keyboard keyboard) {
+ public void setKeyboard(final Keyboard keyboard) {
super.setKeyboard(keyboard);
mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
-getPaddingTop() + mVerticalCorrection);
}
@Override
- public KeyDetector getKeyDetector() {
- return mKeyDetector;
+ public void showMoreKeysPanel(final View parentView, final Controller controller,
+ final int pointX, final int pointY, final KeyboardActionListener listener) {
+ mController = controller;
+ mListener = listener;
+ final View container = getContainerView();
+ // The coordinates of panel's left-top corner in parentView's coordinate system.
+ final int x = pointX - getDefaultCoordX() - container.getPaddingLeft();
+ final int y = pointY - container.getMeasuredHeight() + container.getPaddingBottom();
+
+ parentView.getLocationInWindow(mCoordinates);
+ // Ensure the horizontal position of the panel does not extend past the screen edges.
+ final int maxX = parentView.getMeasuredWidth() - container.getMeasuredWidth();
+ final int panelX = Math.max(0, Math.min(maxX, x)) + CoordinateUtils.x(mCoordinates);
+ final int panelY = y + CoordinateUtils.y(mCoordinates);
+ container.setX(panelX);
+ container.setY(panelY);
+
+ mOriginX = x + container.getPaddingLeft();
+ mOriginY = y + container.getPaddingTop();
+ controller.onShowMoreKeysPanel(this);
}
- @Override
- public KeyboardActionListener getKeyboardActionListener() {
- return mMoreKeysKeyboardListener;
+ /**
+ * Returns the default x coordinate for showing this panel.
+ */
+ protected int getDefaultCoordX() {
+ return ((MoreKeysKeyboard)getKeyboard()).getDefaultCoordX();
}
@Override
- public DrawingProxy getDrawingProxy() {
- return this;
+ public void onDownEvent(final int x, final int y, final int pointerId, final long eventTime) {
+ mActivePointerId = pointerId;
+ onMoveKeyInternal(x, y, pointerId);
}
@Override
- public TimerProxy getTimerProxy() {
- return EMPTY_TIMER_PROXY;
+ public void onMoveEvent(int x, int y, final int pointerId, long eventTime) {
+ if (mActivePointerId != pointerId) {
+ return;
+ }
+ final boolean hasOldKey = (mCurrentKey != null);
+ onMoveKeyInternal(x, y, pointerId);
+ if (hasOldKey && mCurrentKey == null) {
+ // If the pointer has moved too far away from any target then cancel the panel.
+ mController.onCancelMoreKeysPanel();
+ }
}
@Override
- public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) {
- // More keys 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);
+ public void onUpEvent(final int x, final int y, final int pointerId, final long eventTime) {
+ if (mCurrentKey != null && mActivePointerId == pointerId) {
+ updateReleaseKeyGraphics(mCurrentKey);
+ onCodeInput(mCurrentKey.mCode, x, y);
+ mCurrentKey = null;
+ }
}
- @Override
- public void showMoreKeysPanel(View parentView, Controller controller, int pointX, int pointY,
- PopupWindow window, KeyboardActionListener listener) {
- mController = controller;
- mListener = listener;
- final View container = (View)getParent();
- final MoreKeysKeyboard pane = (MoreKeysKeyboard)getKeyboard();
- final int defaultCoordX = pane.getDefaultCoordX();
- // The coordinates of panel's left-top corner in parentView's coordinate system.
- final int x = pointX - defaultCoordX - container.getPaddingLeft();
- final int y = pointY - container.getMeasuredHeight() + container.getPaddingBottom();
+ /**
+ * Performs the specific action for this panel when the user presses a key on the panel.
+ */
+ protected void onCodeInput(final int code, final int x, final int y) {
+ if (code == Constants.CODE_OUTPUT_TEXT) {
+ mListener.onTextInput(mCurrentKey.getOutputText());
+ } else if (code != Constants.CODE_UNSPECIFIED) {
+ mListener.onCodeInput(code, x, y);
+ }
+ }
- window.setContentView(container);
- window.setWidth(container.getMeasuredWidth());
- window.setHeight(container.getMeasuredHeight());
- parentView.getLocationInWindow(mCoordinates);
- window.showAtLocation(parentView, Gravity.NO_GRAVITY,
- x + mCoordinates[0], y + mCoordinates[1]);
+ private void onMoveKeyInternal(int x, int y, int pointerId) {
+ if (mActivePointerId != pointerId) {
+ // Ignore old pointers when newer pointer is active.
+ return;
+ }
+ final Key oldKey = mCurrentKey;
+ final Key newKey = mKeyDetector.detectHitKey(x, y);
+ if (newKey != oldKey) {
+ mCurrentKey = newKey;
+ invalidateKey(mCurrentKey);
+ if (oldKey != null) {
+ updateReleaseKeyGraphics(oldKey);
+ }
+ if (newKey != null) {
+ updatePressKeyGraphics(newKey);
+ }
+ }
+ }
- mOriginX = x + container.getPaddingLeft();
- mOriginY = y + container.getPaddingTop();
+ private void updateReleaseKeyGraphics(final Key key) {
+ key.onReleased();
+ invalidateKey(key);
}
- private boolean mIsDismissing;
+ private void updatePressKeyGraphics(final Key key) {
+ key.onPressed();
+ invalidateKey(key);
+ }
@Override
public boolean dismissMoreKeysPanel() {
- if (mIsDismissing || mController == null) return false;
- mIsDismissing = true;
- final boolean dismissed = mController.dismissMoreKeysPanel();
- mIsDismissing = false;
- return dismissed;
+ if (mController == null) return false;
+ return mController.onDismissMoreKeysPanel();
}
@Override
- public int translateX(int x) {
+ public int translateX(final int x) {
return x - mOriginX;
}
@Override
- public int translateY(int y) {
+ public int translateY(final int y) {
return y - mOriginY;
}
+
+ @Override
+ public boolean onTouchEvent(final MotionEvent me) {
+ final int action = me.getActionMasked();
+ final long eventTime = me.getEventTime();
+ final int index = me.getActionIndex();
+ final int x = (int)me.getX(index);
+ final int y = (int)me.getY(index);
+ final int pointerId = me.getPointerId(index);
+ processMotionEvent(action, x, y, pointerId, eventTime);
+ return true;
+ }
+
+ public void processMotionEvent(final int action, final int x, final int y,
+ final int pointerId, final long eventTime) {
+ switch (action) {
+ case MotionEvent.ACTION_DOWN:
+ case MotionEvent.ACTION_POINTER_DOWN:
+ onDownEvent(x, y, pointerId, eventTime);
+ break;
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_POINTER_UP:
+ onUpEvent(x, y, pointerId, eventTime);
+ break;
+ case MotionEvent.ACTION_MOVE:
+ onMoveEvent(x, y, pointerId, eventTime);
+ break;
+ }
+ }
+
+ @Override
+ public View getContainerView() {
+ return (View)getParent();
+ }
+
+ @Override
+ public boolean isShowingInParent() {
+ return (getContainerView().getParent() != null);
+ }
}
diff --git a/java/src/com/android/inputmethod/keyboard/MoreKeysPanel.java b/java/src/com/android/inputmethod/keyboard/MoreKeysPanel.java
index f9a196d24..9c677e5c8 100644
--- a/java/src/com/android/inputmethod/keyboard/MoreKeysPanel.java
+++ b/java/src/com/android/inputmethod/keyboard/MoreKeysPanel.java
@@ -17,25 +17,77 @@
package com.android.inputmethod.keyboard;
import android.view.View;
-import android.widget.PopupWindow;
-public interface MoreKeysPanel extends PointerTracker.KeyEventHandler {
+public interface MoreKeysPanel {
public interface Controller {
- public boolean dismissMoreKeysPanel();
+ /**
+ * Add the {@link MoreKeysPanel} to the target view.
+ * @param panel
+ */
+ public void onShowMoreKeysPanel(final MoreKeysPanel panel);
+
+ /**
+ * Remove the current {@link MoreKeysPanel} from the target view.
+ */
+ public boolean onDismissMoreKeysPanel();
+
+ /**
+ * Instructs the parent to cancel the panel (e.g., when entering a different input mode).
+ */
+ public void onCancelMoreKeysPanel();
}
/**
- * Show more keys panel.
+ * Initializes the layout and event handling of this {@link MoreKeysPanel} and calls the
+ * controller's onShowMoreKeysPanel to add the panel's container view.
+ *
+ * @param parentView the parent view of this {@link MoreKeysPanel}
+ * @param controller the controller that can dismiss this {@link MoreKeysPanel}
+ * @param pointX x coordinate of this {@link MoreKeysPanel}
+ * @param pointY y coordinate of this {@link MoreKeysPanel}
+ * @param listener the listener that will receive keyboard action from this
+ * {@link MoreKeysPanel}.
+ */
+ // TODO: Currently the MoreKeysPanel is inside a container view that is added to the parent.
+ // Consider the simpler approach of placing the MoreKeysPanel itself into the parent view.
+ public void showMoreKeysPanel(View parentView, Controller controller, int pointX,
+ int pointY, KeyboardActionListener listener);
+
+ /**
+ * Dismisses the more keys panel and calls the controller's onDismissMoreKeysPanel to remove
+ * the panel's container view.
+ */
+ public boolean dismissMoreKeysPanel();
+
+ /**
+ * Process a move event on the more keys panel.
+ *
+ * @param x translated x coordinate of the touch point
+ * @param y translated y coordinate of the touch point
+ * @param pointerId pointer id touch point
+ * @param eventTime timestamp of touch point
+ */
+ public void onMoveEvent(final int x, final int y, final int pointerId, final long eventTime);
+
+ /**
+ * Process a down event on the more keys panel.
+ *
+ * @param x translated x coordinate of the touch point
+ * @param y translated y coordinate of the touch point
+ * @param pointerId pointer id touch point
+ * @param eventTime timestamp of touch point
+ */
+ public void onDownEvent(final int x, final int y, final int pointerId, final long eventTime);
+
+ /**
+ * Process an up event on the more keys panel.
*
- * @param parentView the parent view of this more keys panel
- * @param controller the controller that can dismiss this more keys panel
- * @param pointX x coordinate of this more keys panel
- * @param pointY y coordinate of this more keys panel
- * @param window PopupWindow to be used to show this more keys panel
- * @param listener the listener that will receive keyboard action from this more keys panel.
+ * @param x translated x coordinate of the touch point
+ * @param y translated y coordinate of the touch point
+ * @param pointerId pointer id touch point
+ * @param eventTime timestamp of touch point
*/
- public void showMoreKeysPanel(View parentView, Controller controller, int pointX, int pointY,
- PopupWindow window, KeyboardActionListener listener);
+ public void onUpEvent(final int x, final int y, final int pointerId, final long eventTime);
/**
* Translate X-coordinate of touch event to the local X-coordinate of this
@@ -54,4 +106,14 @@ public interface MoreKeysPanel extends PointerTracker.KeyEventHandler {
* @return the local Y-coordinate to this {@link MoreKeysPanel}
*/
public int translateY(int y);
+
+ /**
+ * Return the view containing the more keys panel.
+ */
+ public View getContainerView();
+
+ /**
+ * Return whether the panel is currently being shown.
+ */
+ public boolean isShowingInParent();
}
diff --git a/java/src/com/android/inputmethod/keyboard/PointerTracker.java b/java/src/com/android/inputmethod/keyboard/PointerTracker.java
index d0f7cb276..d54b98ccc 100644
--- a/java/src/com/android/inputmethod/keyboard/PointerTracker.java
+++ b/java/src/com/android/inputmethod/keyboard/PointerTracker.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -27,6 +27,8 @@ import com.android.inputmethod.keyboard.internal.GestureStroke.GestureStrokePara
import com.android.inputmethod.keyboard.internal.GestureStrokeWithPreviewPoints;
import com.android.inputmethod.keyboard.internal.PointerTrackerQueue;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
+import com.android.inputmethod.latin.CoordinateUtils;
import com.android.inputmethod.latin.InputPointers;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
@@ -75,11 +77,13 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
public TimerProxy getTimerProxy();
}
- public interface DrawingProxy extends MoreKeysPanel.Controller {
+ public interface DrawingProxy {
public void invalidateKey(Key key);
public void showKeyPreview(PointerTracker tracker);
public void dismissKeyPreview(PointerTracker tracker);
- public void showGesturePreviewTrail(PointerTracker tracker, boolean isOldestTracker);
+ public void showSlidingKeyInputPreview(PointerTracker tracker);
+ public void dismissSlidingKeyInputPreview();
+ public void showGesturePreviewTrail(PointerTracker tracker);
}
public interface TimerProxy {
@@ -93,6 +97,9 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
public void cancelDoubleTapTimer();
public boolean isInDoubleTapTimeout();
public void cancelKeyTimers();
+ public void startUpdateBatchInputTimer(PointerTracker tracker);
+ public void cancelUpdateBatchInputTimer(PointerTracker tracker);
+ public void cancelAllUpdateBatchInputTimers();
public static class Adapter implements TimerProxy {
@Override
@@ -115,6 +122,12 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
public boolean isInDoubleTapTimeout() { return false; }
@Override
public void cancelKeyTimers() {}
+ @Override
+ public void startUpdateBatchInputTimer(PointerTracker tracker) {}
+ @Override
+ public void cancelUpdateBatchInputTimer(PointerTracker tracker) {}
+ @Override
+ public void cancelAllUpdateBatchInputTimers() {}
}
}
@@ -156,7 +169,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
private static final boolean sNeedsProximateBogusDownMoveUpEventHack = true;
private static final ArrayList<PointerTracker> sTrackers = CollectionUtils.newArrayList();
- private static PointerTrackerQueue sPointerTrackerQueue;
+ private static final PointerTrackerQueue sPointerTrackerQueue = new PointerTrackerQueue();
public final int mPointerId;
@@ -289,6 +302,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
// The position and time at which first down event occurred.
private long mDownTime;
+ private int[] mDownCoordinates = CoordinateUtils.newInstance();
private long mUpTime;
// The current key where this pointer is.
@@ -304,11 +318,11 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
// true if keyboard layout has been changed.
private boolean mKeyboardLayoutHasBeenChanged;
- // true if event is already translated to a key action.
- private boolean mKeyAlreadyProcessed;
+ // true if this pointer is no longer tracking touch event.
+ private boolean mIsTrackingCanceled;
- // true if this pointer has been long-pressed and is showing a more keys panel.
- private boolean mIsShowingMoreKeysPanel;
+ // the more keys panel currently being shown. equals null if no panel is active.
+ private MoreKeysPanel mMoreKeysPanel;
// true if this pointer is in a sliding key input.
boolean mIsInSlidingKeyInput;
@@ -325,13 +339,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
private final GestureStrokeWithPreviewPoints mGestureStrokeWithPreviewPoints;
- public static void init(boolean hasDistinctMultitouch,
- boolean needsPhantomSuddenMoveEventHack) {
- if (hasDistinctMultitouch) {
- sPointerTrackerQueue = new PointerTrackerQueue();
- } else {
- sPointerTrackerQueue = null;
- }
+ public static void init(final boolean needsPhantomSuddenMoveEventHack) {
sNeedsPhantomSuddenMoveEventHack = needsPhantomSuddenMoveEventHack;
sParams = PointerTrackerParams.DEFAULT;
sGestureStrokeParams = GestureStrokeParams.DEFAULT;
@@ -375,7 +383,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
}
public static boolean isAnyInSlidingKeyInput() {
- return sPointerTrackerQueue != null ? sPointerTrackerQueue.isAnyInSlidingKeyInput() : false;
+ return sPointerTrackerQueue.isAnyInSlidingKeyInput();
}
public static void setKeyboardActionListener(final KeyboardActionListener listener) {
@@ -407,6 +415,17 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
}
}
+ public static void dismissAllMoreKeysPanels() {
+ final int trackersSize = sTrackers.size();
+ for (int i = 0; i < trackersSize; ++i) {
+ final PointerTracker tracker = sTrackers.get(i);
+ if (tracker.isShowingMoreKeysPanel()) {
+ tracker.mMoreKeysPanel.dismissMoreKeysPanel();
+ tracker.mMoreKeysPanel = null;
+ }
+ }
+ }
+
private PointerTracker(final int id, final KeyEventHandler handler) {
if (handler == null) {
throw new NullPointerException();
@@ -453,8 +472,8 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
final boolean altersCode = key.altCodeWhileTyping() && mTimerProxy.isTypingState();
final int code = altersCode ? key.getAltCode() : primaryCode;
if (DEBUG_LISTENER) {
- final String output = code == Keyboard.CODE_OUTPUT_TEXT
- ? key.getOutputText() : Keyboard.printableCode(code);
+ final String output = code == Constants.CODE_OUTPUT_TEXT
+ ? key.getOutputText() : Constants.printableCode(code);
Log.d(TAG, String.format("[%d] onCodeInput: %4d %4d %s%s%s", mPointerId, x, y,
output, ignoreModifierKey ? " ignoreModifier" : "",
altersCode ? " altersCode" : "", key.isEnabled() ? "" : " disabled"));
@@ -469,9 +488,9 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
// Even if the key is disabled, it should respond if it is in the altCodeWhileTyping state.
if (key.isEnabled() || altersCode) {
sTimeRecorder.onCodeInput(code, eventTime);
- if (code == Keyboard.CODE_OUTPUT_TEXT) {
+ if (code == Constants.CODE_OUTPUT_TEXT) {
mListener.onTextInput(key.getOutputText());
- } else if (code != Keyboard.CODE_UNSPECIFIED) {
+ } else if (code != Constants.CODE_UNSPECIFIED) {
mListener.onCodeInput(code, x, y);
}
}
@@ -487,7 +506,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
final boolean ignoreModifierKey = mIsInSlidingKeyInputFromModifier && key.isModifier();
if (DEBUG_LISTENER) {
Log.d(TAG, String.format("[%d] onRelease : %s%s%s%s", mPointerId,
- Keyboard.printableCode(primaryCode),
+ Constants.printableCode(primaryCode),
withSliding ? " sliding" : "", ignoreModifierKey ? " ignoreModifier" : "",
key.isEnabled() ? "": " disabled"));
}
@@ -522,7 +541,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
mKeyboard = keyDetector.getKeyboard();
final int keyWidth = mKeyboard.mMostCommonKeyWidth;
final int keyHeight = mKeyboard.mMostCommonKeyHeight;
- mGestureStrokeWithPreviewPoints.setKeyboardGeometry(keyWidth);
+ mGestureStrokeWithPreviewPoints.setKeyboardGeometry(keyWidth, mKeyboard.mOccupiedHeight);
final Key newKey = mKeyDetector.detectHitKey(mKeyX, mKeyY);
if (newKey != mCurrentKey) {
if (mDrawingProxy != null) {
@@ -539,6 +558,10 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
return mIsInSlidingKeyInput;
}
+ public boolean isInSlidingKeyInputFromModifier() {
+ return mIsInSlidingKeyInputFromModifier;
+ }
+
public Key getKey() {
return mCurrentKey;
}
@@ -641,20 +664,21 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
return mGestureStrokeWithPreviewPoints;
}
- public int getLastX() {
- return mLastX;
- }
-
- public int getLastY() {
- return mLastY;
+ public void getLastCoordinates(final int[] outCoords) {
+ CoordinateUtils.set(outCoords, mLastX, mLastY);
}
public long getDownTime() {
return mDownTime;
}
+ public void getDownCoordinates(final int[] outCoords) {
+ CoordinateUtils.copy(outCoords, mDownCoordinates);
+ }
+
private Key onDownKey(final int x, final int y, final long eventTime) {
mDownTime = eventTime;
+ CoordinateUtils.set(mDownCoordinates, x, y);
mBogusMoveEventDetector.onDownKey();
return onMoveToNewKey(onMoveKeyInternal(x, y), x, y);
}
@@ -682,7 +706,11 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
}
private static int getActivePointerTrackerCount() {
- return (sPointerTrackerQueue == null) ? 1 : sPointerTrackerQueue.size();
+ return sPointerTrackerQueue.size();
+ }
+
+ public boolean isOldestTrackerInQueue() {
+ return sPointerTrackerQueue.getOldestElement() == this;
}
private void mayStartBatchInput(final Key key) {
@@ -701,48 +729,80 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
sLastRecognitionPointSize = 0;
sLastRecognitionTime = 0;
mListener.onStartBatchInput();
+ dismissAllMoreKeysPanels();
}
- final boolean isOldestTracker = sPointerTrackerQueue.getOldestElement() == this;
- mDrawingProxy.showGesturePreviewTrail(this, isOldestTracker);
+ mTimerProxy.cancelLongPressTimer();
+ mDrawingProxy.showGesturePreviewTrail(this);
+ }
+
+ public void updateBatchInputByTimer(final long eventTime) {
+ final int gestureTime = (int)(eventTime - sGestureFirstDownTime);
+ mGestureStrokeWithPreviewPoints.duplicateLastPointWith(gestureTime);
+ updateBatchInput(eventTime);
}
private void mayUpdateBatchInput(final long eventTime, final Key key) {
if (key != null) {
- synchronized (sAggregratedPointers) {
- final GestureStroke stroke = mGestureStrokeWithPreviewPoints;
- stroke.appendIncrementalBatchPoints(sAggregratedPointers);
- final int size = sAggregratedPointers.getPointerSize();
- if (size > sLastRecognitionPointSize
- && stroke.hasRecognitionTimePast(eventTime, sLastRecognitionTime)) {
- sLastRecognitionPointSize = size;
- sLastRecognitionTime = eventTime;
- if (DEBUG_LISTENER) {
- Log.d(TAG, String.format("[%d] onUpdateBatchInput: batchPoints=%d",
- mPointerId, size));
- }
- mListener.onUpdateBatchInput(sAggregratedPointers);
+ updateBatchInput(eventTime);
+ }
+ if (mIsTrackingCanceled) {
+ return;
+ }
+ mDrawingProxy.showGesturePreviewTrail(this);
+ }
+
+ private void updateBatchInput(final long eventTime) {
+ synchronized (sAggregratedPointers) {
+ final GestureStroke stroke = mGestureStrokeWithPreviewPoints;
+ stroke.appendIncrementalBatchPoints(sAggregratedPointers);
+ final int size = sAggregratedPointers.getPointerSize();
+ if (size > sLastRecognitionPointSize
+ && stroke.hasRecognitionTimePast(eventTime, sLastRecognitionTime)) {
+ sLastRecognitionPointSize = size;
+ sLastRecognitionTime = eventTime;
+ if (DEBUG_LISTENER) {
+ Log.d(TAG, String.format("[%d] onUpdateBatchInput: batchPoints=%d", mPointerId,
+ size));
}
+ mTimerProxy.startUpdateBatchInputTimer(this);
+ mListener.onUpdateBatchInput(sAggregratedPointers);
}
}
- final boolean isOldestTracker = sPointerTrackerQueue.getOldestElement() == this;
- mDrawingProxy.showGesturePreviewTrail(this, isOldestTracker);
}
private void mayEndBatchInput(final long eventTime) {
synchronized (sAggregratedPointers) {
mGestureStrokeWithPreviewPoints.appendAllBatchPoints(sAggregratedPointers);
if (getActivePointerTrackerCount() == 1) {
- if (DEBUG_LISTENER) {
- Log.d(TAG, String.format("[%d] onEndBatchInput : batchPoints=%d",
- mPointerId, sAggregratedPointers.getPointerSize()));
- }
sInGesture = false;
sTimeRecorder.onEndBatchInput(eventTime);
- mListener.onEndBatchInput(sAggregratedPointers);
+ mTimerProxy.cancelAllUpdateBatchInputTimers();
+ if (!mIsTrackingCanceled) {
+ if (DEBUG_LISTENER) {
+ Log.d(TAG, String.format("[%d] onEndBatchInput : batchPoints=%d",
+ mPointerId, sAggregratedPointers.getPointerSize()));
+ }
+ mListener.onEndBatchInput(sAggregratedPointers);
+ }
}
}
- final boolean isOldestTracker = sPointerTrackerQueue.getOldestElement() == this;
- mDrawingProxy.showGesturePreviewTrail(this, isOldestTracker);
+ if (mIsTrackingCanceled) {
+ return;
+ }
+ mDrawingProxy.showGesturePreviewTrail(this);
+ }
+
+ private void cancelBatchInput() {
+ sPointerTrackerQueue.cancelAllPointerTracker();
+ mIsDetectingGesture = false;
+ if (!sInGesture) {
+ return;
+ }
+ sInGesture = false;
+ if (DEBUG_LISTENER) {
+ Log.d(TAG, String.format("[%d] onCancelBatchInput", mPointerId));
+ }
+ mListener.onCancelBatchInput();
}
public void processMotionEvent(final int action, final int x, final int y, final long eventTime,
@@ -770,7 +830,6 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
if (DEBUG_EVENT) {
printTouchEvent("onDownEvent:", x, y, eventTime);
}
-
mDrawingProxy = handler.getDrawingProxy();
mTimerProxy = handler.getTimerProxy();
setKeyboardActionListener(handler.getKeyboardActionListener());
@@ -787,29 +846,26 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.pointerTracker_onDownEvent(deltaT, distance * distance);
}
- mKeyAlreadyProcessed = true;
+ cancelTracking();
return;
}
}
final Key key = getKeyOn(x, y);
mBogusMoveEventDetector.onActualDownEvent(x, y);
- final PointerTrackerQueue queue = sPointerTrackerQueue;
- if (queue != null) {
- if (key != null && key.isModifier()) {
- // Before processing a down event of modifier key, all pointers already being
- // tracked should be released.
- queue.releaseAllPointers(eventTime);
- }
- queue.add(this);
+ if (key != null && key.isModifier()) {
+ // Before processing a down event of modifier key, all pointers already being
+ // tracked should be released.
+ sPointerTrackerQueue.releaseAllPointers(eventTime);
}
+ sPointerTrackerQueue.add(this);
onDownEventInternal(x, y, eventTime);
if (!sShouldHandleGesture) {
return;
}
- // A gesture should start only from the letter key.
+ // A gesture should start only from a non-modifier key.
mIsDetectingGesture = (mKeyboard != null) && mKeyboard.mId.isAlphabetKeyboard()
- && !mIsShowingMoreKeysPanel && key != null && Keyboard.isLetterCode(key.mCode);
+ && key != null && !key.isModifier();
if (mIsDetectingGesture) {
if (getActivePointerTrackerCount() == 1) {
sGestureFirstDownTime = eventTime;
@@ -819,6 +875,10 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
}
}
+ private boolean isShowingMoreKeysPanel() {
+ return (mMoreKeysPanel != null);
+ }
+
private void onDownEventInternal(final int x, final int y, final long eventTime) {
Key key = onDownKey(x, y, eventTime);
// Sliding key is allowed when 1) enabled by configuration, 2) this pointer starts sliding
@@ -827,7 +887,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
|| (key != null && key.isModifier())
|| mKeyDetector.alwaysAllowsSlidingInput();
mKeyboardLayoutHasBeenChanged = false;
- mKeyAlreadyProcessed = false;
+ mIsTrackingCanceled = false;
resetSlidingKeyInput();
if (key != null) {
// This onPress call may have changed keyboard layout. Those cases are detected at
@@ -853,13 +913,29 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
private void resetSlidingKeyInput() {
mIsInSlidingKeyInput = false;
mIsInSlidingKeyInputFromModifier = false;
+ mDrawingProxy.dismissSlidingKeyInputPreview();
}
private void onGestureMoveEvent(final int x, final int y, final long eventTime,
final boolean isMajorEvent, final Key key) {
final int gestureTime = (int)(eventTime - sGestureFirstDownTime);
if (mIsDetectingGesture) {
- mGestureStrokeWithPreviewPoints.addPoint(x, y, gestureTime, isMajorEvent);
+ final int beforeLength = mGestureStrokeWithPreviewPoints.getLength();
+ final boolean onValidArea = mGestureStrokeWithPreviewPoints.addPointOnKeyboard(
+ x, y, gestureTime, isMajorEvent);
+ if (mGestureStrokeWithPreviewPoints.getLength() > beforeLength) {
+ mTimerProxy.startUpdateBatchInputTimer(this);
+ }
+ // If the move event goes out from valid batch input area, cancel batch input.
+ if (!onValidArea) {
+ cancelBatchInput();
+ return;
+ }
+ // If the MoreKeysPanel is showing then do not attempt to enter gesture mode. However,
+ // the gestured touch points are still being recorded in case the panel is dismissed.
+ if (isShowingMoreKeysPanel()) {
+ return;
+ }
mayStartBatchInput(key);
if (sInGesture) {
mayUpdateBatchInput(eventTime, key);
@@ -871,7 +947,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
if (DEBUG_MOVE_EVENT) {
printTouchEvent("onMoveEvent:", x, y, eventTime);
}
- if (mKeyAlreadyProcessed) {
+ if (mIsTrackingCanceled) {
return;
}
@@ -888,141 +964,164 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
}
}
+ if (isShowingMoreKeysPanel()) {
+ final int translatedX = mMoreKeysPanel.translateX(x);
+ final int translatedY = mMoreKeysPanel.translateY(y);
+ mMoreKeysPanel.onMoveEvent(translatedX, translatedY, mPointerId, eventTime);
+ onMoveKey(x, y);
+ mDrawingProxy.showSlidingKeyInputPreview(this);
+ return;
+ }
onMoveEventInternal(x, y, eventTime);
}
+ private void processSlidingKeyInput(final Key newKey, final int x, final int y,
+ final long eventTime) {
+ // This onPress call may have changed keyboard layout. Those cases are detected
+ // at {@link #setKeyboard}. In those cases, we should update key according
+ // to the new keyboard layout.
+ Key key = newKey;
+ if (callListenerOnPressAndCheckKeyboardLayoutChange(key)) {
+ key = onMoveKey(x, y);
+ }
+ onMoveToNewKey(key, x, y);
+ startLongPressTimer(key);
+ setPressedKeyGraphics(key, eventTime);
+ }
+
+ private void processPhantomSuddenMoveHack(final Key key, final int x, final int y,
+ final long eventTime, final Key oldKey, final int lastX, final int lastY) {
+ if (DEBUG_MODE) {
+ Log.w(TAG, String.format("[%d] onMoveEvent:"
+ + " phantom sudden move event (distance=%d) is translated to "
+ + "up[%d,%d,%s]/down[%d,%d,%s] events", mPointerId,
+ getDistance(x, y, lastX, lastY),
+ lastX, lastY, Constants.printableCode(oldKey.mCode),
+ x, y, Constants.printableCode(key.mCode)));
+ }
+ // TODO: This should be moved to outside of this nested if-clause?
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.pointerTracker_onMoveEvent(x, y, lastX, lastY);
+ }
+ onUpEventInternal(x, y, eventTime);
+ onDownEventInternal(x, y, eventTime);
+ }
+
+ private void processProximateBogusDownMoveUpEventHack(final Key key, final int x, final int y,
+ final long eventTime, final Key oldKey, final int lastX, final int lastY) {
+ if (DEBUG_MODE) {
+ final float keyDiagonal = (float)Math.hypot(
+ mKeyboard.mMostCommonKeyWidth, mKeyboard.mMostCommonKeyHeight);
+ final float radiusRatio =
+ mBogusMoveEventDetector.getDistanceFromDownEvent(x, y)
+ / keyDiagonal;
+ Log.w(TAG, String.format("[%d] onMoveEvent:"
+ + " bogus down-move-up event (raidus=%.2f key diagonal) is "
+ + " translated to up[%d,%d,%s]/down[%d,%d,%s] events",
+ mPointerId, radiusRatio,
+ lastX, lastY, Constants.printableCode(oldKey.mCode),
+ x, y, Constants.printableCode(key.mCode)));
+ }
+ onUpEventInternal(x, y, eventTime);
+ onDownEventInternal(x, y, eventTime);
+ }
+
+ private void processSildeOutFromOldKey(final Key oldKey) {
+ setReleasedKeyGraphics(oldKey);
+ callListenerOnRelease(oldKey, oldKey.mCode, true);
+ startSlidingKeyInput(oldKey);
+ mTimerProxy.cancelKeyTimers();
+ }
+
+ private void slideFromOldKeyToNewKey(final Key key, final int x, final int y,
+ final long eventTime, final Key oldKey, final int lastX, final int lastY) {
+ // 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.
+ processSildeOutFromOldKey(oldKey);
+ startRepeatKey(key);
+ if (mIsAllowedSlidingKeyInput) {
+ processSlidingKeyInput(key, x, y, eventTime);
+ }
+ // HACK: On some devices, quick successive touches may be reported as a sudden move by
+ // touch panel firmware. This hack detects such cases and translates the move event to
+ // successive up and down events.
+ // TODO: Should find a way to balance gesture detection and this hack.
+ else if (sNeedsPhantomSuddenMoveEventHack
+ && getDistance(x, y, lastX, lastY) >= mPhantonSuddenMoveThreshold) {
+ processPhantomSuddenMoveHack(key, x, y, eventTime, oldKey, lastX, lastY);
+ }
+ // HACK: On some devices, quick successive proximate touches may be reported as a bogus
+ // down-move-up event by touch panel firmware. This hack detects such cases and breaks
+ // these events into separate up and down events.
+ else if (sNeedsProximateBogusDownMoveUpEventHack && sTimeRecorder.isInFastTyping(eventTime)
+ && mBogusMoveEventDetector.isCloseToActualDownEvent(x, y)) {
+ processProximateBogusDownMoveUpEventHack(key, x, y, eventTime, oldKey, lastX, lastY);
+ }
+ // HACK: If there are currently multiple touches, register the key even if the finger
+ // slides off the key. This defends against noise from some touch panels when there are
+ // close multiple touches.
+ // Caveat: When in chording input mode with a modifier key, we don't use this hack.
+ else if (getActivePointerTrackerCount() > 1
+ && !sPointerTrackerQueue.hasModifierKeyOlderThan(this)) {
+ if (DEBUG_MODE) {
+ Log.w(TAG, String.format("[%d] onMoveEvent:"
+ + " detected sliding finger while multi touching", mPointerId));
+ }
+ onUpEvent(x, y, eventTime);
+ cancelTracking();
+ setReleasedKeyGraphics(oldKey);
+ } else {
+ if (!mIsDetectingGesture) {
+ cancelTracking();
+ }
+ setReleasedKeyGraphics(oldKey);
+ }
+ }
+
+ private void slideOutFromOldKey(final Key oldKey, final int x, final int y) {
+ // The pointer has been slid out from the previous key, we must call onRelease() to
+ // notify that the previous key has been released.
+ processSildeOutFromOldKey(oldKey);
+ if (mIsAllowedSlidingKeyInput) {
+ onMoveToNewKey(null, x, y);
+ } else {
+ if (!mIsDetectingGesture) {
+ cancelTracking();
+ }
+ }
+ }
+
private void onMoveEventInternal(final int x, final int y, final long eventTime) {
final int lastX = mLastX;
final int lastY = mLastY;
final Key oldKey = mCurrentKey;
- Key key = onMoveKey(x, y);
+ final Key newKey = onMoveKey(x, y);
if (sShouldHandleGesture) {
// Register move event on gesture tracker.
- onGestureMoveEvent(x, y, eventTime, true /* isMajorEvent */, key);
+ onGestureMoveEvent(x, y, eventTime, true /* isMajorEvent */, newKey);
if (sInGesture) {
- mTimerProxy.cancelLongPressTimer();
mCurrentKey = null;
setReleasedKeyGraphics(oldKey);
return;
}
}
- if (key != null) {
- if (oldKey == null) {
+ if (newKey != null) {
+ if (oldKey != null && isMajorEnoughMoveToBeOnNewKey(x, y, eventTime, newKey)) {
+ slideFromOldKeyToNewKey(newKey, x, y, eventTime, oldKey, lastX, lastY);
+ } else if (oldKey == null) {
// The pointer has been slid in to the new key, but the finger was not on any keys.
// In this case, we must call onPress() to notify that the new key is being pressed.
- // This onPress call may have changed keyboard layout. Those cases are detected at
- // {@link #setKeyboard}. In those cases, we should update key according to the
- // new keyboard layout.
- if (callListenerOnPressAndCheckKeyboardLayoutChange(key)) {
- key = onMoveKey(x, y);
- }
- onMoveToNewKey(key, x, y);
- startLongPressTimer(key);
- setPressedKeyGraphics(key, eventTime);
- } else if (isMajorEnoughMoveToBeOnNewKey(x, y, eventTime, key)) {
- // 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.
- setReleasedKeyGraphics(oldKey);
- callListenerOnRelease(oldKey, oldKey.mCode, true);
- startSlidingKeyInput(oldKey);
- mTimerProxy.cancelKeyTimers();
- startRepeatKey(key);
- if (mIsAllowedSlidingKeyInput) {
- // This onPress call may have changed keyboard layout. Those cases are detected
- // at {@link #setKeyboard}. In those cases, we should update key according
- // to the new keyboard layout.
- if (callListenerOnPressAndCheckKeyboardLayoutChange(key)) {
- key = onMoveKey(x, y);
- }
- onMoveToNewKey(key, x, y);
- startLongPressTimer(key);
- setPressedKeyGraphics(key, eventTime);
- } else {
- // HACK: On some devices, quick successive touches may be reported as a sudden
- // move by touch panel firmware. This hack detects such cases and translates the
- // move event to successive up and down events.
- // TODO: Should find a way to balance gesture detection and this hack.
- if (sNeedsPhantomSuddenMoveEventHack
- && getDistance(x, y, lastX, lastY) >= mPhantonSuddenMoveThreshold) {
- if (DEBUG_MODE) {
- Log.w(TAG, String.format("[%d] onMoveEvent:"
- + " phantom sudden move event (distance=%d) is translated to "
- + "up[%d,%d,%s]/down[%d,%d,%s] events", mPointerId,
- getDistance(x, y, lastX, lastY),
- lastX, lastY, Keyboard.printableCode(oldKey.mCode),
- x, y, Keyboard.printableCode(key.mCode)));
- }
- // TODO: This should be moved to outside of this nested if-clause?
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.pointerTracker_onMoveEvent(x, y, lastX, lastY);
- }
- onUpEventInternal(eventTime);
- onDownEventInternal(x, y, eventTime);
- }
- // HACK: On some devices, quick successive proximate touches may be reported as
- // a bogus down-move-up event by touch panel firmware. This hack detects such
- // cases and breaks these events into separate up and down events.
- else if (sNeedsProximateBogusDownMoveUpEventHack
- && sTimeRecorder.isInFastTyping(eventTime)
- && mBogusMoveEventDetector.isCloseToActualDownEvent(x, y)) {
- if (DEBUG_MODE) {
- final float keyDiagonal = (float)Math.hypot(
- mKeyboard.mMostCommonKeyWidth, mKeyboard.mMostCommonKeyHeight);
- final float radiusRatio =
- mBogusMoveEventDetector.getDistanceFromDownEvent(x, y)
- / keyDiagonal;
- Log.w(TAG, String.format("[%d] onMoveEvent:"
- + " bogus down-move-up event (raidus=%.2f key diagonal) is "
- + " translated to up[%d,%d,%s]/down[%d,%d,%s] events",
- mPointerId, radiusRatio,
- lastX, lastY, Keyboard.printableCode(oldKey.mCode),
- x, y, Keyboard.printableCode(key.mCode)));
- }
- onUpEventInternal(eventTime);
- onDownEventInternal(x, y, eventTime);
- } else {
- // HACK: If there are currently multiple touches, register the key even if
- // the finger slides off the key. This defends against noise from some
- // touch panels when there are close multiple touches.
- // Caveat: When in chording input mode with a modifier key, we don't use
- // this hack.
- if (getActivePointerTrackerCount() > 1 && sPointerTrackerQueue != null
- && !sPointerTrackerQueue.hasModifierKeyOlderThan(this)) {
- if (DEBUG_MODE) {
- Log.w(TAG, String.format("[%d] onMoveEvent:"
- + " detected sliding finger while multi touching",
- mPointerId));
- }
- onUpEvent(x, y, eventTime);
- mKeyAlreadyProcessed = true;
- }
- if (!mIsDetectingGesture) {
- mKeyAlreadyProcessed = true;
- }
- setReleasedKeyGraphics(oldKey);
- }
- }
+ processSlidingKeyInput(newKey, x, y, eventTime);
}
- } else {
- if (oldKey != null && isMajorEnoughMoveToBeOnNewKey(x, y, eventTime, key)) {
- // The pointer has been slid out from the previous key, we must call onRelease() to
- // notify that the previous key has been released.
- setReleasedKeyGraphics(oldKey);
- callListenerOnRelease(oldKey, oldKey.mCode, true);
- startSlidingKeyInput(oldKey);
- mTimerProxy.cancelLongPressTimer();
- if (mIsAllowedSlidingKeyInput) {
- onMoveToNewKey(key, x, y);
- } else {
- if (!mIsDetectingGesture) {
- mKeyAlreadyProcessed = true;
- }
- }
+ } else { // newKey == null
+ if (oldKey != null && isMajorEnoughMoveToBeOnNewKey(x, y, eventTime, newKey)) {
+ slideOutFromOldKey(oldKey, x, y);
}
}
+ mDrawingProxy.showSlidingKeyInputPreview(this);
}
public void onUpEvent(final int x, final int y, final long eventTime) {
@@ -1030,22 +1129,18 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
printTouchEvent("onUpEvent :", x, y, eventTime);
}
- final PointerTrackerQueue queue = sPointerTrackerQueue;
- if (queue != null) {
- if (!sInGesture) {
- if (mCurrentKey != null && mCurrentKey.isModifier()) {
- // Before processing an up event of modifier key, all pointers already being
- // tracked should be released.
- queue.releaseAllPointersExcept(this, eventTime);
- } else {
- queue.releaseAllPointersOlderThan(this, eventTime);
- }
+ mTimerProxy.cancelUpdateBatchInputTimer(this);
+ if (!sInGesture) {
+ if (mCurrentKey != null && mCurrentKey.isModifier()) {
+ // Before processing an up event of modifier key, all pointers already being
+ // tracked should be released.
+ sPointerTrackerQueue.releaseAllPointersExcept(this, eventTime);
+ } else {
+ sPointerTrackerQueue.releaseAllPointersOlderThan(this, eventTime);
}
}
- onUpEventInternal(eventTime);
- if (queue != null) {
- queue.remove(this);
- }
+ onUpEventInternal(x, y, eventTime);
+ sPointerTrackerQueue.remove(this);
}
// Let this pointer tracker know that one of newer-than-this pointer trackers got an up event.
@@ -1054,13 +1149,16 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
@Override
public void onPhantomUpEvent(final long eventTime) {
if (DEBUG_EVENT) {
- printTouchEvent("onPhntEvent:", getLastX(), getLastY(), eventTime);
+ printTouchEvent("onPhntEvent:", mLastX, mLastY, eventTime);
}
- onUpEventInternal(eventTime);
- mKeyAlreadyProcessed = true;
+ if (isShowingMoreKeysPanel()) {
+ return;
+ }
+ onUpEventInternal(mLastX, mLastY, eventTime);
+ cancelTracking();
}
- private void onUpEventInternal(final long eventTime) {
+ private void onUpEventInternal(final int x, final int y, final long eventTime) {
mTimerProxy.cancelKeyTimers();
resetSlidingKeyInput();
mIsDetectingGesture = false;
@@ -1068,9 +1166,16 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
mCurrentKey = null;
// Release the last pressed key.
setReleasedKeyGraphics(currentKey);
- if (mIsShowingMoreKeysPanel) {
- mDrawingProxy.dismissMoreKeysPanel();
- mIsShowingMoreKeysPanel = false;
+
+ if (isShowingMoreKeysPanel()) {
+ if (!mIsTrackingCanceled) {
+ final int translatedX = mMoreKeysPanel.translateX(x);
+ final int translatedY = mMoreKeysPanel.translateY(y);
+ mMoreKeysPanel.onUpEvent(translatedX, translatedY, mPointerId, eventTime);
+ }
+ mMoreKeysPanel.dismissMoreKeysPanel();
+ mMoreKeysPanel = null;
+ return;
}
if (sInGesture) {
@@ -1081,7 +1186,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
return;
}
- if (mKeyAlreadyProcessed) {
+ if (mIsTrackingCanceled) {
return;
}
if (currentKey != null && !currentKey.isRepeatable()) {
@@ -1089,19 +1194,27 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
}
}
- public void onShowMoreKeysPanel(final int x, final int y, final KeyEventHandler handler) {
- onLongPressed();
- mIsShowingMoreKeysPanel = true;
- onDownEvent(x, y, SystemClock.uptimeMillis(), handler);
+ public void onShowMoreKeysPanel(final int translatedX, final int translatedY,
+ final MoreKeysPanel panel) {
+ setReleasedKeyGraphics(mCurrentKey);
+ final long eventTime = SystemClock.uptimeMillis();
+ mMoreKeysPanel = panel;
+ mMoreKeysPanel.onDownEvent(translatedX, translatedY, mPointerId, eventTime);
+ }
+
+ @Override
+ public void cancelTracking() {
+ if (isShowingMoreKeysPanel()) {
+ return;
+ }
+ mIsTrackingCanceled = true;
}
public void onLongPressed() {
- mKeyAlreadyProcessed = true;
+ resetSlidingKeyInput();
+ cancelTracking();
setReleasedKeyGraphics(mCurrentKey);
- final PointerTrackerQueue queue = sPointerTrackerQueue;
- if (queue != null) {
- queue.remove(this);
- }
+ sPointerTrackerQueue.remove(this);
}
public void onCancelEvent(final int x, final int y, final long eventTime) {
@@ -1109,11 +1222,9 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
printTouchEvent("onCancelEvt:", x, y, eventTime);
}
- final PointerTrackerQueue queue = sPointerTrackerQueue;
- if (queue != null) {
- queue.releaseAllPointersExcept(this, eventTime);
- queue.remove(this);
- }
+ cancelBatchInput();
+ sPointerTrackerQueue.cancelAllPointerTracker();
+ sPointerTrackerQueue.releaseAllPointers(eventTime);
onCancelEventInternal();
}
@@ -1121,9 +1232,9 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
mTimerProxy.cancelKeyTimers();
setReleasedKeyGraphics(mCurrentKey);
resetSlidingKeyInput();
- if (mIsShowingMoreKeysPanel) {
- mDrawingProxy.dismissMoreKeysPanel();
- mIsShowingMoreKeysPanel = false;
+ if (isShowingMoreKeysPanel()) {
+ mMoreKeysPanel.dismissMoreKeysPanel();
+ mMoreKeysPanel = null;
}
}
@@ -1149,38 +1260,38 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
final Key curKey = mCurrentKey;
if (newKey == curKey) {
return false;
- } else if (curKey != null) {
- final int keyHysteresisDistanceSquared = mKeyDetector.getKeyHysteresisDistanceSquared(
- mIsInSlidingKeyInputFromModifier);
- final int distanceFromKeyEdgeSquared = curKey.squaredDistanceToEdge(x, y);
- if (distanceFromKeyEdgeSquared >= keyHysteresisDistanceSquared) {
- if (DEBUG_MODE) {
- final float distanceToEdgeRatio = (float)Math.sqrt(distanceFromKeyEdgeSquared)
- / mKeyboard.mMostCommonKeyWidth;
- Log.d(TAG, String.format("[%d] isMajorEnoughMoveToBeOnNewKey:"
- +" %.2f key width from key edge",
- mPointerId, distanceToEdgeRatio));
- }
- return true;
+ }
+ if (curKey == null /* && newKey != null */) {
+ return true;
+ }
+ // Here curKey points to the different key from newKey.
+ final int keyHysteresisDistanceSquared = mKeyDetector.getKeyHysteresisDistanceSquared(
+ mIsInSlidingKeyInputFromModifier);
+ final int distanceFromKeyEdgeSquared = curKey.squaredDistanceToEdge(x, y);
+ if (distanceFromKeyEdgeSquared >= keyHysteresisDistanceSquared) {
+ if (DEBUG_MODE) {
+ final float distanceToEdgeRatio = (float)Math.sqrt(distanceFromKeyEdgeSquared)
+ / mKeyboard.mMostCommonKeyWidth;
+ Log.d(TAG, String.format("[%d] isMajorEnoughMoveToBeOnNewKey:"
+ +" %.2f key width from key edge", mPointerId, distanceToEdgeRatio));
}
- if (sNeedsProximateBogusDownMoveUpEventHack && !mIsAllowedSlidingKeyInput
- && sTimeRecorder.isInFastTyping(eventTime)
- && mBogusMoveEventDetector.hasTraveledLongDistance(x, y)) {
- if (DEBUG_MODE) {
- final float keyDiagonal = (float)Math.hypot(
- mKeyboard.mMostCommonKeyWidth, mKeyboard.mMostCommonKeyHeight);
- final float lengthFromDownRatio =
- mBogusMoveEventDetector.mAccumulatedDistanceFromDownKey / keyDiagonal;
- Log.d(TAG, String.format("[%d] isMajorEnoughMoveToBeOnNewKey:"
- + " %.2f key diagonal from virtual down point",
- mPointerId, lengthFromDownRatio));
- }
- return true;
+ return true;
+ }
+ if (sNeedsProximateBogusDownMoveUpEventHack && !mIsAllowedSlidingKeyInput
+ && sTimeRecorder.isInFastTyping(eventTime)
+ && mBogusMoveEventDetector.hasTraveledLongDistance(x, y)) {
+ if (DEBUG_MODE) {
+ final float keyDiagonal = (float)Math.hypot(
+ mKeyboard.mMostCommonKeyWidth, mKeyboard.mMostCommonKeyHeight);
+ final float lengthFromDownRatio =
+ mBogusMoveEventDetector.mAccumulatedDistanceFromDownKey / keyDiagonal;
+ Log.d(TAG, String.format("[%d] isMajorEnoughMoveToBeOnNewKey:"
+ + " %.2f key diagonal from virtual down point",
+ mPointerId, lengthFromDownRatio));
}
- return false;
- } else { // curKey == null && newKey != null
return true;
}
+ return false;
}
private void startLongPressTimer(final Key key) {
@@ -1205,6 +1316,6 @@ public final class PointerTracker implements PointerTrackerQueue.Element {
final Key key = mKeyDetector.detectHitKey(x, y);
final String code = KeyDetector.printableCode(key);
Log.d(TAG, String.format("[%d]%s%s %4d %4d %5d %s", mPointerId,
- (mKeyAlreadyProcessed ? "-" : " "), title, x, y, eventTime, code));
+ (mIsTrackingCanceled ? "-" : " "), title, x, y, eventTime, code));
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/ProximityInfo.java b/java/src/com/android/inputmethod/keyboard/ProximityInfo.java
index 06a9e9252..32cee734a 100644
--- a/java/src/com/android/inputmethod/keyboard/ProximityInfo.java
+++ b/java/src/com/android/inputmethod/keyboard/ProximityInfo.java
@@ -1,23 +1,24 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.graphics.Rect;
import android.text.TextUtils;
+import android.util.Log;
import com.android.inputmethod.keyboard.internal.TouchPositionCorrection;
import com.android.inputmethod.latin.Constants;
@@ -26,11 +27,13 @@ import com.android.inputmethod.latin.JniUtils;
import java.util.Arrays;
public final class ProximityInfo {
- /** MAX_PROXIMITY_CHARS_SIZE must be the same as MAX_PROXIMITY_CHARS_SIZE_INTERNAL
- * in defines.h */
+ private static final String TAG = ProximityInfo.class.getSimpleName();
+ private static final boolean DEBUG = false;
+
+ // Must be equal to MAX_PROXIMITY_CHARS_SIZE in native/jni/src/defines.h
public static final int MAX_PROXIMITY_CHARS_SIZE = 16;
/** Number of key widths from current touch point to search for nearest keys. */
- private static float SEARCH_DISTANCE = 1.2f;
+ private static final float SEARCH_DISTANCE = 1.2f;
private static final Key[] EMPTY_KEY_ARRAY = new Key[0];
private static final float DEFAULT_TOUCH_POSITION_CORRECTION_RADIUS = 0.15f;
@@ -76,17 +79,21 @@ public final class ProximityInfo {
mNativeProximityInfo = createNativeProximityInfo(touchPositionCorrection);
}
- public static ProximityInfo createDummyProximityInfo() {
+ private static ProximityInfo createDummyProximityInfo() {
return new ProximityInfo("", 1, 1, 1, 1, 1, 1, EMPTY_KEY_ARRAY, null);
}
- public static ProximityInfo createSpellCheckerProximityInfo(final int[] proximity,
+ public static ProximityInfo createSpellCheckerProximityInfo(final int[] proximityCharsArray,
final int rowSize, final int gridWidth, final int gridHeight) {
final ProximityInfo spellCheckerProximityInfo = createDummyProximityInfo();
spellCheckerProximityInfo.mNativeProximityInfo =
- spellCheckerProximityInfo.setProximityInfoNative("",
- rowSize, gridWidth, gridHeight, gridWidth, gridHeight,
- 1, proximity, 0, null, null, null, null, null, null, null, null);
+ spellCheckerProximityInfo.setProximityInfoNative("" /* locale */,
+ gridWidth /* displayWidth */, gridHeight /* displayHeight */,
+ gridWidth, gridHeight, 1 /* mostCommonKeyWidth */, proximityCharsArray,
+ 0 /* keyCount */, null /*keyXCoordinates */, null /* keyYCoordinates */,
+ null /* keyWidths */, null /* keyHeights */, null /* keyCharCodes */,
+ null /* sweetSpotCenterXs */, null /* sweetSpotCenterYs */,
+ null /* sweetSpotRadii */);
return spellCheckerProximityInfo;
}
@@ -95,32 +102,65 @@ public final class ProximityInfo {
JniUtils.loadNativeLibrary();
}
- private native long setProximityInfoNative(
- String locale, int maxProximityCharsSize, int displayWidth,
- int displayHeight, int gridWidth, int gridHeight,
- int mostCommonKeyWidth, int[] proximityCharsArray,
- int keyCount, int[] keyXCoordinates, int[] keyYCoordinates,
- int[] keyWidths, int[] keyHeights, int[] keyCharCodes,
- float[] sweetSpotCenterX, float[] sweetSpotCenterY, float[] sweetSpotRadii);
+ // TODO: Stop passing proximityCharsArray
+ private static native long setProximityInfoNative(String locale,
+ int displayWidth, int displayHeight, int gridWidth, int gridHeight,
+ int mostCommonKeyWidth, int[] proximityCharsArray, int keyCount, int[] keyXCoordinates,
+ int[] keyYCoordinates, int[] keyWidths, int[] keyHeights, int[] keyCharCodes,
+ float[] sweetSpotCenterXs, float[] sweetSpotCenterYs, float[] sweetSpotRadii);
- private native void releaseProximityInfoNative(long nativeProximityInfo);
+ private static native void releaseProximityInfoNative(long nativeProximityInfo);
- private final long createNativeProximityInfo(
- final TouchPositionCorrection touchPositionCorrection) {
+ private static boolean needsProximityInfo(final Key key) {
+ // Don't include special keys into ProximityInfo.
+ return key.mCode >= Constants.CODE_SPACE;
+ }
+
+ private static int getProximityInfoKeysCount(final Key[] keys) {
+ int count = 0;
+ for (final Key key : keys) {
+ if (needsProximityInfo(key)) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ private long createNativeProximityInfo(final TouchPositionCorrection touchPositionCorrection) {
final Key[][] gridNeighborKeys = mGridNeighbors;
- final int keyboardWidth = mKeyboardMinWidth;
- final int keyboardHeight = mKeyboardHeight;
- final Key[] keys = mKeys;
final int[] proximityCharsArray = new int[mGridSize * MAX_PROXIMITY_CHARS_SIZE];
Arrays.fill(proximityCharsArray, Constants.NOT_A_CODE);
for (int i = 0; i < mGridSize; ++i) {
final int proximityCharsLength = gridNeighborKeys[i].length;
+ int infoIndex = i * MAX_PROXIMITY_CHARS_SIZE;
for (int j = 0; j < proximityCharsLength; ++j) {
- proximityCharsArray[i * MAX_PROXIMITY_CHARS_SIZE + j] =
- gridNeighborKeys[i][j].mCode;
+ final Key neighborKey = gridNeighborKeys[i][j];
+ // Excluding from proximityCharsArray
+ if (!needsProximityInfo(neighborKey)) {
+ continue;
+ }
+ proximityCharsArray[infoIndex] = neighborKey.mCode;
+ infoIndex++;
}
}
- final int keyCount = keys.length;
+ if (DEBUG) {
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < mGridSize; i++) {
+ sb.setLength(0);
+ for (int j = 0; j < MAX_PROXIMITY_CHARS_SIZE; j++) {
+ final int code = proximityCharsArray[i * MAX_PROXIMITY_CHARS_SIZE + j];
+ if (code == Constants.NOT_A_CODE) {
+ break;
+ }
+ if (sb.length() > 0) sb.append(" ");
+ sb.append(Constants.printableCode(code));
+ }
+ Log.d(TAG, "proxmityChars["+i+"]: " + sb);
+ }
+ }
+
+ final Key[] keys = mKeys;
+ final int keyCount = getProximityInfoKeysCount(keys);
final int[] keyXCoordinates = new int[keyCount];
final int[] keyYCoordinates = new int[keyCount];
final int[] keyWidths = new int[keyCount];
@@ -130,45 +170,72 @@ public final class ProximityInfo {
final float[] sweetSpotCenterYs;
final float[] sweetSpotRadii;
- for (int i = 0; i < keyCount; ++i) {
- final Key key = keys[i];
- keyXCoordinates[i] = key.mX;
- keyYCoordinates[i] = key.mY;
- keyWidths[i] = key.mWidth;
- keyHeights[i] = key.mHeight;
- keyCharCodes[i] = key.mCode;
+ for (int infoIndex = 0, keyIndex = 0; keyIndex < keys.length; keyIndex++) {
+ final Key key = keys[keyIndex];
+ // Excluding from key coordinate arrays
+ if (!needsProximityInfo(key)) {
+ continue;
+ }
+ keyXCoordinates[infoIndex] = key.mX;
+ keyYCoordinates[infoIndex] = key.mY;
+ keyWidths[infoIndex] = key.mWidth;
+ keyHeights[infoIndex] = key.mHeight;
+ keyCharCodes[infoIndex] = key.mCode;
+ infoIndex++;
}
if (touchPositionCorrection != null && touchPositionCorrection.isValid()) {
+ if (DEBUG) {
+ Log.d(TAG, "touchPositionCorrection: ON");
+ }
sweetSpotCenterXs = new float[keyCount];
sweetSpotCenterYs = new float[keyCount];
sweetSpotRadii = new float[keyCount];
+ final int rows = touchPositionCorrection.getRows();
final float defaultRadius = DEFAULT_TOUCH_POSITION_CORRECTION_RADIUS
* (float)Math.hypot(mMostCommonKeyWidth, mMostCommonKeyHeight);
- for (int i = 0; i < keyCount; i++) {
- final Key key = keys[i];
+ for (int infoIndex = 0, keyIndex = 0; keyIndex < keys.length; keyIndex++) {
+ final Key key = keys[keyIndex];
+ // Excluding from touch position correction arrays
+ if (!needsProximityInfo(key)) {
+ continue;
+ }
final Rect hitBox = key.mHitBox;
- sweetSpotCenterXs[i] = hitBox.exactCenterX();
- sweetSpotCenterYs[i] = hitBox.exactCenterY();
- sweetSpotRadii[i] = defaultRadius;
+ sweetSpotCenterXs[infoIndex] = hitBox.exactCenterX();
+ sweetSpotCenterYs[infoIndex] = hitBox.exactCenterY();
+ sweetSpotRadii[infoIndex] = defaultRadius;
final int row = hitBox.top / mMostCommonKeyHeight;
- if (row < touchPositionCorrection.getRows()) {
+ if (row < rows) {
final int hitBoxWidth = hitBox.width();
final int hitBoxHeight = hitBox.height();
final float hitBoxDiagonal = (float)Math.hypot(hitBoxWidth, hitBoxHeight);
- sweetSpotCenterXs[i] += touchPositionCorrection.getX(row) * hitBoxWidth;
- sweetSpotCenterYs[i] += touchPositionCorrection.getY(row) * hitBoxHeight;
- sweetSpotRadii[i] = touchPositionCorrection.getRadius(row) * hitBoxDiagonal;
+ sweetSpotCenterXs[infoIndex] +=
+ touchPositionCorrection.getX(row) * hitBoxWidth;
+ sweetSpotCenterYs[infoIndex] +=
+ touchPositionCorrection.getY(row) * hitBoxHeight;
+ sweetSpotRadii[infoIndex] =
+ touchPositionCorrection.getRadius(row) * hitBoxDiagonal;
}
+ if (DEBUG) {
+ Log.d(TAG, String.format(
+ " [%2d] row=%d x/y/r=%7.2f/%7.2f/%5.2f %s code=%s", infoIndex, row,
+ sweetSpotCenterXs[infoIndex], sweetSpotCenterYs[infoIndex],
+ sweetSpotRadii[infoIndex], (row < rows ? "correct" : "default"),
+ Constants.printableCode(key.mCode)));
+ }
+ infoIndex++;
}
} else {
sweetSpotCenterXs = sweetSpotCenterYs = sweetSpotRadii = null;
+ if (DEBUG) {
+ Log.d(TAG, "touchPositionCorrection: OFF");
+ }
}
- return setProximityInfoNative(mLocaleStr, MAX_PROXIMITY_CHARS_SIZE,
- keyboardWidth, keyboardHeight, mGridWidth, mGridHeight, mMostCommonKeyWidth,
- proximityCharsArray,
- keyCount, keyXCoordinates, keyYCoordinates, keyWidths, keyHeights, keyCharCodes,
+ // TODO: Stop passing proximityCharsArray
+ return setProximityInfoNative(mLocaleStr, mKeyboardMinWidth, mKeyboardHeight,
+ mGridWidth, mGridHeight, mMostCommonKeyWidth, proximityCharsArray, keyCount,
+ keyXCoordinates, keyYCoordinates, keyWidths, keyHeights, keyCharCodes,
sweetSpotCenterXs, sweetSpotCenterYs, sweetSpotRadii);
}
@@ -221,7 +288,7 @@ public final class ProximityInfo {
return;
}
int index = 0;
- if (primaryKeyCode > Keyboard.CODE_SPACE) {
+ if (primaryKeyCode > Constants.CODE_SPACE) {
dest[index++] = primaryKeyCode;
}
final Key[] nearestKeys = getNearestKeys(x, y);
@@ -230,7 +297,7 @@ public final class ProximityInfo {
break;
}
final int code = key.mCode;
- if (code <= Keyboard.CODE_SPACE) {
+ if (code <= Constants.CODE_SPACE) {
break;
}
dest[index++] = code;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java b/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java
new file mode 100644
index 000000000..b814fc162
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2012 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.internal;
+
+import android.graphics.Canvas;
+import android.view.View;
+
+import com.android.inputmethod.keyboard.PointerTracker;
+
+/**
+ * Abstract base class for previews that are drawn on PreviewPlacerView, e.g.,
+ * GestureFloatingPrevewText, GestureTrail, and SlidingKeyInputPreview.
+ */
+public abstract class AbstractDrawingPreview {
+ private final View mDrawingView;
+ private boolean mPreviewEnabled;
+
+ protected AbstractDrawingPreview(final View drawingView) {
+ mDrawingView = drawingView;
+ }
+
+ public final View getDrawingView() {
+ return mDrawingView;
+ }
+
+ public final void setPreviewEnabled(final boolean enabled) {
+ mPreviewEnabled = enabled;
+ }
+
+ public boolean isPreviewEnabled() {
+ return mPreviewEnabled;
+ }
+
+ public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) {
+ // Default implementation is empty.
+ }
+
+ public void onDetachFromWindow() {
+ // Default implementation is empty.
+ }
+
+ /**
+ * Draws the preview
+ * @param canvas The canvas where the preview is drawn.
+ */
+ public abstract void drawPreview(final Canvas canvas);
+
+ /**
+ * Set the position of the preview.
+ * @param tracker The new location of the preview is based on the points in PointerTracker.
+ */
+ public abstract void setPreviewPosition(final PointerTracker tracker);
+}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/AlphabetShiftState.java b/java/src/com/android/inputmethod/keyboard/internal/AlphabetShiftState.java
index 44aa72a0a..33f6b4965 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/AlphabetShiftState.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/AlphabetShiftState.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java b/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java
new file mode 100644
index 000000000..ab810a580
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2012 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.internal;
+
+import android.content.res.TypedArray;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Paint.Align;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.text.TextUtils;
+import android.view.View;
+
+import com.android.inputmethod.keyboard.PointerTracker;
+import com.android.inputmethod.latin.CoordinateUtils;
+import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.SuggestedWords;
+
+/**
+ * The class for single gesture preview text. The class for multiple gesture preview text will be
+ * derived from it.
+ *
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextSize
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextColor
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewTextOffset
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewColor
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewHorizontalPadding
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewVerticalPadding
+ * @attr ref R.styleable#KeyboardView_gestureFloatingPreviewRoundRadius
+ */
+public class GestureFloatingPreviewText extends AbstractDrawingPreview {
+ protected static final class GesturePreviewTextParams {
+ public final int mGesturePreviewTextOffset;
+ public final int mGesturePreviewTextHeight;
+ public final float mGesturePreviewHorizontalPadding;
+ public final float mGesturePreviewVerticalPadding;
+ public final float mGesturePreviewRoundRadius;
+
+ private final int mGesturePreviewTextSize;
+ private final int mGesturePreviewTextColor;
+ private final int mGesturePreviewColor;
+ private final Paint mPaint = new Paint();
+
+ private static final char[] TEXT_HEIGHT_REFERENCE_CHAR = { 'M' };
+
+ public GesturePreviewTextParams(final TypedArray mainKeyboardViewAttr) {
+ mGesturePreviewTextSize = mainKeyboardViewAttr.getDimensionPixelSize(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewTextSize, 0);
+ mGesturePreviewTextColor = mainKeyboardViewAttr.getColor(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewTextColor, 0);
+ mGesturePreviewTextOffset = mainKeyboardViewAttr.getDimensionPixelOffset(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewTextOffset, 0);
+ mGesturePreviewColor = mainKeyboardViewAttr.getColor(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewColor, 0);
+ mGesturePreviewHorizontalPadding = mainKeyboardViewAttr.getDimension(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewHorizontalPadding, 0.0f);
+ mGesturePreviewVerticalPadding = mainKeyboardViewAttr.getDimension(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewVerticalPadding, 0.0f);
+ mGesturePreviewRoundRadius = mainKeyboardViewAttr.getDimension(
+ R.styleable.MainKeyboardView_gestureFloatingPreviewRoundRadius, 0.0f);
+
+ final Paint textPaint = getTextPaint();
+ final Rect textRect = new Rect();
+ textPaint.getTextBounds(TEXT_HEIGHT_REFERENCE_CHAR, 0, 1, textRect);
+ mGesturePreviewTextHeight = textRect.height();
+ }
+
+ public Paint getTextPaint() {
+ mPaint.setAntiAlias(true);
+ mPaint.setTextAlign(Align.CENTER);
+ mPaint.setTextSize(mGesturePreviewTextSize);
+ mPaint.setColor(mGesturePreviewTextColor);
+ return mPaint;
+ }
+
+ public Paint getBackgroundPaint() {
+ mPaint.setColor(mGesturePreviewColor);
+ return mPaint;
+ }
+ }
+
+ private final GesturePreviewTextParams mParams;
+ private final RectF mGesturePreviewRectangle = new RectF();
+ private int mPreviewTextX;
+ private int mPreviewTextY;
+ private SuggestedWords mSuggestedWords = SuggestedWords.EMPTY;
+ private final int[] mLastPointerCoords = CoordinateUtils.newInstance();
+
+ public GestureFloatingPreviewText(final View drawingView, final TypedArray typedArray) {
+ super(drawingView);
+ mParams = new GesturePreviewTextParams(typedArray);
+ }
+
+ public void setSuggetedWords(final SuggestedWords suggestedWords) {
+ if (!isPreviewEnabled()) {
+ return;
+ }
+ mSuggestedWords = suggestedWords;
+ updatePreviewPosition();
+ }
+
+ @Override
+ public void setPreviewPosition(final PointerTracker tracker) {
+ final boolean needsToUpdateLastPointer =
+ tracker.isOldestTrackerInQueue() && isPreviewEnabled();
+ if (!needsToUpdateLastPointer) {
+ return;
+ }
+ tracker.getLastCoordinates(mLastPointerCoords);
+ updatePreviewPosition();
+ }
+
+ /**
+ * Draws gesture preview text
+ * @param canvas The canvas where preview text is drawn.
+ */
+ @Override
+ public void drawPreview(final Canvas canvas) {
+ if (!isPreviewEnabled() || mSuggestedWords.isEmpty()
+ || TextUtils.isEmpty(mSuggestedWords.getWord(0))) {
+ return;
+ }
+ final float round = mParams.mGesturePreviewRoundRadius;
+ canvas.drawRoundRect(
+ mGesturePreviewRectangle, round, round, mParams.getBackgroundPaint());
+ final String text = mSuggestedWords.getWord(0);
+ canvas.drawText(text, mPreviewTextX, mPreviewTextY, mParams.getTextPaint());
+ }
+
+ /**
+ * Updates gesture preview text position based on mLastPointerCoords.
+ */
+ protected void updatePreviewPosition() {
+ if (mSuggestedWords.isEmpty() || TextUtils.isEmpty(mSuggestedWords.getWord(0))) {
+ getDrawingView().invalidate();
+ return;
+ }
+ final String text = mSuggestedWords.getWord(0);
+
+ final RectF rectangle = mGesturePreviewRectangle;
+
+ final int textHeight = mParams.mGesturePreviewTextHeight;
+ final float textWidth = mParams.getTextPaint().measureText(text);
+ final float hPad = mParams.mGesturePreviewHorizontalPadding;
+ final float vPad = mParams.mGesturePreviewVerticalPadding;
+ final float rectWidth = textWidth + hPad * 2.0f;
+ final float rectHeight = textHeight + vPad * 2.0f;
+
+ final int displayWidth = getDrawingView().getResources().getDisplayMetrics().widthPixels;
+ final float rectX = Math.min(
+ Math.max(CoordinateUtils.x(mLastPointerCoords) - rectWidth / 2.0f, 0.0f),
+ displayWidth - rectWidth);
+ final float rectY = CoordinateUtils.y(mLastPointerCoords)
+ - mParams.mGesturePreviewTextOffset - rectHeight;
+ rectangle.set(rectX, rectY, rectX + rectWidth, rectY + rectHeight);
+
+ mPreviewTextX = (int)(rectX + hPad + textWidth / 2.0f);
+ mPreviewTextY = (int)(rectY + vPad) + textHeight;
+ // TODO: Should narrow the invalidate region.
+ getDrawingView().invalidate();
+ }
+}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/GesturePreviewTrail.java b/java/src/com/android/inputmethod/keyboard/internal/GesturePreviewTrail.java
index 699aaeaef..b047fe038 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/GesturePreviewTrail.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/GesturePreviewTrail.java
@@ -1,15 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -19,13 +21,19 @@ import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
-import android.graphics.RectF;
import android.os.SystemClock;
import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.ResizableIntArray;
+/*
+ * @attr ref R.styleable#MainKeyboardView_gesturePreviewTrailFadeoutStartDelay
+ * @attr ref R.styleable#MainKeyboardView_gesturePreviewTrailFadeoutDuration
+ * @attr ref R.styleable#MainKeyboardView_gesturePreviewTrailUpdateInterval
+ * @attr ref R.styleable#MainKeyboardView_gesturePreviewTrailColor
+ * @attr ref R.styleable#MainKeyboardView_gesturePreviewTrailWidth
+ */
final class GesturePreviewTrail {
private static final int DEFAULT_CAPACITY = GestureStrokeWithPreviewPoints.PREVIEW_CAPACITY;
@@ -47,20 +55,20 @@ final class GesturePreviewTrail {
public final int mTrailLingerDuration;
- public Params(final TypedArray keyboardViewAttr) {
- mTrailColor = keyboardViewAttr.getColor(
- R.styleable.KeyboardView_gesturePreviewTrailColor, 0);
- mTrailStartWidth = keyboardViewAttr.getDimension(
- R.styleable.KeyboardView_gesturePreviewTrailStartWidth, 0.0f);
- mTrailEndWidth = keyboardViewAttr.getDimension(
- R.styleable.KeyboardView_gesturePreviewTrailEndWidth, 0.0f);
- mFadeoutStartDelay = keyboardViewAttr.getInt(
- R.styleable.KeyboardView_gesturePreviewTrailFadeoutStartDelay, 0);
- mFadeoutDuration = keyboardViewAttr.getInt(
- R.styleable.KeyboardView_gesturePreviewTrailFadeoutDuration, 0);
+ public Params(final TypedArray mainKeyboardViewAttr) {
+ mTrailColor = mainKeyboardViewAttr.getColor(
+ R.styleable.MainKeyboardView_gesturePreviewTrailColor, 0);
+ mTrailStartWidth = mainKeyboardViewAttr.getDimension(
+ R.styleable.MainKeyboardView_gesturePreviewTrailStartWidth, 0.0f);
+ mTrailEndWidth = mainKeyboardViewAttr.getDimension(
+ R.styleable.MainKeyboardView_gesturePreviewTrailEndWidth, 0.0f);
+ mFadeoutStartDelay = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_gesturePreviewTrailFadeoutStartDelay, 0);
+ mFadeoutDuration = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_gesturePreviewTrailFadeoutDuration, 0);
mTrailLingerDuration = mFadeoutStartDelay + mFadeoutDuration;
- mUpdateInterval = keyboardViewAttr.getInt(
- R.styleable.KeyboardView_gesturePreviewTrailUpdateInterval, 0);
+ mUpdateInterval = mainKeyboardViewAttr.getInt(
+ R.styleable.MainKeyboardView_gesturePreviewTrailUpdateInterval, 0);
}
}
@@ -102,6 +110,16 @@ final class GesturePreviewTrail {
}
}
+ /**
+ * Calculate the alpha of a gesture trail.
+ * A gesture trail starts from fully opaque. After mFadeStartDelay has been passed, the alpha
+ * of a trail reduces in proportion to the elapsed time. Then after mFadeDuration has been
+ * passed, a trail becomes fully transparent.
+ *
+ * @param elapsedTime the elapsed time since a trail has been made.
+ * @param params gesture trail display parameters
+ * @return the width of a gesture trail
+ */
private static int getAlpha(final int elapsedTime, final Params params) {
if (elapsedTime < params.mFadeoutStartDelay) {
return Constants.Color.ALPHA_OPAQUE;
@@ -112,104 +130,22 @@ final class GesturePreviewTrail {
return Constants.Color.ALPHA_OPAQUE - decreasingAlpha;
}
+ /**
+ * Calculate the width of a gesture trail.
+ * A gesture trail starts from the width of mTrailStartWidth and reduces its width in proportion
+ * to the elapsed time. After mTrailEndWidth has been passed, the width becomes mTraiLEndWidth.
+ *
+ * @param elapsedTime the elapsed time since a trail has been made.
+ * @param params gesture trail display parameters
+ * @return the width of a gesture trail
+ */
private static float getWidth(final int elapsedTime, final Params params) {
- return Math.max((params.mTrailLingerDuration - elapsedTime)
- * (params.mTrailStartWidth - params.mTrailEndWidth)
- / params.mTrailLingerDuration, 0.0f);
- }
-
- static final class WorkingSet {
- // Input
- // Previous point (P1) coordinates and trail radius.
- public float p1x, p1y;
- public float r1;
- // Current point (P2) coordinates and trail radius.
- public float p2x, p2y;
- public float r2;
-
- // Output
- // Closing point of arc at P1.
- public float p1ax, p1ay;
- // Opening point of arc at P1.
- public float p1bx, p1by;
- // Opening point of arc at P2.
- public float p2ax, p2ay;
- // Closing point of arc at P2.
- public float p2bx, p2by;
- // Start angle of the trail arcs.
- public float aa;
- // Sweep angle of the trail arc at P1.
- public float a1;
- public RectF arc1 = new RectF();
- // Sweep angle of the trail arc at P2.
- public float a2;
- public RectF arc2 = new RectF();
- }
-
- private static final float RIGHT_ANGLE = (float)(Math.PI / 2.0d);
- private static final float RADIAN_TO_DEGREE = (float)(180.0d / Math.PI);
-
- private static boolean calculatePathPoints(final WorkingSet w) {
- final float dx = w.p2x - w.p1x;
- final float dy = w.p2y - w.p1y;
- // Distance of the points.
- final double l = Math.hypot(dx, dy);
- if (Double.compare(0.0d, l) == 0) {
- return false;
- }
- // Angle of the line p1-p2
- final float a = (float)Math.atan2(dy, dx);
- // Difference of trail cap radius.
- final float dr = w.r2 - w.r1;
- // Variation of angle at trail cap.
- final float ar = (float)Math.asin(dr / l);
- // The start angle of trail cap arc at P1.
- final float aa = a - (RIGHT_ANGLE + ar);
- // The end angle of trail cap arc at P2.
- final float ab = a + (RIGHT_ANGLE + ar);
- final float cosa = (float)Math.cos(aa);
- final float sina = (float)Math.sin(aa);
- final float cosb = (float)Math.cos(ab);
- final float sinb = (float)Math.sin(ab);
- w.p1ax = w.p1x + w.r1 * cosa;
- w.p1ay = w.p1y + w.r1 * sina;
- w.p1bx = w.p1x + w.r1 * cosb;
- w.p1by = w.p1y + w.r1 * sinb;
- w.p2ax = w.p2x + w.r2 * cosa;
- w.p2ay = w.p2y + w.r2 * sina;
- w.p2bx = w.p2x + w.r2 * cosb;
- w.p2by = w.p2y + w.r2 * sinb;
- w.aa = aa * RADIAN_TO_DEGREE;
- final float ar2degree = ar * 2.0f * RADIAN_TO_DEGREE;
- w.a1 = -180.0f + ar2degree;
- w.a2 = 180.0f + ar2degree;
- w.arc1.set(w.p1x, w.p1y, w.p1x, w.p1y);
- w.arc1.inset(-w.r1, -w.r1);
- w.arc2.set(w.p2x, w.p2y, w.p2x, w.p2y);
- w.arc2.inset(-w.r2, -w.r2);
- return true;
- }
-
- private static void createPath(final Path path, final WorkingSet w) {
- path.rewind();
- // Trail cap at P1.
- path.moveTo(w.p1x, w.p1y);
- path.arcTo(w.arc1, w.aa, w.a1);
- // Trail cap at P2.
- path.moveTo(w.p2x, w.p2y);
- path.arcTo(w.arc2, w.aa, w.a2);
- // Two trapezoids connecting P1 and P2.
- path.moveTo(w.p1ax, w.p1ay);
- path.lineTo(w.p1x, w.p1y);
- path.lineTo(w.p1bx, w.p1by);
- path.lineTo(w.p2bx, w.p2by);
- path.lineTo(w.p2x, w.p2y);
- path.lineTo(w.p2ax, w.p2ay);
- path.close();
+ final float deltaWidth = params.mTrailStartWidth - params.mTrailEndWidth;
+ return params.mTrailStartWidth - (deltaWidth * elapsedTime) / params.mTrailLingerDuration;
}
- private final WorkingSet mWorkingSet = new WorkingSet();
- private final Path mPath = new Path();
+ private final RoundedLine mRoundedLine = new RoundedLine();
+ private final Rect mRoundedLineBounds = new Rect();
/**
* Draw gesture preview trail
@@ -221,6 +157,8 @@ final class GesturePreviewTrail {
*/
public boolean drawGestureTrail(final Canvas canvas, final Paint paint,
final Rect outBoundsRect, final Params params) {
+ // Initialize bounds rectangle.
+ outBoundsRect.setEmpty();
final int trailSize = mEventTimes.getLength();
if (trailSize == 0) {
return false;
@@ -243,41 +181,32 @@ final class GesturePreviewTrail {
if (startIndex < trailSize) {
paint.setColor(params.mTrailColor);
paint.setStyle(Paint.Style.FILL);
- final Path path = mPath;
- final WorkingSet w = mWorkingSet;
- w.p1x = getXCoordValue(xCoords[startIndex]);
- w.p1y = yCoords[startIndex];
- int lastTime = sinceDown - eventTimes[startIndex];
- float maxWidth = getWidth(lastTime, params);
- w.r1 = maxWidth / 2.0f;
- // Initialize bounds rectangle.
- outBoundsRect.set((int)w.p1x, (int)w.p1y, (int)w.p1x, (int)w.p1y);
- for (int i = startIndex + 1; i < trailSize - 1; i++) {
+ final RoundedLine roundedLine = mRoundedLine;
+ int p1x = getXCoordValue(xCoords[startIndex]);
+ int p1y = yCoords[startIndex];
+ final int lastTime = sinceDown - eventTimes[startIndex];
+ float r1 = getWidth(lastTime, params) / 2.0f;
+ for (int i = startIndex + 1; i < trailSize; i++) {
final int elapsedTime = sinceDown - eventTimes[i];
- w.p2x = getXCoordValue(xCoords[i]);
- w.p2y = yCoords[i];
+ final int p2x = getXCoordValue(xCoords[i]);
+ final int p2y = yCoords[i];
+ final float r2 = getWidth(elapsedTime, params) / 2.0f;
// Draw trail line only when the current point isn't a down point.
if (!isDownEventXCoord(xCoords[i])) {
- final int alpha = getAlpha(elapsedTime, params);
- paint.setAlpha(alpha);
- final float width = getWidth(elapsedTime, params);
- w.r2 = width / 2.0f;
- if (calculatePathPoints(w)) {
- createPath(path, w);
+ final Path path = roundedLine.makePath(p1x, p1y, r1, p2x, p2y, r2);
+ if (path != null) {
+ final int alpha = getAlpha(elapsedTime, params);
+ paint.setAlpha(alpha);
canvas.drawPath(path, paint);
- outBoundsRect.union((int)w.p2x, (int)w.p2y);
+ // Take union for the bounds.
+ roundedLine.getBounds(mRoundedLineBounds);
+ outBoundsRect.union(mRoundedLineBounds);
}
- // Take union for the bounds.
- maxWidth = Math.max(maxWidth, width);
}
- w.p1x = w.p2x;
- w.p1y = w.p2y;
- w.r1 = w.r2;
- lastTime = elapsedTime;
+ p1x = p2x;
+ p1y = p2y;
+ r1 = r2;
}
- // Take care of trail line width.
- final int inset = -((int)maxWidth + 1);
- outBoundsRect.inset(inset, inset);
}
final int newSize = trailSize - startIndex;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java b/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java
index f8244dd5b..53da47c52 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java
@@ -1,15 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -27,6 +29,10 @@ public class GestureStroke {
private static final boolean DEBUG = false;
private static final boolean DEBUG_SPEED = false;
+ // The height of extra area above the keyboard to draw gesture trails.
+ // Proportional to the keyboard height.
+ public static final float EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO = 0.25f;
+
public static final int DEFAULT_CAPACITY = 128;
private final int mPointerId;
@@ -37,6 +43,8 @@ public class GestureStroke {
private final GestureStrokeParams mParams;
private int mKeyWidth; // pixel
+ private int mMinYCoordinate; // pixel
+ private int mMaxYCoordinate; // pixel
// Static threshold for starting gesture detection
private int mDetectFastMoveSpeedThreshold; // pixel /sec
private int mDetectFastMoveTime;
@@ -135,8 +143,10 @@ public class GestureStroke {
mParams = params;
}
- public void setKeyboardGeometry(final int keyWidth) {
+ public void setKeyboardGeometry(final int keyWidth, final int keyboardHeight) {
mKeyWidth = keyWidth;
+ mMinYCoordinate = -(int)(keyboardHeight * EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
+ mMaxYCoordinate = keyboardHeight - 1;
// TODO: Find an appropriate base metric for these length. Maybe diagonal length of the key?
mDetectFastMoveSpeedThreshold = (int)(keyWidth * mParams.mDetectFastMoveSpeedThreshold);
mGestureDynamicDistanceThresholdFrom =
@@ -155,6 +165,10 @@ public class GestureStroke {
}
}
+ public int getLength() {
+ return mEventTimes.getLength();
+ }
+
public void onDownEvent(final int x, final int y, final long downTime,
final long gestureFirstDownTime, final long lastTypingTime) {
reset();
@@ -167,7 +181,7 @@ public class GestureStroke {
elapsedTimeAfterTyping, mAfterFastTyping ? " afterFastTyping" : ""));
}
final int elapsedTimeFromFirstDown = (int)(downTime - gestureFirstDownTime);
- addPoint(x, y, elapsedTimeFromFirstDown, true /* isMajorEvent */);
+ addPointOnKeyboard(x, y, elapsedTimeFromFirstDown, true /* isMajorEvent */);
}
private int getGestureDynamicDistanceThreshold(final int deltaTime) {
@@ -194,7 +208,7 @@ public class GestureStroke {
if (!hasDetectedFastMove()) {
return false;
}
- final int size = mEventTimes.getLength();
+ final int size = getLength();
if (size <= 0) {
return false;
}
@@ -220,6 +234,21 @@ public class GestureStroke {
return isStartOfAGesture;
}
+ public void duplicateLastPointWith(final int time) {
+ final int lastIndex = getLength() - 1;
+ if (lastIndex >= 0) {
+ final int x = mXCoordinates.get(lastIndex);
+ final int y = mYCoordinates.get(lastIndex);
+ if (DEBUG) {
+ Log.d(TAG, String.format("[%d] duplicateLastPointWith: %d,%d|%d", mPointerId,
+ x, y, time));
+ }
+ // TODO: Have appendMajorPoint()
+ appendPoint(x, y, time);
+ updateIncrementalRecognitionSize(x, y, time);
+ }
+ }
+
protected void reset() {
mIncrementalRecognitionSize = 0;
mLastIncrementalBatchSize = 0;
@@ -232,6 +261,16 @@ public class GestureStroke {
}
private void appendPoint(final int x, final int y, final int time) {
+ final int lastIndex = getLength() - 1;
+ // The point that is created by {@link duplicateLastPointWith(int)} may have later event
+ // time than the next {@link MotionEvent}. To maintain the monotonicity of the event time,
+ // drop the successive point here.
+ if (lastIndex >= 0 && mEventTimes.get(lastIndex) > time) {
+ Log.w(TAG, String.format("[%d] drop stale event: %d,%d|%d last: %d,%d|%d", mPointerId,
+ x, y, time, mXCoordinates.get(lastIndex), mYCoordinates.get(lastIndex),
+ mEventTimes.get(lastIndex)));
+ return;
+ }
mEventTimes.add(time);
mXCoordinates.add(x);
mYCoordinates.add(y);
@@ -248,7 +287,7 @@ public class GestureStroke {
}
private int detectFastMove(final int x, final int y, final int time) {
- final int size = mEventTimes.getLength();
+ final int size = getLength();
final int lastIndex = size - 1;
final int lastX = mXCoordinates.get(lastIndex);
final int lastY = mYCoordinates.get(lastIndex);
@@ -277,8 +316,18 @@ public class GestureStroke {
return dist;
}
- public void addPoint(final int x, final int y, final int time, final boolean isMajorEvent) {
- final int size = mEventTimes.getLength();
+ /**
+ * Add a touch event as a gesture point. Returns true if the touch event is on the valid
+ * gesture area.
+ * @param x the x-coordinate of the touch event
+ * @param y the y-coordinate of the touch event
+ * @param time the elapsed time in millisecond from the first gesture down
+ * @param isMajorEvent false if this is a historical move event
+ * @return true if the touch event is on the valid gesture area
+ */
+ public boolean addPointOnKeyboard(final int x, final int y, final int time,
+ final boolean isMajorEvent) {
+ final int size = getLength();
if (size <= 0) {
// Down event
appendPoint(x, y, time);
@@ -293,6 +342,7 @@ public class GestureStroke {
updateIncrementalRecognitionSize(x, y, time);
updateMajorEvent(x, y, time);
}
+ return y >= mMinYCoordinate && y < mMaxYCoordinate;
}
private void updateIncrementalRecognitionSize(final int x, final int y, final int time) {
@@ -304,7 +354,7 @@ public class GestureStroke {
final int pixelsPerSec = pixels * MSEC_PER_SEC;
// Equivalent to (pixels / msecs < mGestureRecognitionThreshold / MSEC_PER_SEC)
if (pixelsPerSec < mGestureRecognitionSpeedThreshold * msecs) {
- mIncrementalRecognitionSize = mEventTimes.getLength();
+ mIncrementalRecognitionSize = getLength();
}
}
@@ -314,7 +364,7 @@ public class GestureStroke {
}
public final void appendAllBatchPoints(final InputPointers out) {
- appendBatchPoints(out, mEventTimes.getLength());
+ appendBatchPoints(out, getLength());
}
public final void appendIncrementalBatchPoints(final InputPointers out) {
diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java b/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java
index 8192c9076..fc81410ff 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java
@@ -1,15 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -56,8 +58,8 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke {
}
@Override
- public void setKeyboardGeometry(final int keyWidth) {
- super.setKeyboardGeometry(keyWidth);
+ public void setKeyboardGeometry(final int keyWidth, final int keyboardHeight) {
+ super.setKeyboardGeometry(keyWidth, keyboardHeight);
final float sampleLength = keyWidth * MIN_PREVIEW_SAMPLE_LENGTH_RATIO_TO_KEY_WIDTH;
mMinPreviewSampleLengthSquare = (int)(sampleLength * sampleLength);
}
@@ -69,8 +71,9 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke {
}
@Override
- public void addPoint(final int x, final int y, final int time, final boolean isMajorEvent) {
- super.addPoint(x, y, time, isMajorEvent);
+ public boolean addPointOnKeyboard(final int x, final int y, final int time,
+ final boolean isMajorEvent) {
+ final boolean onValidArea = super.addPointOnKeyboard(x, y, time, isMajorEvent);
if (isMajorEvent || needsSampling(x, y)) {
mPreviewEventTimes.add(time);
mPreviewXCoordinates.add(x);
@@ -78,6 +81,7 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke {
mLastX = x;
mLastY = y;
}
+ return onValidArea;
}
public void appendPreviewStroke(final ResizableIntArray eventTimes,
diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java b/java/src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java
new file mode 100644
index 000000000..85558f1f6
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2013 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.internal;
+
+import android.content.res.TypedArray;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.PorterDuff;
+import android.graphics.PorterDuffXfermode;
+import android.graphics.Rect;
+import android.os.Message;
+import android.util.SparseArray;
+import android.view.View;
+
+import com.android.inputmethod.keyboard.PointerTracker;
+import com.android.inputmethod.keyboard.internal.GesturePreviewTrail.Params;
+import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
+
+/**
+ * Draw gesture trail preview graphics during gesture.
+ */
+public final class GestureTrailsPreview extends AbstractDrawingPreview {
+ private final SparseArray<GesturePreviewTrail> mGesturePreviewTrails =
+ CollectionUtils.newSparseArray();
+ private final Params mGesturePreviewTrailParams;
+ private final Paint mGesturePaint;
+ private int mOffscreenWidth;
+ private int mOffscreenHeight;
+ private int mOffscreenOffsetY;
+ private Bitmap mOffscreenBuffer;
+ private final Canvas mOffscreenCanvas = new Canvas();
+ private final Rect mOffscreenSrcRect = new Rect();
+ private final Rect mDirtyRect = new Rect();
+ private final Rect mGesturePreviewTrailBoundsRect = new Rect(); // per trail
+
+ private final DrawingHandler mDrawingHandler;
+
+ private static final class DrawingHandler
+ extends StaticInnerHandlerWrapper<GestureTrailsPreview> {
+ private static final int MSG_UPDATE_GESTURE_PREVIEW_TRAIL = 0;
+
+ private final Params mGesturePreviewTrailParams;
+
+ public DrawingHandler(final GestureTrailsPreview outerInstance,
+ final Params gesturePreviewTrailParams) {
+ super(outerInstance);
+ mGesturePreviewTrailParams = gesturePreviewTrailParams;
+ }
+
+ @Override
+ public void handleMessage(final Message msg) {
+ final GestureTrailsPreview preview = getOuterInstance();
+ if (preview == null) return;
+ switch (msg.what) {
+ case MSG_UPDATE_GESTURE_PREVIEW_TRAIL:
+ preview.getDrawingView().invalidate();
+ break;
+ }
+ }
+
+ public void postUpdateGestureTrailPreview() {
+ removeMessages(MSG_UPDATE_GESTURE_PREVIEW_TRAIL);
+ sendMessageDelayed(obtainMessage(MSG_UPDATE_GESTURE_PREVIEW_TRAIL),
+ mGesturePreviewTrailParams.mUpdateInterval);
+ }
+ }
+
+ public GestureTrailsPreview(final View drawingView, final TypedArray mainKeyboardViewAttr) {
+ super(drawingView);
+ mGesturePreviewTrailParams = new Params(mainKeyboardViewAttr);
+ mDrawingHandler = new DrawingHandler(this, mGesturePreviewTrailParams);
+ final Paint gesturePaint = new Paint();
+ gesturePaint.setAntiAlias(true);
+ gesturePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
+ mGesturePaint = gesturePaint;
+ }
+
+ @Override
+ public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) {
+ mOffscreenOffsetY = (int)(
+ height * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
+ mOffscreenWidth = width;
+ mOffscreenHeight = mOffscreenOffsetY + height;
+ }
+
+ @Override
+ public void onDetachFromWindow() {
+ freeOffscreenBuffer();
+ }
+
+ private void freeOffscreenBuffer() {
+ if (mOffscreenBuffer != null) {
+ mOffscreenBuffer.recycle();
+ mOffscreenBuffer = null;
+ }
+ }
+
+ private void mayAllocateOffscreenBuffer() {
+ if (mOffscreenBuffer != null && mOffscreenBuffer.getWidth() == mOffscreenWidth
+ && mOffscreenBuffer.getHeight() == mOffscreenHeight) {
+ return;
+ }
+ freeOffscreenBuffer();
+ mOffscreenBuffer = Bitmap.createBitmap(
+ mOffscreenWidth, mOffscreenHeight, Bitmap.Config.ARGB_8888);
+ mOffscreenCanvas.setBitmap(mOffscreenBuffer);
+ mOffscreenCanvas.translate(0, mOffscreenOffsetY);
+ }
+
+ private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint,
+ final Rect dirtyRect) {
+ // Clear previous dirty rectangle.
+ if (!dirtyRect.isEmpty()) {
+ paint.setColor(Color.TRANSPARENT);
+ paint.setStyle(Paint.Style.FILL);
+ offscreenCanvas.drawRect(dirtyRect, paint);
+ }
+ dirtyRect.setEmpty();
+ boolean needsUpdatingGesturePreviewTrail = false;
+ // Draw gesture trails to offscreen buffer.
+ synchronized (mGesturePreviewTrails) {
+ // Trails count == fingers count that have ever been active.
+ final int trailsCount = mGesturePreviewTrails.size();
+ for (int index = 0; index < trailsCount; index++) {
+ final GesturePreviewTrail trail = mGesturePreviewTrails.valueAt(index);
+ needsUpdatingGesturePreviewTrail |=
+ trail.drawGestureTrail(offscreenCanvas, paint,
+ mGesturePreviewTrailBoundsRect, mGesturePreviewTrailParams);
+ // {@link #mGesturePreviewTrailBoundsRect} has bounding box of the trail.
+ dirtyRect.union(mGesturePreviewTrailBoundsRect);
+ }
+ }
+ return needsUpdatingGesturePreviewTrail;
+ }
+
+ /**
+ * Draws the preview
+ * @param canvas The canvas where the preview is drawn.
+ */
+ @Override
+ public void drawPreview(final Canvas canvas) {
+ if (!isPreviewEnabled()) {
+ return;
+ }
+ mayAllocateOffscreenBuffer();
+ // Draw gesture trails to offscreen buffer.
+ final boolean needsUpdatingGesturePreviewTrail = drawGestureTrails(
+ mOffscreenCanvas, mGesturePaint, mDirtyRect);
+ if (needsUpdatingGesturePreviewTrail) {
+ mDrawingHandler.postUpdateGestureTrailPreview();
+ }
+ // Transfer offscreen buffer to screen.
+ if (!mDirtyRect.isEmpty()) {
+ mOffscreenSrcRect.set(mDirtyRect);
+ mOffscreenSrcRect.offset(0, mOffscreenOffsetY);
+ canvas.drawBitmap(mOffscreenBuffer, mOffscreenSrcRect, mDirtyRect, null);
+ // Note: Defer clearing the dirty rectangle here because we will get cleared
+ // rectangle on the canvas.
+ }
+ }
+
+ /**
+ * Set the position of the preview.
+ * @param tracker The new location of the preview is based on the points in PointerTracker.
+ */
+ @Override
+ public void setPreviewPosition(final PointerTracker tracker) {
+ if (!isPreviewEnabled()) {
+ return;
+ }
+ GesturePreviewTrail trail;
+ synchronized (mGesturePreviewTrails) {
+ trail = mGesturePreviewTrails.get(tracker.mPointerId);
+ if (trail == null) {
+ trail = new GesturePreviewTrail();
+ mGesturePreviewTrails.put(tracker.mPointerId, trail);
+ }
+ }
+ trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime());
+
+ // TODO: Should narrow the invalidate region.
+ getDrawingView().invalidate();
+ }
+}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeySpecParser.java b/java/src/com/android/inputmethod/keyboard/internal/KeySpecParser.java
index 2caa5eb02..b1813a141 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeySpecParser.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeySpecParser.java
@@ -1,27 +1,28 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
-import static com.android.inputmethod.keyboard.Keyboard.CODE_UNSPECIFIED;
+import static com.android.inputmethod.latin.Constants.CODE_OUTPUT_TEXT;
+import static com.android.inputmethod.latin.Constants.CODE_UNSPECIFIED;
import android.text.TextUtils;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.StringUtils;
@@ -52,8 +53,6 @@ public final class KeySpecParser {
private static final int MAX_STRING_REFERENCE_INDIRECTION = 10;
// Constants for parsing.
- private static int COMMA = ',';
- private static final char ESCAPE_CHAR = '\\';
private static final char LABEL_END = '|';
private static final String PREFIX_TEXT = "!text/";
static final String PREFIX_ICON = "!icon/";
@@ -79,14 +78,14 @@ public final class KeySpecParser {
}
private static String parseEscape(final String text) {
- if (text.indexOf(ESCAPE_CHAR) < 0) {
+ if (text.indexOf(Constants.CSV_ESCAPE) < 0) {
return text;
}
final int length = text.length();
final StringBuilder sb = new StringBuilder();
for (int pos = 0; pos < length; pos++) {
final char c = text.charAt(pos);
- if (c == ESCAPE_CHAR && pos + 1 < length) {
+ if (c == Constants.CSV_ESCAPE && pos + 1 < length) {
// Skip escape char
pos++;
sb.append(text.charAt(pos));
@@ -98,7 +97,7 @@ public final class KeySpecParser {
}
private static int indexOfLabelEnd(final String moreKeySpec, final int start) {
- if (moreKeySpec.indexOf(ESCAPE_CHAR, start) < 0) {
+ if (moreKeySpec.indexOf(Constants.CSV_ESCAPE, start) < 0) {
final int end = moreKeySpec.indexOf(LABEL_END, start);
if (end == 0) {
throw new KeySpecParserError(LABEL_END + " at " + start + ": " + moreKeySpec);
@@ -108,7 +107,7 @@ public final class KeySpecParser {
final int length = moreKeySpec.length();
for (int pos = start; pos < length; pos++) {
final char c = moreKeySpec.charAt(pos);
- if (c == ESCAPE_CHAR && pos + 1 < length) {
+ if (c == Constants.CSV_ESCAPE && pos + 1 < length) {
// Skip escape char
pos++;
} else if (c == LABEL_END) {
@@ -172,7 +171,7 @@ public final class KeySpecParser {
if (indexOfLabelEnd(moreKeySpec, end + 1) >= 0) {
throw new KeySpecParserError("Multiple " + LABEL_END + ": " + moreKeySpec);
}
- return parseCode(moreKeySpec.substring(end + 1), codesSet, Keyboard.CODE_UNSPECIFIED);
+ return parseCode(moreKeySpec.substring(end + 1), codesSet, CODE_UNSPECIFIED);
}
final String outputText = getOutputTextInternal(moreKeySpec);
if (outputText != null) {
@@ -181,14 +180,14 @@ public final class KeySpecParser {
if (StringUtils.codePointCount(outputText) == 1) {
return outputText.codePointAt(0);
}
- return Keyboard.CODE_OUTPUT_TEXT;
+ return CODE_OUTPUT_TEXT;
}
final String label = getLabel(moreKeySpec);
// Code is automatically generated for one letter label.
if (StringUtils.codePointCount(label) == 1) {
return label.codePointAt(0);
}
- return Keyboard.CODE_OUTPUT_TEXT;
+ return CODE_OUTPUT_TEXT;
}
public static int parseCode(final String text, final KeyboardCodesSet codesSet,
@@ -352,7 +351,7 @@ public final class KeySpecParser {
final String name = text.substring(pos + prefixLen, end);
sb.append(textsSet.getText(name));
pos = end - 1;
- } else if (c == ESCAPE_CHAR) {
+ } else if (c == Constants.CSV_ESCAPE) {
if (sb != null) {
// Append both escape character and escaped character.
sb.append(text.substring(pos, Math.min(pos + 2, size)));
@@ -384,45 +383,6 @@ public final class KeySpecParser {
return size;
}
- public static String[] parseCsvString(final String rawText, final KeyboardTextsSet textsSet) {
- final String text = resolveTextReference(rawText, textsSet);
- final int size = text.length();
- if (size == 0) {
- return null;
- }
- if (StringUtils.codePointCount(text) == 1) {
- return text.codePointAt(0) == COMMA ? null : new String[] { text };
- }
-
- ArrayList<String> list = null;
- int start = 0;
- for (int pos = 0; pos < size; pos++) {
- final char c = text.charAt(pos);
- if (c == COMMA) {
- // Skip empty entry.
- if (pos - start > 0) {
- if (list == null) {
- list = CollectionUtils.newArrayList();
- }
- list.add(text.substring(start, pos));
- }
- // Skip comma
- start = pos + 1;
- } else if (c == ESCAPE_CHAR) {
- // Skip escape character and escaped character.
- pos++;
- }
- }
- final String remain = (size - start > 0) ? text.substring(start) : null;
- if (list == null) {
- return remain != null ? new String[] { remain } : null;
- }
- if (remain != null) {
- list.add(remain);
- }
- return list.toArray(new String[list.size()]);
- }
-
public static int getIntValue(final String[] moreKeys, final String key,
final int defaultValue) {
if (moreKeys == null) {
@@ -468,7 +428,7 @@ public final class KeySpecParser {
public static int toUpperCaseOfCodeForLocale(final int code, final boolean needsToUpperCase,
final Locale locale) {
- if (!Keyboard.isLetterCode(code) || !needsToUpperCase) return code;
+ if (!Constants.isLetterCode(code) || !needsToUpperCase) return code;
final String text = new String(new int[] { code } , 0, 1);
final String casedText = KeySpecParser.toUpperCaseOfStringForLocale(
text, needsToUpperCase, locale);
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyStyle.java b/java/src/com/android/inputmethod/keyboard/internal/KeyStyle.java
index e8cacf9e7..5db3ebbd1 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyStyle.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyStyle.java
@@ -1,23 +1,25 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
import android.content.res.TypedArray;
+import com.android.inputmethod.latin.StringUtils;
+
public abstract class KeyStyle {
private final KeyboardTextsSet mTextsSet;
@@ -39,7 +41,8 @@ public abstract class KeyStyle {
protected String[] parseStringArray(final TypedArray a, final int index) {
if (a.hasValue(index)) {
- return KeySpecParser.parseCsvString(a.getString(index), mTextsSet);
+ final String text = KeySpecParser.resolveTextReference(a.getString(index), mTextsSet);
+ return StringUtils.parseCsvString(text);
}
return null;
}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyStylesSet.java b/java/src/com/android/inputmethod/keyboard/internal/KeyStylesSet.java
index 563d22414..a048ad09f 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyStylesSet.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyStylesSet.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardBuilder.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardBuilder.java
index b314a3795..ab851bd64 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardBuilder.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardBuilder.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -21,12 +21,12 @@ import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.util.AttributeSet;
-import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.InflateException;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardId;
@@ -136,7 +136,6 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
protected final KP mParams;
protected final Context mContext;
protected final Resources mResources;
- private final DisplayMetrics mDisplayMetrics;
private int mCurrentY = 0;
private KeyboardRow mCurrentRow = null;
@@ -148,7 +147,6 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
mContext = context;
final Resources res = context.getResources();
mResources = res;
- mDisplayMetrics = res.getDisplayMetrics();
mParams = params;
@@ -166,10 +164,10 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
try {
parseKeyboard(parser);
} catch (XmlPullParserException e) {
- Log.w(BUILDER_TAG, "keyboard XML parse error: " + e);
+ Log.w(BUILDER_TAG, "keyboard XML parse error", e);
throw new IllegalArgumentException(e);
} catch (IOException e) {
- Log.w(BUILDER_TAG, "keyboard XML parse error: " + e);
+ Log.w(BUILDER_TAG, "keyboard XML parse error", e);
throw new RuntimeException(e);
} finally {
parser.close();
@@ -177,7 +175,7 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
return this;
}
- // For test only
+ @UsedForTesting
public void disableTouchPositionCorrectionDataForTest() {
mParams.mTouchPositionCorrection.setEnabled(false);
}
@@ -230,63 +228,43 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
}
private void parseKeyboardAttributes(final XmlPullParser parser) {
- final int displayWidth = mDisplayMetrics.widthPixels;
final TypedArray keyboardAttr = mContext.obtainStyledAttributes(
Xml.asAttributeSet(parser), R.styleable.Keyboard, R.attr.keyboardStyle,
R.style.Keyboard);
final TypedArray keyAttr = mResources.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
try {
- final int displayHeight = mDisplayMetrics.heightPixels;
- final String keyboardHeightString = ResourceUtils.getDeviceOverrideValue(
- mResources, R.array.keyboard_heights, null);
- final float keyboardHeight;
- if (keyboardHeightString != null) {
- keyboardHeight = Float.parseFloat(keyboardHeightString)
- * mDisplayMetrics.density;
- } else {
- keyboardHeight = keyboardAttr.getDimension(
- R.styleable.Keyboard_keyboardHeight, displayHeight / 2);
- }
- final float maxKeyboardHeight = ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_maxKeyboardHeight, displayHeight, displayHeight / 2);
- float minKeyboardHeight = ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_minKeyboardHeight, displayHeight, displayHeight / 2);
- if (minKeyboardHeight < 0) {
- // Specified fraction was negative, so it should be calculated against display
- // width.
- minKeyboardHeight = -ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_minKeyboardHeight, displayWidth, displayWidth / 2);
- }
final KeyboardParams params = mParams;
- // Keyboard height will not exceed maxKeyboardHeight and will not be less than
- // minKeyboardHeight.
- params.mOccupiedHeight = (int)Math.max(
- Math.min(keyboardHeight, maxKeyboardHeight), minKeyboardHeight);
- params.mOccupiedWidth = params.mId.mWidth;
- params.mTopPadding = (int)ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_keyboardTopPadding, params.mOccupiedHeight, 0);
- params.mBottomPadding = (int)ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_keyboardBottomPadding, params.mOccupiedHeight, 0);
- params.mHorizontalEdgesPadding = (int)ResourceUtils.getDimensionOrFraction(
- keyboardAttr,
- R.styleable.Keyboard_keyboardHorizontalEdgesPadding,
- mParams.mOccupiedWidth, 0);
-
- params.mBaseWidth = params.mOccupiedWidth - params.mHorizontalEdgesPadding * 2
- - params.mHorizontalCenterPadding;
- params.mDefaultKeyWidth = (int)ResourceUtils.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_keyWidth, params.mBaseWidth,
- params.mBaseWidth / DEFAULT_KEYBOARD_COLUMNS);
- params.mHorizontalGap = (int)ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_horizontalGap, params.mBaseWidth, 0);
- params.mVerticalGap = (int)ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_verticalGap, params.mOccupiedHeight, 0);
- params.mBaseHeight = params.mOccupiedHeight - params.mTopPadding
+ final int height = params.mId.mHeight;
+ final int width = params.mId.mWidth;
+ params.mOccupiedHeight = height;
+ params.mOccupiedWidth = width;
+ params.mTopPadding = (int)keyboardAttr.getFraction(
+ R.styleable.Keyboard_keyboardTopPadding, height, height, 0);
+ params.mBottomPadding = (int)keyboardAttr.getFraction(
+ R.styleable.Keyboard_keyboardBottomPadding, height, height, 0);
+ params.mLeftPadding = (int)keyboardAttr.getFraction(
+ R.styleable.Keyboard_keyboardLeftPadding, width, width, 0);
+ params.mRightPadding = (int)keyboardAttr.getFraction(
+ R.styleable.Keyboard_keyboardRightPadding, width, width, 0);
+
+ final int baseWidth =
+ params.mOccupiedWidth - params.mLeftPadding - params.mRightPadding;
+ params.mBaseWidth = baseWidth;
+ params.mDefaultKeyWidth = (int)keyAttr.getFraction(R.styleable.Keyboard_Key_keyWidth,
+ baseWidth, baseWidth, baseWidth / DEFAULT_KEYBOARD_COLUMNS);
+ params.mHorizontalGap = (int)keyboardAttr.getFraction(
+ R.styleable.Keyboard_horizontalGap, baseWidth, baseWidth, 0);
+ // TODO: Fix keyboard geometry calculation clearer. Historically vertical gap between
+ // rows are determined based on the entire keyboard height including top and bottom
+ // paddings.
+ params.mVerticalGap = (int)keyboardAttr.getFraction(
+ R.styleable.Keyboard_verticalGap, height, height, 0);
+ final int baseHeight = params.mOccupiedHeight - params.mTopPadding
- params.mBottomPadding + params.mVerticalGap;
+ params.mBaseHeight = baseHeight;
params.mDefaultRowHeight = (int)ResourceUtils.getDimensionOrFraction(keyboardAttr,
- R.styleable.Keyboard_rowHeight, params.mBaseHeight,
- params.mBaseHeight / DEFAULT_KEYBOARD_ROWS);
+ R.styleable.Keyboard_rowHeight, baseHeight, baseHeight / DEFAULT_KEYBOARD_ROWS);
params.mKeyVisualAttributes = KeyVisualAttributes.newInstance(keyAttr);
@@ -621,6 +599,8 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
R.styleable.Keyboard_Case_clobberSettingsKey, id.mClobberSettingsKey);
final boolean shortcutKeyEnabledMatched = matchBoolean(a,
R.styleable.Keyboard_Case_shortcutKeyEnabled, id.mShortcutKeyEnabled);
+ final boolean shortcutKeyOnSymbolsMatched = matchBoolean(a,
+ R.styleable.Keyboard_Case_shortcutKeyOnSymbols, id.mShortcutKeyOnSymbols);
final boolean hasShortcutKeyMatched = matchBoolean(a,
R.styleable.Keyboard_Case_hasShortcutKey, id.mHasShortcutKey);
final boolean languageSwitchKeyEnabledMatched = matchBoolean(a,
@@ -639,12 +619,12 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
final boolean selected = keyboardLayoutSetElementMatched && modeMatched
&& navigateNextMatched && navigatePreviousMatched && passwordInputMatched
&& clobberSettingsKeyMatched && shortcutKeyEnabledMatched
- && hasShortcutKeyMatched && languageSwitchKeyEnabledMatched
- && isMultiLineMatched && imeActionMatched && localeCodeMatched
- && languageCodeMatched && countryCodeMatched;
+ && shortcutKeyOnSymbolsMatched && hasShortcutKeyMatched
+ && languageSwitchKeyEnabledMatched && isMultiLineMatched && imeActionMatched
+ && localeCodeMatched && languageCodeMatched && countryCodeMatched;
if (DEBUG) {
- startTag("<%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s>%s", TAG_CASE,
+ startTag("<%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s>%s", TAG_CASE,
textAttr(a.getString(
R.styleable.Keyboard_Case_keyboardLayoutSetElement),
"keyboardLayoutSetElement"),
@@ -661,6 +641,8 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
"passwordInput"),
booleanAttr(a, R.styleable.Keyboard_Case_shortcutKeyEnabled,
"shortcutKeyEnabled"),
+ booleanAttr(a, R.styleable.Keyboard_Case_shortcutKeyOnSymbols,
+ "shortcutKeyOnSymbols"),
booleanAttr(a, R.styleable.Keyboard_Case_hasShortcutKey,
"hasShortcutKey"),
booleanAttr(a, R.styleable.Keyboard_Case_languageSwitchKeyEnabled,
@@ -760,7 +742,7 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
}
private void startRow(final KeyboardRow row) {
- addEdgeSpace(mParams.mHorizontalEdgesPadding, row);
+ addEdgeSpace(mParams.mLeftPadding, row);
mCurrentRow = row;
mLeftEdge = true;
mRightEdgeKey = null;
@@ -774,7 +756,7 @@ public class KeyboardBuilder<KP extends KeyboardParams> {
mRightEdgeKey.markAsRightEdge(mParams);
mRightEdgeKey = null;
}
- addEdgeSpace(mParams.mHorizontalEdgesPadding, row);
+ addEdgeSpace(mParams.mRightPadding, row);
mCurrentY += row.mRowHeight;
mCurrentRow = null;
mTopEdge = false;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardCodesSet.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardCodesSet.java
index 840d7133d..3e25c3b86 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardCodesSet.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardCodesSet.java
@@ -1,23 +1,23 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
import java.util.HashMap;
@@ -48,9 +48,9 @@ public final class KeyboardCodesSet {
"key_delete",
"key_settings",
"key_shortcut",
- "key_action_enter",
"key_action_next",
"key_action_previous",
+ "key_shift_enter",
"key_language_switch",
"key_research",
"key_unspecified",
@@ -73,22 +73,23 @@ public final class KeyboardCodesSet {
private static final int CODE_LEFT_CURLY_BRACKET = '{';
private static final int CODE_RIGHT_CURLY_BRACKET = '}';
+ // This array should be aligned with the array RTL below.
private static final int[] DEFAULT = {
- Keyboard.CODE_TAB,
- Keyboard.CODE_ENTER,
- Keyboard.CODE_SPACE,
- Keyboard.CODE_SHIFT,
- Keyboard.CODE_SWITCH_ALPHA_SYMBOL,
- Keyboard.CODE_OUTPUT_TEXT,
- Keyboard.CODE_DELETE,
- Keyboard.CODE_SETTINGS,
- Keyboard.CODE_SHORTCUT,
- Keyboard.CODE_ACTION_ENTER,
- Keyboard.CODE_ACTION_NEXT,
- Keyboard.CODE_ACTION_PREVIOUS,
- Keyboard.CODE_LANGUAGE_SWITCH,
- Keyboard.CODE_RESEARCH,
- Keyboard.CODE_UNSPECIFIED,
+ Constants.CODE_TAB,
+ Constants.CODE_ENTER,
+ Constants.CODE_SPACE,
+ Constants.CODE_SHIFT,
+ Constants.CODE_SWITCH_ALPHA_SYMBOL,
+ Constants.CODE_OUTPUT_TEXT,
+ Constants.CODE_DELETE,
+ Constants.CODE_SETTINGS,
+ Constants.CODE_SHORTCUT,
+ Constants.CODE_ACTION_NEXT,
+ Constants.CODE_ACTION_PREVIOUS,
+ Constants.CODE_SHIFT_ENTER,
+ Constants.CODE_LANGUAGE_SWITCH,
+ Constants.CODE_RESEARCH,
+ Constants.CODE_UNSPECIFIED,
CODE_LEFT_PARENTHESIS,
CODE_RIGHT_PARENTHESIS,
CODE_LESS_THAN_SIGN,
@@ -138,6 +139,9 @@ public final class KeyboardCodesSet {
};
static {
+ if (DEFAULT.length != RTL.length || DEFAULT.length != ID_TO_NAME.length) {
+ throw new RuntimeException("Internal inconsistency");
+ }
for (int i = 0; i < ID_TO_NAME.length; i++) {
sNameToIdMap.put(ID_TO_NAME[i], i);
}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardIconsSet.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardIconsSet.java
index 7292e8e19..4ac2549c7 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardIconsSet.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardIconsSet.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardParams.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardParams.java
index e6fe50e02..15eb690e1 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardParams.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardParams.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -19,9 +19,9 @@ package com.android.inputmethod.keyboard.internal;
import android.util.SparseIntArray;
import com.android.inputmethod.keyboard.Key;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
import java.util.ArrayList;
import java.util.TreeSet;
@@ -42,8 +42,8 @@ public class KeyboardParams {
public int mTopPadding;
public int mBottomPadding;
- public int mHorizontalEdgesPadding;
- public int mHorizontalCenterPadding;
+ public int mLeftPadding;
+ public int mRightPadding;
public KeyVisualAttributes mKeyVisualAttributes;
@@ -89,7 +89,7 @@ public class KeyboardParams {
mKeys.add(key);
updateHistogram(key);
}
- if (key.mCode == Keyboard.CODE_SHIFT) {
+ if (key.mCode == Constants.CODE_SHIFT) {
mShiftKeys.add(key);
}
if (key.altCodeWhileTyping()) {
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardRow.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardRow.java
index b986262d7..855f65507 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardRow.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardRow.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -54,17 +54,16 @@ public final class KeyboardRow {
public KeyboardRow(final Resources res, final KeyboardParams params, final XmlPullParser parser,
final int y) {
mParams = params;
- TypedArray keyboardAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
+ final TypedArray keyboardAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard);
mRowHeight = (int)ResourceUtils.getDimensionOrFraction(keyboardAttr,
R.styleable.Keyboard_rowHeight,
params.mBaseHeight, params.mDefaultRowHeight);
keyboardAttr.recycle();
- TypedArray keyAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
+ final TypedArray keyAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
- mDefaultKeyWidth = ResourceUtils.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_keyWidth,
- params.mBaseWidth, params.mDefaultKeyWidth);
+ mDefaultKeyWidth = keyAttr.getFraction(R.styleable.Keyboard_Key_keyWidth,
+ params.mBaseWidth, params.mBaseWidth, params.mDefaultKeyWidth);
mDefaultBackgroundType = keyAttr.getInt(R.styleable.Keyboard_Key_backgroundType,
Key.BACKGROUND_TYPE_NORMAL);
keyAttr.recycle();
@@ -112,20 +111,19 @@ public final class KeyboardRow {
}
public float getKeyX(final TypedArray keyAttr) {
- final int keyboardRightEdge = mParams.mOccupiedWidth
- - mParams.mHorizontalEdgesPadding;
if (keyAttr.hasValue(R.styleable.Keyboard_Key_keyXPos)) {
- final float keyXPos = ResourceUtils.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_keyXPos, mParams.mBaseWidth, 0);
+ final float keyXPos = keyAttr.getFraction(R.styleable.Keyboard_Key_keyXPos,
+ mParams.mBaseWidth, mParams.mBaseWidth, 0);
if (keyXPos < 0) {
// If keyXPos is negative, the actual x-coordinate will be
// keyboardWidth + keyXPos.
// keyXPos shouldn't be less than mCurrentX because drawable area for this
// key starts at mCurrentX. Or, this key will overlaps the adjacent key on
// its left hand side.
+ final int keyboardRightEdge = mParams.mOccupiedWidth - mParams.mRightPadding;
return Math.max(keyXPos + keyboardRightEdge, mCurrentX);
} else {
- return keyXPos + mParams.mHorizontalEdgesPadding;
+ return keyXPos + mParams.mLeftPadding;
}
}
return mCurrentX;
@@ -140,15 +138,13 @@ public final class KeyboardRow {
R.styleable.Keyboard_Key_keyWidth, KEYWIDTH_NOT_ENUM);
switch (widthType) {
case KEYWIDTH_FILL_RIGHT:
- final int keyboardRightEdge =
- mParams.mOccupiedWidth - mParams.mHorizontalEdgesPadding;
// If keyWidth is fillRight, the actual key width will be determined to fill
// out the area up to the right edge of the keyboard.
+ final int keyboardRightEdge = mParams.mOccupiedWidth - mParams.mRightPadding;
return keyboardRightEdge - keyXPos;
default: // KEYWIDTH_NOT_ENUM
- return ResourceUtils.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_keyWidth,
- mParams.mBaseWidth, mDefaultKeyWidth);
+ return keyAttr.getFraction(R.styleable.Keyboard_Key_keyWidth,
+ mParams.mBaseWidth, mParams.mBaseWidth, mDefaultKeyWidth);
}
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java
index 631e647e8..95d9ccb58 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -19,7 +19,6 @@ package com.android.inputmethod.keyboard.internal;
import android.text.TextUtils;
import android.util.Log;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.latin.Constants;
/**
@@ -27,7 +26,7 @@ import com.android.inputmethod.latin.Constants;
*
* This class contains all keyboard state transition logic.
*
- * The input events are {@link #onLoadKeyboard(String)}, {@link #onSaveKeyboardState()},
+ * The input events are {@link #onLoadKeyboard()}, {@link #onSaveKeyboardState()},
* {@link #onPressKey(int, boolean, int)}, {@link #onReleaseKey(int, boolean)},
* {@link #onCodeInput(int, boolean, int)}, {@link #onCancelInput(boolean)},
* {@link #onUpdateShiftState(int)}, {@link #onLongPressTimeout(int)}.
@@ -75,7 +74,6 @@ public final class KeyboardState {
private static final int SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL = 3;
private static final int SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE = 4;
private int mSwitchState = SWITCH_STATE_ALPHA;
- private String mLayoutSwitchBackSymbols;
private boolean mIsAlphabetMode;
private AlphabetShiftState mAlphabetShiftState = new AlphabetShiftState();
@@ -110,15 +108,14 @@ public final class KeyboardState {
}
}
- public KeyboardState(SwitchActions switchActions) {
+ public KeyboardState(final SwitchActions switchActions) {
mSwitchActions = switchActions;
}
- public void onLoadKeyboard(String layoutSwitchBackSymbols) {
+ public void onLoadKeyboard() {
if (DEBUG_EVENT) {
Log.d(TAG, "onLoadKeyboard: " + this);
}
- mLayoutSwitchBackSymbols = layoutSwitchBackSymbols;
// Reset alphabet shift state.
mAlphabetShiftState.setShiftLocked(false);
mPrevMainKeyboardWasShiftLocked = false;
@@ -178,7 +175,7 @@ public final class KeyboardState {
private static final int AUTOMATIC_SHIFT = 2;
private static final int SHIFT_LOCK_SHIFTED = 3;
- private void setShifted(int shiftMode) {
+ private void setShifted(final int shiftMode) {
if (DEBUG_ACTION) {
Log.d(TAG, "setShifted: shiftMode=" + shiftModeToString(shiftMode) + " " + this);
}
@@ -217,7 +214,7 @@ public final class KeyboardState {
}
}
- private void setShiftLocked(boolean shiftLocked) {
+ private void setShiftLocked(final boolean shiftLocked) {
if (DEBUG_ACTION) {
Log.d(TAG, "setShiftLocked: shiftLocked=" + shiftLocked + " " + this);
}
@@ -314,14 +311,14 @@ public final class KeyboardState {
mSwitchState = SWITCH_STATE_SYMBOL_BEGIN;
}
- public void onPressKey(int code, boolean isSinglePointer, int autoCaps) {
+ public void onPressKey(final int code, final boolean isSinglePointer, final int autoCaps) {
if (DEBUG_EVENT) {
- Log.d(TAG, "onPressKey: code=" + Keyboard.printableCode(code)
+ Log.d(TAG, "onPressKey: code=" + Constants.printableCode(code)
+ " single=" + isSinglePointer + " autoCaps=" + autoCaps + " " + this);
}
- if (code == Keyboard.CODE_SHIFT) {
+ if (code == Constants.CODE_SHIFT) {
onPressShift();
- } else if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
+ } else if (code == Constants.CODE_SWITCH_ALPHA_SYMBOL) {
onPressSymbol();
} else {
mSwitchActions.cancelDoubleTapTimer();
@@ -347,14 +344,14 @@ public final class KeyboardState {
}
}
- public void onReleaseKey(int code, boolean withSliding) {
+ public void onReleaseKey(final int code, final boolean withSliding) {
if (DEBUG_EVENT) {
- Log.d(TAG, "onReleaseKey: code=" + Keyboard.printableCode(code)
+ Log.d(TAG, "onReleaseKey: code=" + Constants.printableCode(code)
+ " sliding=" + withSliding + " " + this);
}
- if (code == Keyboard.CODE_SHIFT) {
+ if (code == Constants.CODE_SHIFT) {
onReleaseShift(withSliding);
- } else if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
+ } else if (code == Constants.CODE_SWITCH_ALPHA_SYMBOL) {
onReleaseSymbol(withSliding);
}
}
@@ -365,7 +362,7 @@ public final class KeyboardState {
mSwitchState = SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL;
}
- private void onReleaseSymbol(boolean withSliding) {
+ private void onReleaseSymbol(final boolean withSliding) {
if (mSymbolKeyState.isChording()) {
// Switch back to the previous keyboard mode if the user chords the mode change key and
// another key, then releases the mode change key.
@@ -379,17 +376,17 @@ public final class KeyboardState {
mSymbolKeyState.onRelease();
}
- public void onLongPressTimeout(int code) {
+ public void onLongPressTimeout(final int code) {
if (DEBUG_EVENT) {
- Log.d(TAG, "onLongPressTimeout: code=" + Keyboard.printableCode(code) + " " + this);
+ Log.d(TAG, "onLongPressTimeout: code=" + Constants.printableCode(code) + " " + this);
}
- if (mIsAlphabetMode && code == Keyboard.CODE_SHIFT) {
+ if (mIsAlphabetMode && code == Constants.CODE_SHIFT) {
mLongPressShiftLockFired = true;
mSwitchActions.hapticAndAudioFeedback(code);
}
}
- public void onUpdateShiftState(int autoCaps) {
+ public void onUpdateShiftState(final int autoCaps) {
if (DEBUG_EVENT) {
Log.d(TAG, "onUpdateShiftState: autoCaps=" + autoCaps + " " + this);
}
@@ -405,7 +402,7 @@ public final class KeyboardState {
resetKeyboardStateToAlphabet();
}
- private void updateAlphabetShiftState(int autoCaps) {
+ private void updateAlphabetShiftState(final int autoCaps) {
if (!mIsAlphabetMode) return;
if (!mShiftKeyState.isReleasing()) {
// Ignore update shift state event while the shift key is being pressed (including
@@ -459,7 +456,7 @@ public final class KeyboardState {
setShifted(MANUAL_SHIFT);
mShiftKeyState.onPress();
}
- mSwitchActions.startLongPressTimer(Keyboard.CODE_SHIFT);
+ mSwitchActions.startLongPressTimer(Constants.CODE_SHIFT);
}
} else {
// In symbol mode, just toggle symbol and symbol more keyboard.
@@ -469,7 +466,7 @@ public final class KeyboardState {
}
}
- private void onReleaseShift(boolean withSliding) {
+ private void onReleaseShift(final boolean withSliding) {
if (mIsAlphabetMode) {
final boolean isShiftLocked = mAlphabetShiftState.isShiftLocked();
mIsInAlphabetUnshiftedFromShifted = false;
@@ -524,7 +521,7 @@ public final class KeyboardState {
mShiftKeyState.onRelease();
}
- public void onCancelInput(boolean isSinglePointer) {
+ public void onCancelInput(final boolean isSinglePointer) {
if (DEBUG_EVENT) {
Log.d(TAG, "onCancelInput: single=" + isSinglePointer + " " + this);
}
@@ -543,26 +540,20 @@ public final class KeyboardState {
|| mSwitchState == SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE;
}
- private static boolean isSpaceCharacter(int c) {
- return c == Keyboard.CODE_SPACE || c == Keyboard.CODE_ENTER;
+ private static boolean isSpaceCharacter(final int c) {
+ return c == Constants.CODE_SPACE || c == Constants.CODE_ENTER;
}
- private boolean isLayoutSwitchBackCharacter(int c) {
- if (TextUtils.isEmpty(mLayoutSwitchBackSymbols)) return false;
- if (mLayoutSwitchBackSymbols.indexOf(c) >= 0) return true;
- return false;
- }
-
- public void onCodeInput(int code, boolean isSinglePointer, int autoCaps) {
+ public void onCodeInput(final int code, final boolean isSinglePointer, final int autoCaps) {
if (DEBUG_EVENT) {
- Log.d(TAG, "onCodeInput: code=" + Keyboard.printableCode(code)
+ Log.d(TAG, "onCodeInput: code=" + Constants.printableCode(code)
+ " single=" + isSinglePointer
+ " autoCaps=" + autoCaps + " " + this);
}
switch (mSwitchState) {
case SWITCH_STATE_MOMENTARY_ALPHA_AND_SYMBOL:
- if (code == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
+ if (code == Constants.CODE_SWITCH_ALPHA_SYMBOL) {
// Detected only the mode change key has been pressed, and then released.
if (mIsAlphabetMode) {
mSwitchState = SWITCH_STATE_ALPHA;
@@ -578,7 +569,7 @@ public final class KeyboardState {
}
break;
case SWITCH_STATE_MOMENTARY_SYMBOL_AND_MORE:
- if (code == Keyboard.CODE_SHIFT) {
+ if (code == Constants.CODE_SHIFT) {
// Detected only the shift key has been pressed on symbol layout, and then released.
mSwitchState = SWITCH_STATE_SYMBOL_BEGIN;
} else if (isSinglePointer) {
@@ -589,21 +580,15 @@ public final class KeyboardState {
}
break;
case SWITCH_STATE_SYMBOL_BEGIN:
- if (!isSpaceCharacter(code) && (Keyboard.isLetterCode(code)
- || code == Keyboard.CODE_OUTPUT_TEXT)) {
+ if (!isSpaceCharacter(code) && (Constants.isLetterCode(code)
+ || code == Constants.CODE_OUTPUT_TEXT)) {
mSwitchState = SWITCH_STATE_SYMBOL;
}
- // Switch back to alpha keyboard mode immediately if user types one of the switch back
- // characters.
- if (isLayoutSwitchBackCharacter(code)) {
- toggleAlphabetAndSymbols();
- mPrevSymbolsKeyboardWasShifted = false;
- }
break;
case SWITCH_STATE_SYMBOL:
// Switch back to alpha keyboard mode if user types one or more non-space/enter
- // characters followed by a space/enter or one of the switch back characters.
- if (isSpaceCharacter(code) || isLayoutSwitchBackCharacter(code)) {
+ // characters followed by a space/enter.
+ if (isSpaceCharacter(code)) {
toggleAlphabetAndSymbols();
mPrevSymbolsKeyboardWasShifted = false;
}
@@ -611,12 +596,12 @@ public final class KeyboardState {
}
// If the code is a letter, update keyboard shift state.
- if (Keyboard.isLetterCode(code)) {
+ if (Constants.isLetterCode(code)) {
updateAlphabetShiftState(autoCaps);
}
}
- private static String shiftModeToString(int shiftMode) {
+ private static String shiftModeToString(final int shiftMode) {
switch (shiftMode) {
case UNSHIFT: return "UNSHIFT";
case MANUAL_SHIFT: return "MANUAL";
@@ -625,7 +610,7 @@ public final class KeyboardState {
}
}
- private static String switchStateToString(int switchState) {
+ private static String switchStateToString(final int switchState) {
switch (switchState) {
case SWITCH_STATE_ALPHA: return "ALPHA";
case SWITCH_STATE_SYMBOL_BEGIN: return "SYMBOL-BEGIN";
@@ -639,7 +624,7 @@ public final class KeyboardState {
@Override
public String toString() {
return "[keyboard=" + (mIsAlphabetMode ? mAlphabetShiftState.toString()
- : (mIsSymbolShifted ? "SYMBOLS_SHIFTED" : "SYMBOLS"))
+ : (mIsSymbolShifted ? "SYMBOLS_SHIFTED" : "SYMBOLS"))
+ " shift=" + mShiftKeyState
+ " symbol=" + mSymbolKeyState
+ " switch=" + switchStateToString(mSwitchState) + "]";
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardTextsSet.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardTextsSet.java
index 3bb272f8c..493093e95 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardTextsSet.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardTextsSet.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -19,6 +19,7 @@ package com.android.inputmethod.keyboard.internal;
import android.content.Context;
import android.content.res.Resources;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.R;
@@ -64,7 +65,7 @@ public final class KeyboardTextsSet {
loadStringResourcesInternal(context, RESOURCE_NAMES, R.string.english_ime_name);
}
- /* package for test */
+ @UsedForTesting
void loadStringResourcesInternal(Context context, final String[] resourceNames,
int referenceId) {
final Resources res = context.getResources();
@@ -96,9 +97,6 @@ public final class KeyboardTextsSet {
"label_done_key",
"label_previous_key",
// Other labels.
- "label_to_alpha_key",
- "label_to_symbol_key",
- "label_to_symbol_with_microphone_key",
"label_pause_key",
"label_wait_key",
};
@@ -146,13 +144,13 @@ public final class KeyboardTextsSet {
/* 39 */ "keylabel_for_south_slavic_row3_8",
/* 40 */ "more_keys_for_cyrillic_ie",
/* 41 */ "more_keys_for_cyrillic_i",
- /* 42 */ "more_keys_for_single_quote",
- /* 43 */ "more_keys_for_double_quote",
- /* 44 */ "more_keys_for_tablet_double_quote",
- /* 45 */ "more_keys_for_currency_dollar",
- /* 46 */ "more_keys_for_currency_euro",
- /* 47 */ "more_keys_for_currency_pound",
- /* 48 */ "more_keys_for_currency_general",
+ /* 42 */ "label_to_alpha_key",
+ /* 43 */ "more_keys_for_single_quote",
+ /* 44 */ "more_keys_for_double_quote",
+ /* 45 */ "more_keys_for_tablet_double_quote",
+ /* 46 */ "more_keys_for_currency_dollar",
+ /* 47 */ "keylabel_for_currency_generic",
+ /* 48 */ "more_keys_for_currency_generic",
/* 49 */ "more_keys_for_punctuation",
/* 50 */ "more_keys_for_star",
/* 51 */ "more_keys_for_bullet",
@@ -173,66 +171,68 @@ public final class KeyboardTextsSet {
/* 66 */ "keylabel_for_symbols_8",
/* 67 */ "keylabel_for_symbols_9",
/* 68 */ "keylabel_for_symbols_0",
- /* 69 */ "additional_more_keys_for_symbols_1",
- /* 70 */ "additional_more_keys_for_symbols_2",
- /* 71 */ "additional_more_keys_for_symbols_3",
- /* 72 */ "additional_more_keys_for_symbols_4",
- /* 73 */ "additional_more_keys_for_symbols_5",
- /* 74 */ "additional_more_keys_for_symbols_6",
- /* 75 */ "additional_more_keys_for_symbols_7",
- /* 76 */ "additional_more_keys_for_symbols_8",
- /* 77 */ "additional_more_keys_for_symbols_9",
- /* 78 */ "additional_more_keys_for_symbols_0",
- /* 79 */ "more_keys_for_symbols_1",
- /* 80 */ "more_keys_for_symbols_2",
- /* 81 */ "more_keys_for_symbols_3",
- /* 82 */ "more_keys_for_symbols_4",
- /* 83 */ "more_keys_for_symbols_5",
- /* 84 */ "more_keys_for_symbols_6",
- /* 85 */ "more_keys_for_symbols_7",
- /* 86 */ "more_keys_for_symbols_8",
- /* 87 */ "more_keys_for_symbols_9",
- /* 88 */ "more_keys_for_symbols_0",
- /* 89 */ "keylabel_for_comma",
- /* 90 */ "more_keys_for_comma",
- /* 91 */ "keylabel_for_symbols_question",
- /* 92 */ "keylabel_for_symbols_semicolon",
- /* 93 */ "keylabel_for_symbols_percent",
- /* 94 */ "more_keys_for_symbols_exclamation",
- /* 95 */ "more_keys_for_symbols_question",
- /* 96 */ "more_keys_for_symbols_semicolon",
- /* 97 */ "more_keys_for_symbols_percent",
- /* 98 */ "keylabel_for_tablet_comma",
- /* 99 */ "keyhintlabel_for_tablet_comma",
- /* 100 */ "more_keys_for_tablet_comma",
- /* 101 */ "keyhintlabel_for_tablet_period",
- /* 102 */ "more_keys_for_tablet_period",
- /* 103 */ "keylabel_for_apostrophe",
- /* 104 */ "keyhintlabel_for_apostrophe",
- /* 105 */ "more_keys_for_apostrophe",
- /* 106 */ "more_keys_for_q",
- /* 107 */ "more_keys_for_x",
- /* 108 */ "keylabel_for_q",
- /* 109 */ "keylabel_for_w",
- /* 110 */ "keylabel_for_y",
- /* 111 */ "keylabel_for_x",
- /* 112 */ "keylabel_for_spanish_row2_10",
- /* 113 */ "more_keys_for_am_pm",
- /* 114 */ "settings_as_more_key",
- /* 115 */ "shortcut_as_more_key",
- /* 116 */ "action_next_as_more_key",
- /* 117 */ "action_previous_as_more_key",
- /* 118 */ "label_to_more_symbol_key",
- /* 119 */ "label_to_more_symbol_for_tablet_key",
- /* 120 */ "label_tab_key",
- /* 121 */ "label_to_phone_numeric_key",
- /* 122 */ "label_to_phone_symbols_key",
- /* 123 */ "label_time_am",
- /* 124 */ "label_time_pm",
- /* 125 */ "label_to_symbol_key_pcqwerty",
- /* 126 */ "keylabel_for_popular_domain",
- /* 127 */ "more_keys_for_popular_domain",
- /* 128 */ "more_keys_for_smiley",
+ /* 69 */ "label_to_symbol_key",
+ /* 70 */ "label_to_symbol_with_microphone_key",
+ /* 71 */ "additional_more_keys_for_symbols_1",
+ /* 72 */ "additional_more_keys_for_symbols_2",
+ /* 73 */ "additional_more_keys_for_symbols_3",
+ /* 74 */ "additional_more_keys_for_symbols_4",
+ /* 75 */ "additional_more_keys_for_symbols_5",
+ /* 76 */ "additional_more_keys_for_symbols_6",
+ /* 77 */ "additional_more_keys_for_symbols_7",
+ /* 78 */ "additional_more_keys_for_symbols_8",
+ /* 79 */ "additional_more_keys_for_symbols_9",
+ /* 80 */ "additional_more_keys_for_symbols_0",
+ /* 81 */ "more_keys_for_symbols_1",
+ /* 82 */ "more_keys_for_symbols_2",
+ /* 83 */ "more_keys_for_symbols_3",
+ /* 84 */ "more_keys_for_symbols_4",
+ /* 85 */ "more_keys_for_symbols_5",
+ /* 86 */ "more_keys_for_symbols_6",
+ /* 87 */ "more_keys_for_symbols_7",
+ /* 88 */ "more_keys_for_symbols_8",
+ /* 89 */ "more_keys_for_symbols_9",
+ /* 90 */ "more_keys_for_symbols_0",
+ /* 91 */ "keylabel_for_comma",
+ /* 92 */ "more_keys_for_comma",
+ /* 93 */ "keylabel_for_symbols_question",
+ /* 94 */ "keylabel_for_symbols_semicolon",
+ /* 95 */ "keylabel_for_symbols_percent",
+ /* 96 */ "more_keys_for_symbols_exclamation",
+ /* 97 */ "more_keys_for_symbols_question",
+ /* 98 */ "more_keys_for_symbols_semicolon",
+ /* 99 */ "more_keys_for_symbols_percent",
+ /* 100 */ "keylabel_for_tablet_comma",
+ /* 101 */ "keyhintlabel_for_tablet_comma",
+ /* 102 */ "more_keys_for_tablet_comma",
+ /* 103 */ "keyhintlabel_for_tablet_period",
+ /* 104 */ "more_keys_for_tablet_period",
+ /* 105 */ "keylabel_for_apostrophe",
+ /* 106 */ "keyhintlabel_for_apostrophe",
+ /* 107 */ "more_keys_for_apostrophe",
+ /* 108 */ "more_keys_for_q",
+ /* 109 */ "more_keys_for_x",
+ /* 110 */ "keylabel_for_q",
+ /* 111 */ "keylabel_for_w",
+ /* 112 */ "keylabel_for_y",
+ /* 113 */ "keylabel_for_x",
+ /* 114 */ "keylabel_for_spanish_row2_10",
+ /* 115 */ "more_keys_for_am_pm",
+ /* 116 */ "settings_as_more_key",
+ /* 117 */ "shortcut_as_more_key",
+ /* 118 */ "action_next_as_more_key",
+ /* 119 */ "action_previous_as_more_key",
+ /* 120 */ "label_to_more_symbol_key",
+ /* 121 */ "label_to_more_symbol_for_tablet_key",
+ /* 122 */ "label_tab_key",
+ /* 123 */ "label_to_phone_numeric_key",
+ /* 124 */ "label_to_phone_symbols_key",
+ /* 125 */ "label_time_am",
+ /* 126 */ "label_time_pm",
+ /* 127 */ "label_to_symbol_key_pcqwerty",
+ /* 128 */ "keylabel_for_popular_domain",
+ /* 129 */ "more_keys_for_popular_domain",
+ /* 130 */ "more_keys_for_smiley",
};
private static final String EMPTY = "";
@@ -245,22 +245,23 @@ public final class KeyboardTextsSet {
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY,
/* ~41 */
- /* 42 */ "!fixedColumnOrder!4,\u2018,\u2019,\u201A,\u201B",
+ // Label for "switch to alphabetic" key.
+ /* 42 */ "ABC",
+ /* 43 */ "!fixedColumnOrder!4,\u2018,\u2019,\u201A,\u201B",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK.
// <string name="more_keys_for_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;,&#x00BB;</string>
- /* 43 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB,\u00BB",
+ /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB,\u00BB",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK.
// <string name="more_keys_for_tablet_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;,&#x00BB;,&#x2018;,&#x2019;,&#x201A;,&#x201B;</string>
- /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB,\u00BB,\u2018,\u2019,\u201A,\u201B",
+ /* 45 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB,\u00BB,\u2018,\u2019,\u201A,\u201B",
// U+00A2: "¢" CENT SIGN
// U+00A3: "£" POUND SIGN
// U+20AC: "€" EURO SIGN
// U+00A5: "¥" YEN SIGN
// U+20B1: "₱" PESO SIGN
- /* 45 */ "\u00A2,\u00A3,\u20AC,\u00A5,\u20B1",
- /* 46 */ "\u00A2,\u00A3,$,\u00A5,\u20B1",
- /* 47 */ "\u00A2,$,\u20AC,\u00A5,\u20B1",
- /* 48 */ "\u00A2,$,\u20AC,\u00A3,\u00A5,\u20B1",
+ /* 46 */ "\u00A2,\u00A3,\u20AC,\u00A5,\u20B1",
+ /* 47 */ "$",
+ /* 48 */ "$,\u00A2,\u20AC,\u00A3,\u00A5,\u20B1",
/* 49 */ "!fixedColumnOrder!8,\",\',#,-,:,!,\\,,?,@,&,\\%,+,;,/,(,)",
// U+2020: "†" DAGGER
// U+2021: "‡" DOUBLE DAGGER
@@ -307,89 +308,94 @@ public final class KeyboardTextsSet {
/* 66 */ "8",
/* 67 */ "9",
/* 68 */ "0",
- /* 69~ */
+ // Label for "switch to symbols" key.
+ /* 69 */ "?123",
+ // Label for "switch to symbols with microphone" key. This string shouldn't include the "mic"
+ // part because it'll be appended by the code.
+ /* 70 */ "123",
+ /* 71~ */
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,
- /* ~78 */
+ /* ~80 */
// U+00B9: "¹" SUPERSCRIPT ONE
// U+00BD: "½" VULGAR FRACTION ONE HALF
// U+2153: "⅓" VULGAR FRACTION ONE THIRD
// U+00BC: "¼" VULGAR FRACTION ONE QUARTER
// U+215B: "⅛" VULGAR FRACTION ONE EIGHTH
- /* 79 */ "\u00B9,\u00BD,\u2153,\u00BC,\u215B",
+ /* 81 */ "\u00B9,\u00BD,\u2153,\u00BC,\u215B",
// U+00B2: "²" SUPERSCRIPT TWO
// U+2154: "⅔" VULGAR FRACTION TWO THIRDS
- /* 80 */ "\u00B2,\u2154",
+ /* 82 */ "\u00B2,\u2154",
// U+00B3: "³" SUPERSCRIPT THREE
// U+00BE: "¾" VULGAR FRACTION THREE QUARTERS
// U+215C: "⅜" VULGAR FRACTION THREE EIGHTHS
- /* 81 */ "\u00B3,\u00BE,\u215C",
+ /* 83 */ "\u00B3,\u00BE,\u215C",
// U+2074: "⁴" SUPERSCRIPT FOUR
- /* 82 */ "\u2074",
+ /* 84 */ "\u2074",
// U+215D: "⅝" VULGAR FRACTION FIVE EIGHTHS
- /* 83 */ "\u215D",
- /* 84 */ EMPTY,
- // U+215E: "⅞" VULGAR FRACTION SEVEN EIGHTHS
- /* 85 */ "\u215E",
+ /* 85 */ "\u215D",
/* 86 */ EMPTY,
- /* 87 */ EMPTY,
+ // U+215E: "⅞" VULGAR FRACTION SEVEN EIGHTHS
+ /* 87 */ "\u215E",
+ /* 88 */ EMPTY,
+ /* 89 */ EMPTY,
// U+207F: "ⁿ" SUPERSCRIPT LATIN SMALL LETTER N
// U+2205: "∅" EMPTY SET
- /* 88 */ "\u207F,\u2205",
- /* 89 */ ",",
- /* 90 */ EMPTY,
- /* 91 */ "?",
- /* 92 */ ";",
- /* 93 */ "%",
+ /* 90 */ "\u207F,\u2205",
+ /* 91 */ ",",
+ /* 92 */ EMPTY,
+ /* 93 */ "?",
+ /* 94 */ ";",
+ /* 95 */ "%",
// U+00A1: "¡" INVERTED EXCLAMATION MARK
- /* 94 */ "\u00A1",
+ /* 96 */ "\u00A1",
// U+00BF: "¿" INVERTED QUESTION MARK
- /* 95 */ "\u00BF",
- /* 96 */ EMPTY,
+ /* 97 */ "\u00BF",
+ /* 98 */ EMPTY,
// U+2030: "‰" PER MILLE SIGN
- /* 97 */ "\u2030",
- /* 98 */ ",",
- /* 99 */ "!",
- /* 100 */ "!",
- /* 101 */ "?",
- /* 102 */ "?",
- /* 103 */ "\'",
- /* 104 */ "\"",
- /* 105 */ "\"",
- /* 106 */ EMPTY,
- /* 107 */ EMPTY,
- /* 108 */ "q",
- /* 109 */ "w",
- /* 110 */ "y",
- /* 111 */ "x",
+ /* 99 */ "\u2030",
+ /* 100 */ ",",
+ /* 101 */ "!",
+ /* 102 */ "!",
+ /* 103 */ "?",
+ /* 104 */ "?",
+ /* 105 */ "\'",
+ /* 106 */ "\"",
+ /* 107 */ "\"",
+ /* 108 */ EMPTY,
+ /* 109 */ EMPTY,
+ /* 110 */ "q",
+ /* 111 */ "w",
+ /* 112 */ "y",
+ /* 113 */ "x",
// U+00F1: "ñ" LATIN SMALL LETTER N WITH TILDE
- /* 112 */ "\u00F1",
- /* 113 */ "!fixedColumnOrder!2,!hasLabels!,!text/label_time_am,!text/label_time_pm",
- /* 114 */ "!icon/settings_key|!code/key_settings",
- /* 115 */ "!icon/shortcut_key|!code/key_shortcut",
- /* 116 */ "!hasLabels!,!text/label_next_key|!code/key_action_next",
- /* 117 */ "!hasLabels!,!text/label_previous_key|!code/key_action_previous",
+ /* 114 */ "\u00F1",
+ /* 115 */ "!fixedColumnOrder!2,!hasLabels!,!text/label_time_am,!text/label_time_pm",
+ /* 116 */ "!icon/settings_key|!code/key_settings",
+ /* 117 */ "!icon/shortcut_key|!code/key_shortcut",
+ /* 118 */ "!hasLabels!,!text/label_next_key|!code/key_action_next",
+ /* 119 */ "!hasLabels!,!text/label_previous_key|!code/key_action_previous",
// Label for "switch to more symbol" modifier key. Must be short to fit on key!
- /* 118 */ "= \\ <",
+ /* 120 */ "= \\ <",
// Label for "switch to more symbol" modifier key on tablets. Must be short to fit on key!
- /* 119 */ "~ \\ {",
+ /* 121 */ "~ \\ {",
// Label for "Tab" key. Must be short to fit on key!
- /* 120 */ "Tab",
+ /* 122 */ "Tab",
// Label for "switch to phone numeric" key. Must be short to fit on key!
- /* 121 */ "123",
+ /* 123 */ "123",
// Label for "switch to phone symbols" key. Must be short to fit on key!
// U+FF0A: "*" FULLWIDTH ASTERISK
// U+FF03: "#" FULLWIDTH NUMBER SIGN
- /* 122 */ "\uFF0A\uFF03",
+ /* 124 */ "\uFF0A\uFF03",
// Key label for "ante meridiem"
- /* 123 */ "AM",
+ /* 125 */ "AM",
// Key label for "post meridiem"
- /* 124 */ "PM",
+ /* 126 */ "PM",
// Label for "switch to symbols" key on PC QWERTY layout
- /* 125 */ "Sym",
- /* 126 */ ".com",
+ /* 127 */ "Sym",
+ /* 128 */ ".com",
// popular web domains for the locale - most popular, displayed on the keyboard
- /* 127 */ "!hasLabels!,.net,.org,.gov,.edu",
- /* 128 */ "!fixedColumnOrder!5,!hasLabels!,=-O|=-O ,:-P|:-P ,;-)|;-) ,:-(|:-( ,:-)|:-) ,:-!|:-! ,:-$|:-$ ,B-)|B-) ,:O|:O ,:-*|:-* ,:-D|:-D ,:\'(|:\'( ,:-\\\\|:-\\\\ ,O:-)|O:-) ,:-[|:-[ ",
+ /* 129 */ "!hasLabels!,.net,.org,.gov,.edu",
+ /* 130 */ "!fixedColumnOrder!5,!hasLabels!,=-O|=-O ,:-P|:-P ,;-)|;-) ,:-(|:-( ,:-)|:-) ,:-!|:-! ,:-$|:-$ ,B-)|B-) ,:O|:O ,:-*|:-* ,:-D|:-D ,:\'(|:\'( ,:-\\\\|:-\\\\ ,O:-)|O:-) ,:-[|:-[ ",
};
/* Language af: Afrikaans */
@@ -450,17 +456,30 @@ public final class KeyboardTextsSet {
/* 0~ */
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null, null, null,
- /* ~42 */
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0623: "ا" ARABIC LETTER ALEF
+ // U+200C: ZERO WIDTH NON-JOINER
+ // U+0628: "ب" ARABIC LETTER BEH
+ // U+062C: "پ" ARABIC LETTER PEH
+ /* 42 */ "\u0623\u200C\u0628\u200C\u062C",
+ /* 43 */ null,
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// <string name="more_keys_for_double_quote">&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;|&#x00BB;,&#x00BB;|&#x00AB;</string>
- /* 43 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB",
+ /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// <string name="more_keys_for_tablet_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;|&#x00BB;,&#x00BB|&#x00AB;;,&#x2018;,&#x2019;,&#x201A;,&#x201B;</string>
- /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB,\u2018,\u2019,\u201A,\u201B",
- /* 45~ */
- null, null, null, null,
- /* ~48 */
+ /* 45 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB,\u2018,\u2019,\u201A,\u201B",
+ // U+00A2: "¢" CENT SIGN
+ // U+00A3: "£" POUND SIGN
+ // U+20AC: "€" EURO SIGN
+ // U+00A5: "¥" YEN SIGN
+ // U+20B1: "₱" PESO SIGN
+ // U+FDFC: "﷼" RIAL SIGN
+ /* 46 */ "\u00A2,\u00A3,\u20AC,\u00A5,\u20B1,\uFDFC",
+ /* 47 */ null,
+ /* 48 */ null,
// U+061F: "؟" ARABIC QUESTION MARK
// U+060C: "،" ARABIC COMMA
// U+061B: "؛" ARABIC SEMICOLON
@@ -509,7 +528,8 @@ public final class KeyboardTextsSet {
// U+064E: "َ" ARABIC FATHA
// U+0640: "ـ" ARABIC TATWEEL
// In order to make Tatweel easily distinguishable from other punctuations, we use consecutive Tatweels only for its displayed label.
- /* 57 */ "!fixedColumnOrder!7,\u0655,\u0654,\u0652,\u064D,\u064C,\u064B,\u0651,\u0656,\u0670,\u0653,\u0650,\u064F,\u064E,\u0640\u0640\u0640|\u0640",
+ // Note: The space character is needed as a preceding letter to draw Arabic diacritics characters correctly.
+ /* 57 */ "!fixedColumnOrder!7, \u0655|\u0655, \u0654|\u0654, \u0652|\u0652, \u064D|\u064D, \u064C|\u064C, \u064B|\u064B, \u0651|\u0651, \u0656|\u0656, \u0670|\u0670, \u0653|\u0653, \u0650|\u0650, \u064F|\u064F, \u064E|\u064E,\u0640\u0640\u0640|\u0640",
/* 58 */ "\u0651",
// U+0661: "١" ARABIC-INDIC DIGIT ONE
/* 59 */ "\u0661",
@@ -531,42 +551,48 @@ public final class KeyboardTextsSet {
/* 67 */ "\u0669",
// U+0660: "٠" ARABIC-INDIC DIGIT ZERO
/* 68 */ "\u0660",
- /* 69 */ "1",
- /* 70 */ "2",
- /* 71 */ "3",
- /* 72 */ "4",
- /* 73 */ "5",
- /* 74 */ "6",
- /* 75 */ "7",
- /* 76 */ "8",
- /* 77 */ "9",
+ // Label for "switch to symbols" key.
+ // U+061F: "؟" ARABIC QUESTION MARK
+ /* 69 */ "\u0663\u0662\u0661\u061F",
+ // Label for "switch to symbols with microphone" key. This string shouldn't include the "mic"
+ // part because it'll be appended by the code.
+ /* 70 */ "\u0663\u0662\u0661",
+ /* 71 */ "1",
+ /* 72 */ "2",
+ /* 73 */ "3",
+ /* 74 */ "4",
+ /* 75 */ "5",
+ /* 76 */ "6",
+ /* 77 */ "7",
+ /* 78 */ "8",
+ /* 79 */ "9",
// U+066B: "٫" ARABIC DECIMAL SEPARATOR
// U+066C: "٬" ARABIC THOUSANDS SEPARATOR
- /* 78 */ "0,\u066B,\u066C",
- /* 79~ */
+ /* 80 */ "0,\u066B,\u066C",
+ /* 81~ */
null, null, null, null, null, null, null, null, null, null,
- /* ~88 */
+ /* ~90 */
// U+060C: "،" ARABIC COMMA
- /* 89 */ "\u060C",
- /* 90 */ "\\,",
- /* 91 */ "\u061F",
- /* 92 */ "\u061B",
+ /* 91 */ "\u060C",
+ /* 92 */ "\\,",
+ /* 93 */ "\u061F",
+ /* 94 */ "\u061B",
// U+066A: "٪" ARABIC PERCENT SIGN
- /* 93 */ "\u066A",
- /* 94 */ null,
- /* 95 */ "?",
- /* 96 */ ";",
+ /* 95 */ "\u066A",
+ /* 96 */ null,
+ /* 97 */ "?",
+ /* 98 */ ";",
// U+2030: "‰" PER MILLE SIGN
- /* 97 */ "\\%,\u2030",
- /* 98~ */
+ /* 99 */ "\\%,\u2030",
+ /* 100~ */
null, null, null, null, null,
- /* ~102 */
+ /* ~104 */
// U+060C: "،" ARABIC COMMA
// U+061B: "؛" ARABIC SEMICOLON
// U+061F: "؟" ARABIC QUESTION MARK
- /* 103 */ "\u060C",
- /* 104 */ "\u061F",
- /* 105 */ "\u061F,\u061B,!,:,-,/,\',\"",
+ /* 105 */ "\u060C",
+ /* 106 */ "\u061F",
+ /* 107 */ "\u061F,\u061B,!,:,-,/,\',\"",
};
/* Language be: Belarusian */
@@ -595,6 +621,26 @@ public final class KeyboardTextsSet {
/* ~39 */
// U+0451: "ё" CYRILLIC SMALL LETTER IO
/* 40 */ "\u0451",
+ /* 41 */ null,
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
+ };
+
+ /* Language bg: Bulgarian */
+ private static final String[] LANGUAGE_bg = {
+ /* 0~ */
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
};
/* Language ca: Catalan */
@@ -830,6 +876,20 @@ public final class KeyboardTextsSet {
/* 6 */ "\u00F1,\u0144",
};
+ /* Language el: Greek */
+ private static final String[] LANGUAGE_el = {
+ /* 0~ */
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0391: "Α" GREEK CAPITAL LETTER ALPHA
+ // U+0392: "Β" GREEK CAPITAL LETTER BETA
+ // U+0393: "Γ" GREEK CAPITAL LETTER GAMMA
+ /* 42 */ "\u0391\u0392\u0393",
+ };
+
/* Language en: English */
private static final String[] LANGUAGE_en = {
// U+00E0: "à" LATIN SMALL LETTER A WITH GRAVE
@@ -998,20 +1058,20 @@ public final class KeyboardTextsSet {
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null,
- /* ~105 */
- /* 106 */ "q",
- /* 107 */ "x",
+ null, null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~107 */
+ /* 108 */ "q",
+ /* 109 */ "x",
// U+015D: "ŝ" LATIN SMALL LETTER S WITH CIRCUMFLEX
- /* 108 */ "\u015D",
+ /* 110 */ "\u015D",
// U+011D: "ĝ" LATIN SMALL LETTER G WITH CIRCUMFLEX
- /* 109 */ "\u011D",
+ /* 111 */ "\u011D",
// U+016D: "ŭ" LATIN SMALL LETTER U WITH BREVE
- /* 110 */ "\u016D",
+ /* 112 */ "\u016D",
// U+0109: "ĉ" LATIN SMALL LETTER C WITH CIRCUMFLEX
- /* 111 */ "\u0109",
+ /* 113 */ "\u0109",
// U+0135: "ĵ" LATIN SMALL LETTER J WITH CIRCUMFLEX
- /* 112 */ "\u0135",
+ /* 114 */ "\u0135",
};
/* Language es: Spanish */
@@ -1078,13 +1138,16 @@ public final class KeyboardTextsSet {
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null,
- /* ~99 */
+ null, null, null, null, null, null, null,
+ /* ~101 */
// U+00A1: "¡" INVERTED EXCLAMATION MARK
- /* 100 */ "!,\u00A1",
- /* 101 */ null,
+ /* 102 */ "!,\u00A1",
+ /* 103 */ null,
// U+00BF: "¿" INVERTED QUESTION MARK
- /* 102 */ "?,\u00BF",
+ /* 104 */ "?,\u00BF",
+ /* 105 */ "\"",
+ /* 106 */ "\'",
+ /* 107 */ "\'",
};
/* Language et: Estonian */
@@ -1192,17 +1255,31 @@ public final class KeyboardTextsSet {
/* 0~ */
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null, null, null,
- /* ~42 */
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0627: "ا" ARABIC LETTER ALEF
+ // U+200C: ZERO WIDTH NON-JOINER
+ // U+0628: "ب" ARABIC LETTER BEH
+ // U+067E: "پ" ARABIC LETTER PEH
+ /* 42 */ "\u0627\u200C\u0628\u200C\u067E",
+ /* 43 */ null,
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// <string name="more_keys_for_double_quote">&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;|&#x00BB;,&#x00BB;|&#x00AB;</string>
- /* 43 */ "!fixedColumnOrder!4,\u201C,\u201D,\",\'",
+ /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\",\'",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// <string name="more_keys_for_tablet_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;|&#x00BB;,&#x00BB|&#x00AB;;,&#x2018;,&#x2019;,&#x201A;,&#x201B;</string>
- /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB,\u2018,\u2019,\u201A,\u201B",
- /* 45~ */
- null, null, null, null,
- /* ~48 */
+ /* 45 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB,\u2018,\u2019,\u201A,\u201B",
+ /* 46 */ null,
+ // U+FDFC: "﷼" RIAL SIGN
+ // U+060B: "؋" AFGHANI SIGN
+ // U+00A2: "¢" CENT SIGN
+ // U+00A3: "£" POUND SIGN
+ // U+20AC: "€" EURO SIGN
+ // U+00A5: "¥" YEN SIGN
+ // U+20B1: "₱" PESO SIGN
+ /* 47 */ "\uFDFC",
+ /* 48 */ "$,\u00A2,\u20AC,\u00A3,\u00A5,\u20B1,\u060B",
// U+061F: "؟" ARABIC QUESTION MARK
// U+060C: "،" ARABIC COMMA
// U+061B: "؛" ARABIC SEMICOLON
@@ -1251,7 +1328,8 @@ public final class KeyboardTextsSet {
// U+064E: "َ" ARABIC FATHA
// U+0640: "ـ" ARABIC TATWEEL
// In order to make Tatweel easily distinguishable from other punctuations, we use consecutive Tatweels only for its displayed label.
- /* 57 */ "!fixedColumnOrder!7,\u0655,\u0652,\u0651,\u064C,\u064D,\u064B,\u0654,\u0656,\u0670,\u0653,\u064F,\u0650,\u064E,\u0640\u0640\u0640|\u0640",
+ // Note: The space character is needed as a preceding letter to draw Arabic diacritics characters correctly.
+ /* 57 */ "!fixedColumnOrder!7, \u0655|\u0655, \u0652|\u0652, \u0651|\u0651, \u064C|\u064C, \u064D|\u064D, \u064B|\u064B, \u0654|\u0654, \u0656|\u0656, \u0670|\u0670, \u0653|\u0653, \u064F|\u064F, \u0650|\u0650, \u064E|\u064E,\u0640\u0640\u0640|\u0640",
/* 58 */ "\u064B",
// U+06F1: "۱" EXTENDED ARABIC-INDIC DIGIT ONE
/* 59 */ "\u06F1",
@@ -1273,46 +1351,52 @@ public final class KeyboardTextsSet {
/* 67 */ "\u06F9",
// U+06F0: "۰" EXTENDED ARABIC-INDIC DIGIT ZERO
/* 68 */ "\u06F0",
- /* 69 */ "1",
- /* 70 */ "2",
- /* 71 */ "3",
- /* 72 */ "4",
- /* 73 */ "5",
- /* 74 */ "6",
- /* 75 */ "7",
- /* 76 */ "8",
- /* 77 */ "9",
+ // Label for "switch to symbols" key.
+ // U+061F: "؟" ARABIC QUESTION MARK
+ /* 69 */ "\u06F3\u06F2\u06F1\u061F",
+ // Label for "switch to symbols with microphone" key. This string shouldn't include the "mic"
+ // part because it'll be appended by the code.
+ /* 70 */ "\u06F3\u06F2\u06F1",
+ /* 71 */ "1",
+ /* 72 */ "2",
+ /* 73 */ "3",
+ /* 74 */ "4",
+ /* 75 */ "5",
+ /* 76 */ "6",
+ /* 77 */ "7",
+ /* 78 */ "8",
+ /* 79 */ "9",
// U+066B: "٫" ARABIC DECIMAL SEPARATOR
// U+066C: "٬" ARABIC THOUSANDS SEPARATOR
- /* 78 */ "0,\u066B,\u066C",
- /* 79~ */
+ /* 80 */ "0,\u066B,\u066C",
+ /* 81~ */
null, null, null, null, null, null, null, null, null, null,
- /* ~88 */
+ /* ~90 */
// U+060C: "،" ARABIC COMMA
- /* 89 */ "\u060C",
- /* 90 */ "\\,",
- /* 91 */ "\u061F",
- /* 92 */ "\u061B",
+ /* 91 */ "\u060C",
+ /* 92 */ "\\,",
+ /* 93 */ "\u061F",
+ /* 94 */ "\u061B",
// U+066A: "٪" ARABIC PERCENT SIGN
- /* 93 */ "\u066A",
- /* 94 */ null,
- /* 95 */ "?",
- /* 96 */ ";",
+ /* 95 */ "\u066A",
+ /* 96 */ null,
+ /* 97 */ "?",
+ /* 98 */ ";",
// U+2030: "‰" PER MILLE SIGN
- /* 97 */ "\\%,\u2030",
+ /* 99 */ "\\%,\u2030",
// U+060C: "،" ARABIC COMMA
// U+061B: "؛" ARABIC SEMICOLON
// U+061F: "؟" ARABIC QUESTION MARK
// U+00AB: "«" LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
// U+00BB: "»" RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
- /* 98 */ "\u060C",
- /* 99 */ "!",
- /* 100 */ "!,\\,",
- /* 101 */ "\u061F",
- /* 102 */ "\u061F,?",
- /* 103 */ "\u060C",
- /* 104 */ "\u061F",
- /* 105 */ "!fixedColumnOrder!4,:,!,\u061F,\u061B,-,/,\u00AB|\u00BB,\u00BB|\u00AB",
+ /* 100 */ "\u060C",
+ /* 101 */ "!",
+ /* 102 */ "!,\\,",
+ /* 103 */ "\u061F",
+ /* 104 */ "\u061F,?",
+ /* 105 */ "\u060C",
+ /* 106 */ "\u061F",
+ /* 107 */ "!fixedColumnOrder!4,:,!,\u061F,\u061B,-,/,\u00AB|\u00BB,\u00BB|\u00AB",
};
/* Language fi: Finnish */
@@ -1420,8 +1504,20 @@ public final class KeyboardTextsSet {
/* 0~ */
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0915: "क" DEVANAGARI LETTER KA
+ // U+0916: "ख" DEVANAGARI LETTER KHA
+ // U+0917: "ग" DEVANAGARI LETTER GA
+ /* 42 */ "\u0915\u0916\u0917",
+ /* 43~ */
+ null, null, null, null,
+ /* ~46 */
+ // U+20B9: "₹" INDIAN RUPEE SIGN
+ /* 47 */ "\u20B9",
+ /* 48~ */
+ null, null, null, null, null, null, null, null, null, null, null,
/* ~58 */
// U+0967: "१" DEVANAGARI DIGIT ONE
/* 59 */ "\u0967",
@@ -1443,16 +1539,21 @@ public final class KeyboardTextsSet {
/* 67 */ "\u096F",
// U+0966: "०" DEVANAGARI DIGIT ZERO
/* 68 */ "\u0966",
- /* 69 */ "1",
- /* 70 */ "2",
- /* 71 */ "3",
- /* 72 */ "4",
- /* 73 */ "5",
- /* 74 */ "6",
- /* 75 */ "7",
- /* 76 */ "8",
- /* 77 */ "9",
- /* 78 */ "0",
+ // Label for "switch to symbols" key.
+ /* 69 */ "?\u0967\u0968\u0969",
+ // Label for "switch to symbols with microphone" key. This string shouldn't include the "mic"
+ // part because it'll be appended by the code.
+ /* 70 */ "\u0967\u0968\u0969",
+ /* 71 */ "1",
+ /* 72 */ "2",
+ /* 73 */ "3",
+ /* 74 */ "4",
+ /* 75 */ "5",
+ /* 76 */ "6",
+ /* 77 */ "7",
+ /* 78 */ "8",
+ /* 79 */ "9",
+ /* 80 */ "0",
};
/* Language hr: Croatian */
@@ -1640,17 +1741,25 @@ public final class KeyboardTextsSet {
/* 0~ */
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null, null, null, null, null, null, null, null, null, null, null,
- /* ~42 */
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+05D0: "א" HEBREW LETTER ALEF
+ // U+05D1: "ב" HEBREW LETTER BET
+ // U+05D2: "ג" HEBREW LETTER GIMEL
+ /* 42 */ "\u05D0\u05D1\u05D2",
+ /* 43 */ null,
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// <string name="more_keys_for_double_quote">&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;|&#x00BB;,&#x00BB;|&#x00AB;</string>
- /* 43 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB",
+ /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// <string name="more_keys_for_tablet_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;|&#x00BB;,&#x00BB|&#x00AB;;,&#x2018;,&#x2019;,&#x201A;,&#x201B;</string>
- /* 44 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB,\u2018,\u2019,\u201A,\u201B",
- /* 45~ */
- null, null, null, null, null,
- /* ~49 */
+ /* 45 */ "!fixedColumnOrder!4,\u201C,\u201D,\u00AB|\u00BB,\u00BB|\u00AB,\u2018,\u2019,\u201A,\u201B",
+ /* 46 */ null,
+ // U+20AA: "₪" NEW SHEQEL SIGN
+ /* 47 */ "\u20AA",
+ /* 48 */ null,
+ /* 49 */ null,
// U+2605: "★" BLACK STAR
/* 50 */ "\u2605",
/* 51 */ null,
@@ -1680,6 +1789,20 @@ public final class KeyboardTextsSet {
/* 56 */ "!fixedColumnOrder!3,\u203A|\u2039,\u2265|\u2264,\u00BB|\u00AB",
};
+ /* Language ka: Georgian */
+ private static final String[] LANGUAGE_ka = {
+ /* 0~ */
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+10D0: "ა" GEORGIAN LETTER AN
+ // U+10D1: "ბ" GEORGIAN LETTER BAN
+ // U+10D2: "გ" GEORGIAN LETTER GAN
+ /* 42 */ "\u10D0\u10D1\u10D2",
+ };
+
/* Language ky: Kirghiz */
private static final String[] LANGUAGE_ky = {
/* 0~ */
@@ -1711,6 +1834,12 @@ public final class KeyboardTextsSet {
/* ~39 */
// U+0451: "ё" CYRILLIC SMALL LETTER IO
/* 40 */ "\u0451",
+ /* 41 */ null,
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
};
/* Language lt: Lithuanian */
@@ -1911,7 +2040,12 @@ public final class KeyboardTextsSet {
/* 40 */ "\u0450",
// U+045D: "ѝ" CYRILLIC SMALL LETTER I WITH GRAVE
/* 41 */ "\u045D",
- /* 42 */ null,
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
+ /* 43 */ null,
// U+2018: "‘" LEFT SINGLE QUOTATION MARK
// U+2019: "’" RIGHT SINGLE QUOTATION MARK
// U+201A: "‚" SINGLE LOW-9 QUOTATION MARK
@@ -1922,10 +2056,29 @@ public final class KeyboardTextsSet {
// U+201F: "‟" DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK.
// <string name="more_keys_for_double_quote">!fixedColumnOrder!6,&#x201E;,&#x201C;,&#x201D;,&#x201F;,&#x00AB;,&#x00BB;</string>
- /* 43 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB",
+ /* 44 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK.
// <string name="more_keys_for_tablet_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;,&#x00BB;,&#x2018;,&#x2019;,&#x201A;,&#x201B;</string>
- /* 44 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB,\u2018,\u2019,\u201A,\u201B",
+ /* 45 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB,\u2018,\u2019,\u201A,\u201B",
+ };
+
+ /* Language mn: Mongolian */
+ private static final String[] LANGUAGE_mn = {
+ /* 0~ */
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
+ /* 43~ */
+ null, null, null, null,
+ /* ~46 */
+ // U+20AE: "₮" TUGRIK SIGN
+ /* 47 */ "\u20AE",
};
/* Language nb: Norwegian Bokmål */
@@ -2205,6 +2358,12 @@ public final class KeyboardTextsSet {
/* ~39 */
// U+0451: "ё" CYRILLIC SMALL LETTER IO
/* 40 */ "\u0451",
+ /* 41 */ null,
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
};
/* Language sk: Slovak */
@@ -2354,8 +2513,13 @@ public final class KeyboardTextsSet {
/* 40 */ "\u0450",
// U+045D: "ѝ" CYRILLIC SMALL LETTER I WITH GRAVE
/* 41 */ "\u045D",
- /* 42 */ null,
// END: More keys definitions for Serbian (Cyrillic)
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
+ /* 43 */ null,
// U+2018: "‘" LEFT SINGLE QUOTATION MARK
// U+2019: "’" RIGHT SINGLE QUOTATION MARK
// U+201A: "‚" SINGLE LOW-9 QUOTATION MARK
@@ -2366,10 +2530,10 @@ public final class KeyboardTextsSet {
// U+201F: "‟" DOUBLE HIGH-REVERSED-9 QUOTATION MARK
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK.
// <string name="more_keys_for_double_quote">!fixedColumnOrder!6,&#x201E;,&#x201C;,&#x201D;,&#x201F;,&#x00AB;,&#x00BB;</string>
- /* 43 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB",
+ /* 44 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB",
// TODO: Neither DroidSans nor Roboto have the glyph for U+201F DOUBLE HIGH-REVERSED-9 QUOTATION MARK.
// <string name="more_keys_for_tablet_double_quote">!fixedColumnOrder!6,&#x201C;,&#x201D;,&#x201E;,&#x201F;,&#x00AB;,&#x00BB;,&#x2018;,&#x2019;,&#x201A;,&#x201B;</string>
- /* 44 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB,\u2018,\u2019,\u201A,\u201B",
+ /* 45 */ "!fixedColumnOrder!5,\u201E,\u201C,\u201D,\u00AB,\u00BB,\u2018,\u2019,\u201A,\u201B",
};
/* Language sv: Swedish */
@@ -2465,6 +2629,25 @@ public final class KeyboardTextsSet {
/* 15 */ "g\'",
};
+ /* Language th: Thai */
+ private static final String[] LANGUAGE_th = {
+ /* 0~ */
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0E01: "ก" THAI CHARACTER KO KAI
+ // U+0E02: "ข" THAI CHARACTER KHO KHAI
+ // U+0E04: "ค" THAI CHARACTER KHO KHWAI
+ /* 42 */ "\u0E01\u0E02\u0E04",
+ /* 43~ */
+ null, null, null, null,
+ /* ~46 */
+ // U+0E3F: "฿" THAI CURRENCY SYMBOL BAHT
+ /* 47 */ "\u0E3F",
+ };
+
/* Language tl: Tagalog */
private static final String[] LANGUAGE_tl = {
// U+00E1: "á" LATIN SMALL LETTER A WITH ACUTE
@@ -2589,6 +2772,19 @@ public final class KeyboardTextsSet {
/* 34 */ null,
// U+044A: "ъ" CYRILLIC SMALL LETTER HARD SIGN
/* 35 */ "\u044A",
+ /* 36~ */
+ null, null, null, null, null, null,
+ /* ~41 */
+ // Label for "switch to alphabetic" key.
+ // U+0410: "А" CYRILLIC CAPITAL LETTER A
+ // U+0411: "Б" CYRILLIC CAPITAL LETTER BE
+ // U+0412: "В" CYRILLIC CAPITAL LETTER VE
+ /* 42 */ "\u0410\u0411\u0412",
+ /* 43~ */
+ null, null, null, null,
+ /* ~46 */
+ // U+20B4: "₴" HRYVNIA SIGN
+ /* 47 */ "\u20B4",
};
/* Language vi: Vietnamese */
@@ -2670,6 +2866,13 @@ public final class KeyboardTextsSet {
/* 8 */ "\u1EF3,\u00FD,\u1EF7,\u1EF9,\u1EF5",
// U+0111: "đ" LATIN SMALL LETTER D WITH STROKE
/* 9 */ "\u0111",
+ /* 10~ */
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null,
+ /* ~46 */
+ // U+20AB: "₫" DONG SIGN
+ /* 47 */ "\u20AB",
};
/* Language zu: Zulu */
@@ -2847,10 +3050,12 @@ public final class KeyboardTextsSet {
"af", LANGUAGE_af, /* Afrikaans */
"ar", LANGUAGE_ar, /* Arabic */
"be", LANGUAGE_be, /* Belarusian */
+ "bg", LANGUAGE_bg, /* Bulgarian */
"ca", LANGUAGE_ca, /* Catalan */
"cs", LANGUAGE_cs, /* Czech */
"da", LANGUAGE_da, /* Danish */
"de", LANGUAGE_de, /* German */
+ "el", LANGUAGE_el, /* Greek */
"en", LANGUAGE_en, /* English */
"eo", LANGUAGE_eo, /* Esperanto */
"es", LANGUAGE_es, /* Spanish */
@@ -2864,10 +3069,12 @@ public final class KeyboardTextsSet {
"is", LANGUAGE_is, /* Icelandic */
"it", LANGUAGE_it, /* Italian */
"iw", LANGUAGE_iw, /* Hebrew */
+ "ka", LANGUAGE_ka, /* Georgian */
"ky", LANGUAGE_ky, /* Kirghiz */
"lt", LANGUAGE_lt, /* Lithuanian */
"lv", LANGUAGE_lv, /* Latvian */
"mk", LANGUAGE_mk, /* Macedonian */
+ "mn", LANGUAGE_mn, /* Mongolian */
"nb", LANGUAGE_nb, /* Norwegian Bokmål */
"nl", LANGUAGE_nl, /* Dutch */
"pl", LANGUAGE_pl, /* Polish */
@@ -2880,6 +3087,7 @@ public final class KeyboardTextsSet {
"sr", LANGUAGE_sr, /* Serbian */
"sv", LANGUAGE_sv, /* Swedish */
"sw", LANGUAGE_sw, /* Swahili */
+ "th", LANGUAGE_th, /* Thai */
"tl", LANGUAGE_tl, /* Tagalog */
"tr", LANGUAGE_tr, /* Turkish */
"uk", LANGUAGE_uk, /* Ukrainian */
diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeysCache.java b/java/src/com/android/inputmethod/keyboard/internal/KeysCache.java
index d1b4c8524..db154a391 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/KeysCache.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/KeysCache.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/ModifierKeyState.java b/java/src/com/android/inputmethod/keyboard/internal/ModifierKeyState.java
index b39b97720..b254ab8d4 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/ModifierKeyState.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/ModifierKeyState.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java b/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java
index 550391b49..b38d79f7b 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/MoreKeySpec.java
@@ -1,24 +1,24 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
import android.text.TextUtils;
-import com.android.inputmethod.keyboard.Keyboard;
+import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.StringUtils;
import java.util.Locale;
@@ -35,10 +35,10 @@ public final class MoreKeySpec {
KeySpecParser.getLabel(moreKeySpec), needsToUpperCase, locale);
final int code = KeySpecParser.toUpperCaseOfCodeForLocale(
KeySpecParser.getCode(moreKeySpec, codesSet), needsToUpperCase, locale);
- if (code == Keyboard.CODE_UNSPECIFIED) {
+ if (code == Constants.CODE_UNSPECIFIED) {
// Some letter, for example German Eszett (U+00DF: "ß"), has multiple characters
// upper case representation ("SS").
- mCode = Keyboard.CODE_OUTPUT_TEXT;
+ mCode = Constants.CODE_OUTPUT_TEXT;
mOutputText = mLabel;
} else {
mCode = code;
@@ -75,8 +75,8 @@ public final class MoreKeySpec {
public String toString() {
final String label = (mIconId == KeyboardIconsSet.ICON_UNDEFINED ? mLabel
: KeySpecParser.PREFIX_ICON + KeyboardIconsSet.getIconName(mIconId));
- final String output = (mCode == Keyboard.CODE_OUTPUT_TEXT ? mOutputText
- : Keyboard.printableCode(mCode));
+ final String output = (mCode == Constants.CODE_OUTPUT_TEXT ? mOutputText
+ : Constants.printableCode(mCode));
if (StringUtils.codePointCount(label) == 1 && label.codePointAt(0) == mCode) {
return output;
} else {
diff --git a/java/src/com/android/inputmethod/keyboard/internal/PointerTrackerQueue.java b/java/src/com/android/inputmethod/keyboard/internal/PointerTrackerQueue.java
index a52f202aa..2df7e5cf5 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/PointerTrackerQueue.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/PointerTrackerQueue.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -30,6 +30,7 @@ public final class PointerTrackerQueue {
public boolean isModifier();
public boolean isInSlidingKeyInput();
public void onPhantomUpEvent(long eventTime);
+ public void cancelTracking();
}
private static final int INITIAL_CAPACITY = 10;
@@ -182,6 +183,15 @@ public final class PointerTrackerQueue {
return false;
}
+ public synchronized void cancelAllPointerTracker() {
+ final ArrayList<Element> expandableArray = mExpandableArrayOfActivePointers;
+ final int arraySize = mArraySize;
+ for (int index = 0; index < arraySize; index++) {
+ final Element element = expandableArray.get(index);
+ element.cancelTracking();
+ }
+ }
+
@Override
public synchronized String toString() {
final StringBuilder sb = new StringBuilder();
diff --git a/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java b/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java
index 776ac0204..23761103f 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java
@@ -17,332 +17,64 @@
package com.android.inputmethod.keyboard.internal;
import android.content.Context;
-import android.content.res.TypedArray;
-import android.graphics.Bitmap;
import android.graphics.Canvas;
-import android.graphics.Color;
import android.graphics.Paint;
-import android.graphics.Paint.Align;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
-import android.graphics.Rect;
-import android.graphics.RectF;
-import android.os.Message;
-import android.text.TextUtils;
import android.util.AttributeSet;
-import android.util.SparseArray;
import android.widget.RelativeLayout;
-import com.android.inputmethod.keyboard.PointerTracker;
-import com.android.inputmethod.keyboard.internal.GesturePreviewTrail.Params;
import com.android.inputmethod.latin.CollectionUtils;
-import com.android.inputmethod.latin.R;
-import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
+import com.android.inputmethod.latin.CoordinateUtils;
-public final class PreviewPlacerView extends RelativeLayout {
- // The height of extra area above the keyboard to draw gesture trails.
- // Proportional to the keyboard height.
- private static final float EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO = 0.25f;
-
- private final int mGestureFloatingPreviewTextColor;
- private final int mGestureFloatingPreviewTextOffset;
- private final int mGestureFloatingPreviewColor;
- private final float mGestureFloatingPreviewHorizontalPadding;
- private final float mGestureFloatingPreviewVerticalPadding;
- private final float mGestureFloatingPreviewRoundRadius;
-
- private int mKeyboardViewOriginX;
- private int mKeyboardViewOriginY;
-
- private final SparseArray<GesturePreviewTrail> mGesturePreviewTrails =
- CollectionUtils.newSparseArray();
- private final Params mGesturePreviewTrailParams;
- private final Paint mGesturePaint;
- private boolean mDrawsGesturePreviewTrail;
- private int mOffscreenWidth;
- private int mOffscreenHeight;
- private int mOffscreenOffsetY;
- private Bitmap mOffscreenBuffer;
- private final Canvas mOffscreenCanvas = new Canvas();
- private final Rect mOffscreenDirtyRect = new Rect();
- private final Rect mGesturePreviewTrailBoundsRect = new Rect(); // per trail
-
- private final Paint mTextPaint;
- private String mGestureFloatingPreviewText;
- private final int mGestureFloatingPreviewTextHeight;
- // {@link RectF} is needed for {@link Canvas#drawRoundRect(RectF, float, float, Paint)}.
- private final RectF mGestureFloatingPreviewRectangle = new RectF();
- private int mLastPointerX;
- private int mLastPointerY;
- private static final char[] TEXT_HEIGHT_REFERENCE_CHAR = { 'M' };
- private boolean mDrawsGestureFloatingPreviewText;
-
- private final DrawingHandler mDrawingHandler;
-
- private static final class DrawingHandler extends StaticInnerHandlerWrapper<PreviewPlacerView> {
- private static final int MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 0;
- private static final int MSG_UPDATE_GESTURE_PREVIEW_TRAIL = 1;
+import java.util.ArrayList;
- private final Params mGesturePreviewTrailParams;
- private final int mGestureFloatingPreviewTextLingerTimeout;
-
- public DrawingHandler(final PreviewPlacerView outerInstance,
- final Params gesturePreviewTrailParams,
- final int getstureFloatinPreviewTextLinerTimeout) {
- super(outerInstance);
- mGesturePreviewTrailParams = gesturePreviewTrailParams;
- mGestureFloatingPreviewTextLingerTimeout = getstureFloatinPreviewTextLinerTimeout;
- }
-
- @Override
- public void handleMessage(final Message msg) {
- final PreviewPlacerView placerView = getOuterInstance();
- if (placerView == null) return;
- switch (msg.what) {
- case MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT:
- placerView.setGestureFloatingPreviewText(null);
- break;
- case MSG_UPDATE_GESTURE_PREVIEW_TRAIL:
- placerView.invalidate();
- break;
- }
- }
-
- public void dismissGestureFloatingPreviewText() {
- removeMessages(MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT);
- sendMessageDelayed(obtainMessage(MSG_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT),
- mGestureFloatingPreviewTextLingerTimeout);
- }
+public final class PreviewPlacerView extends RelativeLayout {
+ private final int[] mKeyboardViewOrigin = CoordinateUtils.newInstance();
- public void postUpdateGestureTrailPreview() {
- removeMessages(MSG_UPDATE_GESTURE_PREVIEW_TRAIL);
- sendMessageDelayed(obtainMessage(MSG_UPDATE_GESTURE_PREVIEW_TRAIL),
- mGesturePreviewTrailParams.mUpdateInterval);
- }
- }
+ private final ArrayList<AbstractDrawingPreview> mPreviews = CollectionUtils.newArrayList();
public PreviewPlacerView(final Context context, final AttributeSet attrs) {
- this(context, attrs, R.attr.keyboardViewStyle);
- }
-
- public PreviewPlacerView(final Context context, final AttributeSet attrs, final int defStyle) {
- super(context);
+ super(context, attrs);
setWillNotDraw(false);
- final TypedArray keyboardViewAttr = context.obtainStyledAttributes(
- attrs, R.styleable.KeyboardView, defStyle, R.style.KeyboardView);
- final int gestureFloatingPreviewTextSize = keyboardViewAttr.getDimensionPixelSize(
- R.styleable.KeyboardView_gestureFloatingPreviewTextSize, 0);
- mGestureFloatingPreviewTextColor = keyboardViewAttr.getColor(
- R.styleable.KeyboardView_gestureFloatingPreviewTextColor, 0);
- mGestureFloatingPreviewTextOffset = keyboardViewAttr.getDimensionPixelOffset(
- R.styleable.KeyboardView_gestureFloatingPreviewTextOffset, 0);
- mGestureFloatingPreviewColor = keyboardViewAttr.getColor(
- R.styleable.KeyboardView_gestureFloatingPreviewColor, 0);
- mGestureFloatingPreviewHorizontalPadding = keyboardViewAttr.getDimension(
- R.styleable.KeyboardView_gestureFloatingPreviewHorizontalPadding, 0.0f);
- mGestureFloatingPreviewVerticalPadding = keyboardViewAttr.getDimension(
- R.styleable.KeyboardView_gestureFloatingPreviewVerticalPadding, 0.0f);
- mGestureFloatingPreviewRoundRadius = keyboardViewAttr.getDimension(
- R.styleable.KeyboardView_gestureFloatingPreviewRoundRadius, 0.0f);
- final int gestureFloatingPreviewTextLingerTimeout = keyboardViewAttr.getInt(
- R.styleable.KeyboardView_gestureFloatingPreviewTextLingerTimeout, 0);
- mGesturePreviewTrailParams = new Params(keyboardViewAttr);
- keyboardViewAttr.recycle();
-
- mDrawingHandler = new DrawingHandler(this, mGesturePreviewTrailParams,
- gestureFloatingPreviewTextLingerTimeout);
-
- final Paint gesturePaint = new Paint();
- gesturePaint.setAntiAlias(true);
- gesturePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
- mGesturePaint = gesturePaint;
-
- final Paint textPaint = new Paint();
- textPaint.setAntiAlias(true);
- textPaint.setTextAlign(Align.CENTER);
- textPaint.setTextSize(gestureFloatingPreviewTextSize);
- mTextPaint = textPaint;
- final Rect textRect = new Rect();
- textPaint.getTextBounds(TEXT_HEIGHT_REFERENCE_CHAR, 0, 1, textRect);
- mGestureFloatingPreviewTextHeight = textRect.height();
-
final Paint layerPaint = new Paint();
layerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
setLayerType(LAYER_TYPE_HARDWARE, layerPaint);
}
- public void setKeyboardViewGeometry(final int x, final int y, final int w, final int h) {
- mKeyboardViewOriginX = x;
- mKeyboardViewOriginY = y;
- mOffscreenOffsetY = (int)(h * EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
- mOffscreenWidth = w;
- mOffscreenHeight = mOffscreenOffsetY + h;
- }
-
- public void setGesturePreviewMode(final boolean drawsGesturePreviewTrail,
- final boolean drawsGestureFloatingPreviewText) {
- mDrawsGesturePreviewTrail = drawsGesturePreviewTrail;
- mDrawsGestureFloatingPreviewText = drawsGestureFloatingPreviewText;
+ public void addPreview(final AbstractDrawingPreview preview) {
+ mPreviews.add(preview);
}
- public void invalidatePointer(final PointerTracker tracker, final boolean isOldestTracker) {
- final boolean needsToUpdateLastPointer =
- isOldestTracker && mDrawsGestureFloatingPreviewText;
- if (needsToUpdateLastPointer) {
- mLastPointerX = tracker.getLastX();
- mLastPointerY = tracker.getLastY();
- }
-
- if (mDrawsGesturePreviewTrail) {
- GesturePreviewTrail trail;
- synchronized (mGesturePreviewTrails) {
- trail = mGesturePreviewTrails.get(tracker.mPointerId);
- if (trail == null) {
- trail = new GesturePreviewTrail();
- mGesturePreviewTrails.put(tracker.mPointerId, trail);
- }
- }
- trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime());
- }
-
- // TODO: Should narrow the invalidate region.
- if (mDrawsGesturePreviewTrail || needsToUpdateLastPointer) {
- invalidate();
+ public void setKeyboardViewGeometry(final int[] originCoords, final int width,
+ final int height) {
+ CoordinateUtils.copy(mKeyboardViewOrigin, originCoords);
+ final int count = mPreviews.size();
+ for (int i = 0; i < count; i++) {
+ mPreviews.get(i).setKeyboardGeometry(originCoords, width, height);
}
}
@Override
protected void onDetachedFromWindow() {
- freeOffscreenBuffer();
- }
-
- private void freeOffscreenBuffer() {
- if (mOffscreenBuffer != null) {
- mOffscreenBuffer.recycle();
- mOffscreenBuffer = null;
- }
- }
-
- private void mayAllocateOffscreenBuffer() {
- if (mOffscreenBuffer != null && mOffscreenBuffer.getWidth() == mOffscreenWidth
- && mOffscreenBuffer.getHeight() == mOffscreenHeight) {
- return;
+ super.onDetachedFromWindow();
+ final int count = mPreviews.size();
+ for (int i = 0; i < count; i++) {
+ mPreviews.get(i).onDetachFromWindow();
}
- freeOffscreenBuffer();
- mOffscreenBuffer = Bitmap.createBitmap(
- mOffscreenWidth, mOffscreenHeight, Bitmap.Config.ARGB_8888);
- mOffscreenCanvas.setBitmap(mOffscreenBuffer);
}
@Override
public void onDraw(final Canvas canvas) {
super.onDraw(canvas);
- if (mDrawsGesturePreviewTrail) {
- mayAllocateOffscreenBuffer();
- // Draw gesture trails to offscreen buffer.
- final boolean needsUpdatingGesturePreviewTrail = drawGestureTrails(
- mOffscreenCanvas, mGesturePaint, mOffscreenDirtyRect);
- // Transfer offscreen buffer to screen.
- if (!mOffscreenDirtyRect.isEmpty()) {
- final int offsetY = mKeyboardViewOriginY - mOffscreenOffsetY;
- canvas.translate(mKeyboardViewOriginX, offsetY);
- canvas.drawBitmap(mOffscreenBuffer, mOffscreenDirtyRect, mOffscreenDirtyRect,
- mGesturePaint);
- canvas.translate(-mKeyboardViewOriginX, -offsetY);
- // Note: Defer clearing the dirty rectangle here because we will get cleared
- // rectangle on the canvas.
- }
- if (needsUpdatingGesturePreviewTrail) {
- mDrawingHandler.postUpdateGestureTrailPreview();
- }
- }
- if (mDrawsGestureFloatingPreviewText) {
- canvas.translate(mKeyboardViewOriginX, mKeyboardViewOriginY);
- drawGestureFloatingPreviewText(canvas, mGestureFloatingPreviewText);
- canvas.translate(-mKeyboardViewOriginX, -mKeyboardViewOriginY);
- }
- }
-
- private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint,
- final Rect dirtyRect) {
- // Clear previous dirty rectangle.
- if (!dirtyRect.isEmpty()) {
- paint.setColor(Color.TRANSPARENT);
- paint.setStyle(Paint.Style.FILL);
- offscreenCanvas.drawRect(dirtyRect, paint);
- }
- dirtyRect.setEmpty();
-
- // Draw gesture trails to offscreen buffer.
- offscreenCanvas.translate(0, mOffscreenOffsetY);
- boolean needsUpdatingGesturePreviewTrail = false;
- synchronized (mGesturePreviewTrails) {
- // Trails count == fingers count that have ever been active.
- final int trailsCount = mGesturePreviewTrails.size();
- for (int index = 0; index < trailsCount; index++) {
- final GesturePreviewTrail trail = mGesturePreviewTrails.valueAt(index);
- needsUpdatingGesturePreviewTrail |=
- trail.drawGestureTrail(offscreenCanvas, paint,
- mGesturePreviewTrailBoundsRect, mGesturePreviewTrailParams);
- // {@link #mGesturePreviewTrailBoundsRect} has bounding box of the trail.
- dirtyRect.union(mGesturePreviewTrailBoundsRect);
- }
+ final int originX = CoordinateUtils.x(mKeyboardViewOrigin);
+ final int originY = CoordinateUtils.y(mKeyboardViewOrigin);
+ canvas.translate(originX, originY);
+ final int count = mPreviews.size();
+ for (int i = 0; i < count; i++) {
+ mPreviews.get(i).drawPreview(canvas);
}
- offscreenCanvas.translate(0, -mOffscreenOffsetY);
-
- // Clip dirty rectangle with offscreen buffer width/height.
- dirtyRect.offset(0, mOffscreenOffsetY);
- clipRect(dirtyRect, 0, 0, mOffscreenWidth, mOffscreenHeight);
- return needsUpdatingGesturePreviewTrail;
- }
-
- private static void clipRect(final Rect out, final int left, final int top, final int right,
- final int bottom) {
- out.set(Math.max(out.left, left), Math.max(out.top, top), Math.min(out.right, right),
- Math.min(out.bottom, bottom));
- }
-
- public void setGestureFloatingPreviewText(final String gestureFloatingPreviewText) {
- if (!mDrawsGestureFloatingPreviewText) return;
- mGestureFloatingPreviewText = gestureFloatingPreviewText;
- invalidate();
- }
-
- public void dismissGestureFloatingPreviewText() {
- mDrawingHandler.dismissGestureFloatingPreviewText();
- }
-
- private void drawGestureFloatingPreviewText(final Canvas canvas,
- final String gestureFloatingPreviewText) {
- if (TextUtils.isEmpty(gestureFloatingPreviewText)) {
- return;
- }
-
- final Paint paint = mTextPaint;
- final RectF rectangle = mGestureFloatingPreviewRectangle;
- // TODO: Figure out how we should deal with the floating preview text with multiple moving
- // fingers.
-
- // Paint the round rectangle background.
- final int textHeight = mGestureFloatingPreviewTextHeight;
- final float textWidth = paint.measureText(gestureFloatingPreviewText);
- final float hPad = mGestureFloatingPreviewHorizontalPadding;
- final float vPad = mGestureFloatingPreviewVerticalPadding;
- final float rectWidth = textWidth + hPad * 2.0f;
- final float rectHeight = textHeight + vPad * 2.0f;
- final int canvasWidth = canvas.getWidth();
- final float rectX = Math.min(Math.max(mLastPointerX - rectWidth / 2.0f, 0.0f),
- canvasWidth - rectWidth);
- final float rectY = mLastPointerY - mGestureFloatingPreviewTextOffset - rectHeight;
- rectangle.set(rectX, rectY, rectX + rectWidth, rectY + rectHeight);
- final float round = mGestureFloatingPreviewRoundRadius;
- paint.setColor(mGestureFloatingPreviewColor);
- canvas.drawRoundRect(rectangle, round, round, paint);
- // Paint the text preview
- paint.setColor(mGestureFloatingPreviewTextColor);
- final float textX = rectX + hPad + textWidth / 2.0f;
- final float textY = rectY + vPad + textHeight;
- canvas.drawText(gestureFloatingPreviewText, textX, textY, paint);
+ canvas.translate(-originX, -originY);
}
}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/RoundedLine.java b/java/src/com/android/inputmethod/keyboard/internal/RoundedLine.java
new file mode 100644
index 000000000..2eefd6ae9
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/internal/RoundedLine.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2012 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.internal;
+
+import android.graphics.Path;
+import android.graphics.Rect;
+import android.graphics.RectF;
+
+public final class RoundedLine {
+ private final RectF mArc1 = new RectF();
+ private final RectF mArc2 = new RectF();
+ private final Path mPath = new Path();
+
+ private static final double RADIAN_TO_DEGREE = 180.0d / Math.PI;
+ private static final double RIGHT_ANGLE = Math.PI / 2.0d;
+
+ /**
+ * Make a rounded line path
+ *
+ * @param p1x the x-coordinate of the start point.
+ * @param p1y the y-coordinate of the start point.
+ * @param r1 the radius at the start point
+ * @param p2x the x-coordinate of the end point.
+ * @param p2y the y-coordinate of the end point.
+ * @param r2 the radius at the end point
+ * @return the path of rounded line
+ */
+ public Path makePath(final float p1x, final float p1y, final float r1,
+ final float p2x, final float p2y, final float r2) {
+ final double dx = p2x - p1x;
+ final double dy = p2y - p1y;
+ // Distance of the points.
+ final double l = Math.hypot(dx, dy);
+ if (Double.compare(0.0d, l) == 0) {
+ return null;
+ }
+ // Angle of the line p1-p2
+ final double a = Math.atan2(dy, dx);
+ // Difference of trail cap radius.
+ final double dr = r2 - r1;
+ // Variation of angle at trail cap.
+ final double ar = Math.asin(dr / l);
+ // The start angle of trail cap arc at P1.
+ final double aa = a - (RIGHT_ANGLE + ar);
+ // The end angle of trail cap arc at P2.
+ final double ab = a + (RIGHT_ANGLE + ar);
+ final float cosa = (float)Math.cos(aa);
+ final float sina = (float)Math.sin(aa);
+ final float cosb = (float)Math.cos(ab);
+ final float sinb = (float)Math.sin(ab);
+ // Closing point of arc at P1.
+ final float p1ax = p1x + r1 * cosa;
+ final float p1ay = p1y + r1 * sina;
+ // Opening point of arc at P1.
+ final float p1bx = p1x + r1 * cosb;
+ final float p1by = p1y + r1 * sinb;
+ // Opening point of arc at P2.
+ final float p2ax = p2x + r2 * cosa;
+ final float p2ay = p2y + r2 * sina;
+ // Closing point of arc at P2.
+ final float p2bx = p2x + r2 * cosb;
+ final float p2by = p2y + r2 * sinb;
+ // Start angle of the trail arcs.
+ final float angle = (float)(aa * RADIAN_TO_DEGREE);
+ final float ar2degree = (float)(ar * 2.0d * RADIAN_TO_DEGREE);
+ // Sweep angle of the trail arc at P1.
+ final float a1 = -180.0f + ar2degree;
+ // Sweep angle of the trail arc at P2.
+ final float a2 = 180.0f + ar2degree;
+ mArc1.set(p1x, p1y, p1x, p1y);
+ mArc1.inset(-r1, -r1);
+ mArc2.set(p2x, p2y, p2x, p2y);
+ mArc2.inset(-r2, -r2);
+
+ mPath.rewind();
+ // Trail cap at P1.
+ mPath.moveTo(p1x, p1y);
+ mPath.arcTo(mArc1, angle, a1);
+ // Trail cap at P2.
+ mPath.moveTo(p2x, p2y);
+ mPath.arcTo(mArc2, angle, a2);
+ // Two trapezoids connecting P1 and P2.
+ mPath.moveTo(p1ax, p1ay);
+ mPath.lineTo(p1x, p1y);
+ mPath.lineTo(p1bx, p1by);
+ mPath.lineTo(p2bx, p2by);
+ mPath.lineTo(p2x, p2y);
+ mPath.lineTo(p2ax, p2ay);
+ mPath.close();
+ return mPath;
+ }
+
+ public void getBounds(final Rect outBounds) {
+ // Reuse mArc1 as working variable
+ mPath.computeBounds(mArc1, true /* unused */);
+ mArc1.roundOut(outBounds);
+ }
+}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/ShiftKeyState.java b/java/src/com/android/inputmethod/keyboard/internal/ShiftKeyState.java
index 90db73dee..a497b2eb3 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/ShiftKeyState.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/ShiftKeyState.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
diff --git a/java/src/com/android/inputmethod/keyboard/internal/SlidingKeyInputPreview.java b/java/src/com/android/inputmethod/keyboard/internal/SlidingKeyInputPreview.java
new file mode 100644
index 000000000..37f4e3582
--- /dev/null
+++ b/java/src/com/android/inputmethod/keyboard/internal/SlidingKeyInputPreview.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2013 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.internal;
+
+import android.content.res.TypedArray;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.view.View;
+
+import com.android.inputmethod.keyboard.PointerTracker;
+import com.android.inputmethod.latin.CoordinateUtils;
+import com.android.inputmethod.latin.R;
+
+/**
+ * Draw rubber band preview graphics during sliding key input.
+ */
+public final class SlidingKeyInputPreview extends AbstractDrawingPreview {
+ private final int mPreviewWidth;
+
+ private boolean mShowSlidingKeyInputPreview;
+ private final int[] mPreviewFrom = CoordinateUtils.newInstance();
+ private final int[] mPreviewTo = CoordinateUtils.newInstance();
+
+ // TODO: Finalize the rubber band preview implementation.
+ private final RoundedLine mRoundedLine = new RoundedLine();
+ private final Paint mPaint = new Paint();
+
+ public SlidingKeyInputPreview(final View drawingView, final TypedArray mainKeyboardViewAttr) {
+ super(drawingView);
+ final int previewColor = mainKeyboardViewAttr.getColor(
+ R.styleable.MainKeyboardView_slidingKeyInputPreviewColor, 0);
+ mPreviewWidth = mainKeyboardViewAttr.getDimensionPixelSize(
+ R.styleable.MainKeyboardView_slidingKeyInputPreviewWidth, 0);
+ mPaint.setColor(previewColor);
+ }
+
+ public void dismissSlidingKeyInputPreview() {
+ mShowSlidingKeyInputPreview = false;
+ getDrawingView().invalidate();
+ }
+
+ /**
+ * Draws the preview
+ * @param canvas The canvas where the preview is drawn.
+ */
+ @Override
+ public void drawPreview(final Canvas canvas) {
+ if (!isPreviewEnabled() || !mShowSlidingKeyInputPreview) {
+ return;
+ }
+
+ // TODO: Finalize the rubber band preview implementation.
+ final int radius = mPreviewWidth / 2;
+ final Path path = mRoundedLine.makePath(
+ CoordinateUtils.x(mPreviewFrom), CoordinateUtils.y(mPreviewFrom), radius,
+ CoordinateUtils.x(mPreviewTo), CoordinateUtils.y(mPreviewTo), radius);
+ canvas.drawPath(path, mPaint);
+ }
+
+ /**
+ * Set the position of the preview.
+ * @param tracker The new location of the preview is based on the points in PointerTracker.
+ */
+ @Override
+ public void setPreviewPosition(final PointerTracker tracker) {
+ if (!tracker.isInSlidingKeyInputFromModifier()) {
+ mShowSlidingKeyInputPreview = false;
+ return;
+ }
+ tracker.getDownCoordinates(mPreviewFrom);
+ tracker.getLastCoordinates(mPreviewTo);
+ mShowSlidingKeyInputPreview = true;
+ getDrawingView().invalidate();
+ }
+}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/TouchPositionCorrection.java b/java/src/com/android/inputmethod/keyboard/internal/TouchPositionCorrection.java
index d8950a713..a75384b78 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/TouchPositionCorrection.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/TouchPositionCorrection.java
@@ -1,21 +1,22 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.internal;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.latin.LatinImeLogger;
public final class TouchPositionCorrection {
@@ -66,7 +67,7 @@ public final class TouchPositionCorrection {
}
}
- // For test only
+ @UsedForTesting
public void setEnabled(final boolean enabled) {
mEnabled = enabled;
}
diff --git a/java/src/com/android/inputmethod/keyboard/internal/SuddenJumpingTouchEventHandler.java b/java/src/com/android/inputmethod/keyboard/internal/TouchScreenRegulator.java
index c53428fe5..ac83ff873 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/SuddenJumpingTouchEventHandler.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/TouchScreenRegulator.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.internal;
@@ -20,7 +20,6 @@ import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.MainKeyboardView;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
@@ -28,8 +27,8 @@ import com.android.inputmethod.latin.ResourceUtils;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.research.ResearchLogger;
-public final class SuddenJumpingTouchEventHandler {
- private static final String TAG = SuddenJumpingTouchEventHandler.class.getSimpleName();
+public final class TouchScreenRegulator {
+ private static final String TAG = TouchScreenRegulator.class.getSimpleName();
private static boolean DEBUG_MODE = LatinImeLogger.sDBG;
public interface ProcessMotionEvent {
@@ -50,17 +49,18 @@ public final class SuddenJumpingTouchEventHandler {
private int mJumpThresholdSquare = Integer.MAX_VALUE;
private int mLastX;
private int mLastY;
+ // One-seventh of the keyboard width seems like a reasonable threshold
+ private static final float JUMP_THRESHOLD_RATIO_TO_KEYBOARD_WIDTH = 1.0f / 7.0f;
- public SuddenJumpingTouchEventHandler(Context context, ProcessMotionEvent view) {
+ public TouchScreenRegulator(final Context context, final ProcessMotionEvent view) {
mView = view;
mNeedsSuddenJumpingHack = Boolean.parseBoolean(ResourceUtils.getDeviceOverrideValue(
- context.getResources(), R.array.sudden_jumping_touch_event_device_list, "false"));
+ context.getResources(), R.array.sudden_jumping_touch_event_device_list));
}
- public void setKeyboard(Keyboard newKeyboard) {
- // One-seventh of the keyboard width seems like a reasonable threshold
- final int jumpThreshold = newKeyboard.mOccupiedWidth / 7;
- mJumpThresholdSquare = jumpThreshold * jumpThreshold;
+ public void setKeyboardGeometry(final int keyboardWidth) {
+ final float jumpThreshold = keyboardWidth * JUMP_THRESHOLD_RATIO_TO_KEYBOARD_WIDTH;
+ mJumpThresholdSquare = (int)(jumpThreshold * jumpThreshold);
}
/**
@@ -74,7 +74,7 @@ public final class SuddenJumpingTouchEventHandler {
* @return true if the event was consumed, so that it doesn't continue to be handled by
* {@link MainKeyboardView}.
*/
- private boolean handleSuddenJumping(MotionEvent me) {
+ private boolean handleSuddenJumping(final MotionEvent me) {
if (!mNeedsSuddenJumpingHack)
return false;
final int action = me.getAction();
@@ -140,7 +140,7 @@ public final class SuddenJumpingTouchEventHandler {
return result;
}
- public boolean onTouchEvent(MotionEvent me) {
+ public boolean onTouchEvent(final MotionEvent me) {
// If there was a sudden jump, return without processing the actual motion event.
if (handleSuddenJumping(me)) {
if (DEBUG_MODE)
diff --git a/java/src/com/android/inputmethod/latin/AdditionalSubtype.java b/java/src/com/android/inputmethod/latin/AdditionalSubtype.java
index 509fc1ba3..99b95ea98 100644
--- a/java/src/com/android/inputmethod/latin/AdditionalSubtype.java
+++ b/java/src/com/android/inputmethod/latin/AdditionalSubtype.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -45,7 +45,7 @@ public final class AdditionalSubtype {
final String keyboardLayoutSetName, final String extraValue) {
final String layoutExtraValue = KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName;
final String layoutDisplayNameExtraValue;
- if (Build.VERSION.SDK_INT >= /* JELLY_BEAN */ 15
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
&& SubtypeLocale.isExceptionalLocale(localeString)) {
final String layoutDisplayName = SubtypeLocale.getKeyboardLayoutSetDisplayName(
keyboardLayoutSetName);
diff --git a/java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java b/java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java
index 939451899..ff5e33949 100644
--- a/java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java
+++ b/java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java
@@ -1,17 +1,17 @@
-/**
+/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -44,12 +44,11 @@ import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
-import com.android.inputmethod.compat.CompatUtils;
-
import java.util.ArrayList;
import java.util.TreeSet;
public final class AdditionalSubtypeSettings extends PreferenceFragment {
+ private RichInputMethodManager mRichImm;
private SharedPreferences mPrefs;
private SubtypeLocaleAdapter mSubtypeLocaleAdapter;
private KeyboardLayoutSetAdapter mKeyboardLayoutSetAdapter;
@@ -63,6 +62,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
private static final String KEY_IS_SUBTYPE_ENABLER_NOTIFICATION_DIALOG_OPEN =
"is_subtype_enabler_notification_dialog_open";
private static final String KEY_SUBTYPE_FOR_SUBTYPE_ENABLER = "subtype_for_subtype_enabler";
+
static final class SubtypeLocaleItem extends Pair<String, String>
implements Comparable<SubtypeLocaleItem> {
public SubtypeLocaleItem(final String localeString, final String displayName) {
@@ -70,7 +70,8 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
}
public SubtypeLocaleItem(final String localeString) {
- this(localeString, SubtypeLocale.getSubtypeLocaleDisplayName(localeString));
+ this(localeString,
+ SubtypeLocale.getSubtypeLocaleDisplayNameInSystemLocale(localeString));
}
@Override
@@ -93,14 +94,15 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final TreeSet<SubtypeLocaleItem> items = CollectionUtils.newTreeSet();
- final InputMethodInfo imi = ImfUtils.getInputMethodInfoOfThisIme(context);
+ final InputMethodInfo imi = RichInputMethodManager.getInstance()
+ .getInputMethodInfoOfThisIme();
final int count = imi.getSubtypeCount();
for (int i = 0; i < count; i++) {
final InputMethodSubtype subtype = imi.getSubtypeAt(i);
if (DEBUG_SUBTYPE_ID) {
android.util.Log.d(TAG, String.format("%-6s 0x%08x %11d %s",
subtype.getLocale(), subtype.hashCode(), subtype.hashCode(),
- SubtypeLocale.getSubtypeDisplayName(subtype, context.getResources())));
+ SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype)));
}
if (subtype.containsExtraValueKey(ASCII_CAPABLE)) {
items.add(createItem(context, subtype.getLocale()));
@@ -202,8 +204,8 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
setDialogTitle(R.string.add_style);
setKey(KEY_NEW_SUBTYPE);
} else {
- final String displayName = SubtypeLocale.getSubtypeDisplayName(
- subtype, getContext().getResources());
+ final String displayName =
+ SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype);
setTitle(displayName);
setDialogTitle(displayName);
setKey(KEY_PREFIX + subtype.getLocale() + "_"
@@ -383,10 +385,11 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ mPrefs = getPreferenceManager().getSharedPreferences();
+ RichInputMethodManager.init(getActivity());
+ mRichImm = RichInputMethodManager.getInstance();
addPreferencesFromResource(R.xml.additional_subtype_settings);
setHasOptionsMenu(true);
-
- mPrefs = getPreferenceManager().getSharedPreferences();
}
@Override
@@ -396,7 +399,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
mKeyboardLayoutSetAdapter = new KeyboardLayoutSetAdapter(context);
final String prefSubtypes =
- SettingsValues.getPrefAdditionalSubtypes(mPrefs, getResources());
+ Settings.readPrefAdditionalSubtypes(mPrefs, getResources());
setPrefSubtypes(prefSubtypes, context);
mIsAddingNewSubtype = (savedInstanceState != null)
@@ -439,7 +442,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
mIsAddingNewSubtype = false;
final PreferenceGroup group = getPreferenceScreen();
group.removePreference(subtypePref);
- ImfUtils.setAdditionalInputMethodSubtypes(getActivity(), getSubtypes());
+ mRichImm.setAdditionalInputMethodSubtypes(getSubtypes());
}
@Override
@@ -449,7 +452,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
return;
}
if (findDuplicatedSubtype(subtype) == null) {
- ImfUtils.setAdditionalInputMethodSubtypes(getActivity(), getSubtypes());
+ mRichImm.setAdditionalInputMethodSubtypes(getSubtypes());
return;
}
@@ -466,7 +469,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
mIsAddingNewSubtype = false;
final InputMethodSubtype subtype = subtypePref.getSubtype();
if (findDuplicatedSubtype(subtype) == null) {
- ImfUtils.setAdditionalInputMethodSubtypes(getActivity(), getSubtypes());
+ mRichImm.setAdditionalInputMethodSubtypes(getSubtypes());
mSubtypePreferenceKeyForSubtypeEnabler = subtypePref.getKey();
mSubtypeEnablerNotificationDialog = createDialog(subtypePref);
mSubtypeEnablerNotificationDialog.show();
@@ -494,15 +497,15 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
final Context context = getActivity();
final Resources res = context.getResources();
final String message = res.getString(R.string.custom_input_style_already_exists,
- SubtypeLocale.getSubtypeDisplayName(subtype, res));
+ SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype));
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
private InputMethodSubtype findDuplicatedSubtype(final InputMethodSubtype subtype) {
final String localeString = subtype.getLocale();
final String keyboardLayoutSetName = SubtypeLocale.getKeyboardLayoutSetName(subtype);
- return ImfUtils.findSubtypeByLocaleAndKeyboardLayoutSet(
- getActivity(), localeString, keyboardLayoutSetName);
+ return mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet(
+ localeString, keyboardLayoutSetName);
}
private AlertDialog createDialog(
@@ -514,8 +517,8 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
.setPositiveButton(R.string.enable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
- final Intent intent = CompatUtils.getInputLanguageSelectionIntent(
- ImfUtils.getInputMethodIdOfThisIme(getActivity()),
+ final Intent intent = IntentUtils.getInputLanguageSelectionIntent(
+ mRichImm.getInputMethodIdOfThisIme(),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
@@ -560,20 +563,14 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment {
@Override
public void onPause() {
super.onPause();
- final String oldSubtypes = SettingsValues.getPrefAdditionalSubtypes(mPrefs, getResources());
+ final String oldSubtypes = Settings.readPrefAdditionalSubtypes(mPrefs, getResources());
final InputMethodSubtype[] subtypes = getSubtypes();
final String prefSubtypes = AdditionalSubtype.createPrefSubtypes(subtypes);
if (prefSubtypes.equals(oldSubtypes)) {
return;
}
-
- final SharedPreferences.Editor editor = mPrefs.edit();
- try {
- editor.putString(Settings.PREF_CUSTOM_INPUT_STYLES, prefSubtypes);
- } finally {
- editor.apply();
- }
- ImfUtils.setAdditionalInputMethodSubtypes(getActivity(), subtypes);
+ Settings.writePrefAdditionalSubtypes(mPrefs, prefSubtypes);
+ mRichImm.setAdditionalInputMethodSubtypes(subtypes);
}
@Override
diff --git a/java/src/com/android/inputmethod/latin/AssetFileAddress.java b/java/src/com/android/inputmethod/latin/AssetFileAddress.java
index 29c733ba6..47c750f54 100644
--- a/java/src/com/android/inputmethod/latin/AssetFileAddress.java
+++ b/java/src/com/android/inputmethod/latin/AssetFileAddress.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -35,11 +35,14 @@ final class AssetFileAddress {
mLength = length;
}
+ public static AssetFileAddress makeFromFile(final File file) {
+ if (!file.isFile()) return null;
+ return new AssetFileAddress(file.getAbsolutePath(), 0L, file.length());
+ }
+
public static AssetFileAddress makeFromFileName(final String filename) {
if (null == filename) return null;
- final File f = new File(filename);
- if (!f.isFile()) return null;
- return new AssetFileAddress(filename, 0l, f.length());
+ return makeFromFile(new File(filename));
}
public static AssetFileAddress makeFromFileNameAndOffset(final String filename,
diff --git a/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java b/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java
index 59ef5e09f..986b1a178 100644
--- a/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java
+++ b/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java
@@ -1,29 +1,27 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.media.AudioManager;
+import android.os.Vibrator;
import android.view.HapticFeedbackConstants;
import android.view.View;
-import com.android.inputmethod.keyboard.Keyboard;
-import com.android.inputmethod.latin.VibratorUtils;
-
/**
* This class gathers audio feedback and haptic feedback functions.
*
@@ -31,58 +29,82 @@ import com.android.inputmethod.latin.VibratorUtils;
* complexity of settings and the like.
*/
public final class AudioAndHapticFeedbackManager {
- final private SettingsValues mSettingsValues;
- final private AudioManager mAudioManager;
- final private VibratorUtils mVibratorUtils;
+ private AudioManager mAudioManager;
+ private Vibrator mVibrator;
+
+ private SettingsValues mSettingsValues;
private boolean mSoundOn;
- public AudioAndHapticFeedbackManager(final LatinIME latinIme,
- final SettingsValues settingsValues) {
- mSettingsValues = settingsValues;
- mVibratorUtils = VibratorUtils.getInstance(latinIme);
- mAudioManager = (AudioManager) latinIme.getSystemService(Context.AUDIO_SERVICE);
- mSoundOn = reevaluateIfSoundIsOn();
+ private static final AudioAndHapticFeedbackManager sInstance =
+ new AudioAndHapticFeedbackManager();
+
+ public static AudioAndHapticFeedbackManager getInstance() {
+ return sInstance;
+ }
+
+ private AudioAndHapticFeedbackManager() {
+ // Intentional empty constructor for singleton.
+ }
+
+ public static void init(final Context context) {
+ sInstance.initInternal(context);
+ }
+
+ private void initInternal(final Context context) {
+ mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
+ mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
}
public void hapticAndAudioFeedback(final int primaryCode,
final View viewToPerformHapticFeedbackOn) {
- vibrate(viewToPerformHapticFeedbackOn);
+ vibrateInternal(viewToPerformHapticFeedbackOn);
playKeyClick(primaryCode);
}
+ public boolean hasVibrator() {
+ return mVibrator != null && mVibrator.hasVibrator();
+ }
+
+ public void vibrate(final long milliseconds) {
+ if (mVibrator == null) {
+ return;
+ }
+ mVibrator.vibrate(milliseconds);
+ }
+
private boolean reevaluateIfSoundIsOn() {
- if (!mSettingsValues.mSoundOn || mAudioManager == null) {
+ if (mSettingsValues == null || !mSettingsValues.mSoundOn || mAudioManager == null) {
return false;
- } else {
- return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
}
+ return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
}
- private void playKeyClick(int primaryCode) {
+ private void playKeyClick(final int primaryCode) {
// if mAudioManager is null, we can't play a sound anyway, so return
- if (mAudioManager == null) return;
+ if (mAudioManager == null) {
+ return;
+ }
if (mSoundOn) {
final int sound;
switch (primaryCode) {
- case Keyboard.CODE_DELETE:
+ case Constants.CODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
- case Keyboard.CODE_ENTER:
+ case Constants.CODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
- case Keyboard.CODE_SPACE:
+ case Constants.CODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
default:
sound = AudioManager.FX_KEYPRESS_STANDARD;
break;
}
- mAudioManager.playSoundEffect(sound, mSettingsValues.mFxVolume);
+ mAudioManager.playSoundEffect(sound, mSettingsValues.mKeypressSoundVolume);
}
}
- // TODO: make this private when LatinIME does not call it any more
- public void vibrate(final View viewToPerformHapticFeedbackOn) {
+ private void vibrateInternal(final View viewToPerformHapticFeedbackOn) {
if (!mSettingsValues.mVibrateOn) {
return;
}
@@ -93,9 +115,14 @@ public final class AudioAndHapticFeedbackManager {
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
- } else if (mVibratorUtils != null) {
- mVibratorUtils.vibrate(mSettingsValues.mKeypressVibrationDuration);
+ return;
}
+ vibrate(mSettingsValues.mKeypressVibrationDuration);
+ }
+
+ public void onSettingsChanged(final SettingsValues settingsValues) {
+ mSettingsValues = settingsValues;
+ mSoundOn = reevaluateIfSoundIsOn();
}
public void onRingerModeChanged() {
diff --git a/java/src/com/android/inputmethod/latin/AutoCorrection.java b/java/src/com/android/inputmethod/latin/AutoCorrection.java
index 84fad158f..fa35922b0 100644
--- a/java/src/com/android/inputmethod/latin/AutoCorrection.java
+++ b/java/src/com/android/inputmethod/latin/AutoCorrection.java
@@ -33,11 +33,11 @@ public final class AutoCorrection {
}
public static boolean isValidWord(final ConcurrentHashMap<String, Dictionary> dictionaries,
- CharSequence word, boolean ignoreCase) {
+ final String word, final boolean ignoreCase) {
if (TextUtils.isEmpty(word)) {
return false;
}
- final CharSequence lowerCasedWord = word.toString().toLowerCase();
+ final String lowerCasedWord = word.toLowerCase();
for (final String key : dictionaries.keySet()) {
final Dictionary dictionary = dictionaries.get(key);
// It's unclear how realistically 'dictionary' can be null, but the monkey is somehow
@@ -57,7 +57,7 @@ public final class AutoCorrection {
}
public static int getMaxFrequency(final ConcurrentHashMap<String, Dictionary> dictionaries,
- CharSequence word) {
+ final String word) {
if (TextUtils.isEmpty(word)) {
return Dictionary.NOT_A_PROBABILITY;
}
@@ -76,12 +76,13 @@ public final class AutoCorrection {
// Returns true if this is in any of the dictionaries.
public static boolean isInTheDictionary(
final ConcurrentHashMap<String, Dictionary> dictionaries,
- final CharSequence word, final boolean ignoreCase) {
+ final String word, final boolean ignoreCase) {
return isValidWord(dictionaries, word, ignoreCase);
}
- public static boolean suggestionExceedsAutoCorrectionThreshold(SuggestedWordInfo suggestion,
- CharSequence consideredWord, float autoCorrectionThreshold) {
+ public static boolean suggestionExceedsAutoCorrectionThreshold(
+ final SuggestedWordInfo suggestion, final String consideredWord,
+ final float autoCorrectionThreshold) {
if (null != suggestion) {
// Shortlist a whitelisted word
if (suggestion.mKind == SuggestedWordInfo.KIND_WHITELIST) return true;
@@ -89,8 +90,7 @@ public final class AutoCorrection {
// TODO: when the normalized score of the first suggestion is nearly equals to
// the normalized score of the second suggestion, behave less aggressive.
final float normalizedScore = BinaryDictionary.calcNormalizedScore(
- consideredWord.toString(), suggestion.mWord.toString(),
- autoCorrectionSuggestionScore);
+ consideredWord, suggestion.mWord, autoCorrectionSuggestionScore);
if (DBG) {
Log.d(TAG, "Normalized " + consideredWord + "," + suggestion + ","
+ autoCorrectionSuggestionScore + ", " + normalizedScore
@@ -100,8 +100,7 @@ public final class AutoCorrection {
if (DBG) {
Log.d(TAG, "Auto corrected by S-threshold.");
}
- return !shouldBlockAutoCorrectionBySafetyNet(consideredWord.toString(),
- suggestion.mWord);
+ return !shouldBlockAutoCorrectionBySafetyNet(consideredWord, suggestion.mWord);
}
}
return false;
@@ -110,7 +109,7 @@ public final class AutoCorrection {
// TODO: Resolve the inconsistencies between the native auto correction algorithms and
// this safety net
public static boolean shouldBlockAutoCorrectionBySafetyNet(final String typedWord,
- final CharSequence suggestion) {
+ final String suggestion) {
// Safety net for auto correction.
// Actually if we hit this safety net, it's a bug.
// If user selected aggressive auto correction mode, there is no need to use the safety
@@ -123,7 +122,7 @@ public final class AutoCorrection {
}
final int maxEditDistanceOfNativeDictionary =
(typedWordLength < 5 ? 2 : typedWordLength / 2) + 1;
- final int distance = BinaryDictionary.editDistance(typedWord, suggestion.toString());
+ final int distance = BinaryDictionary.editDistance(typedWord, suggestion);
if (DBG) {
Log.d(TAG, "Autocorrected edit distance = " + distance
+ ", " + maxEditDistanceOfNativeDictionary);
diff --git a/java/src/com/android/inputmethod/latin/BackupAgent.java b/java/src/com/android/inputmethod/latin/BackupAgent.java
index 0beb088ac..1f044618a 100644
--- a/java/src/com/android/inputmethod/latin/BackupAgent.java
+++ b/java/src/com/android/inputmethod/latin/BackupAgent.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2008 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
- *
+ *
+ * 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.
+ * 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;
@@ -23,7 +23,6 @@ import android.app.backup.SharedPreferencesBackupHelper;
* Backs up the Latin IME shared preferences.
*/
public final class BackupAgent extends BackupAgentHelper {
-
@Override
public void onCreate() {
addHelper("shared_pref", new SharedPreferencesBackupHelper(this,
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
index 7184f1d8a..ab2a12fd0 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java
@@ -1,22 +1,21 @@
/*
* Copyright (C) 2008 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
+ * 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
+ * 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.
+ * 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.text.TextUtils;
import android.util.SparseArray;
@@ -31,32 +30,20 @@ import java.util.Locale;
* Implements a static, compacted, binary dictionary of standard words.
*/
public final class BinaryDictionary extends Dictionary {
-
+ private static final String TAG = BinaryDictionary.class.getSimpleName();
public static final String DICTIONARY_PACK_AUTHORITY =
"com.android.inputmethod.latin.dictionarypack";
- /**
- * 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.
- */
- public static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH;
- public static final int MAX_WORDS = 18;
- public static final int MAX_SPACES = 16;
-
- private static final String TAG = BinaryDictionary.class.getSimpleName();
- private static final int MAX_PREDICTIONS = 60;
- private static final int MAX_RESULTS = Math.max(MAX_PREDICTIONS, MAX_WORDS);
-
- private static final int TYPED_LETTER_MULTIPLIER = 2;
+ // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h
+ private static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH;
+ // Must be equal to MAX_RESULTS in native/jni/src/defines.h
+ private static final int MAX_RESULTS = 18;
private long mNativeDict;
private final Locale mLocale;
private final int[] mInputCodePoints = new int[MAX_WORD_LENGTH];
- // TODO: The below should be int[] mOutputCodePoints
- private final char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_RESULTS];
- private final int[] mSpaceIndices = new int[MAX_SPACES];
+ private final int[] mOutputCodePoints = new int[MAX_WORD_LENGTH * MAX_RESULTS];
+ private final int[] mSpaceIndices = new int[MAX_RESULTS];
private final int[] mOutputScores = new int[MAX_RESULTS];
private final int[] mOutputTypes = new int[MAX_RESULTS];
@@ -67,7 +54,7 @@ public final class BinaryDictionary extends Dictionary {
// TODO: There should be a way to remove used DicTraverseSession objects from
// {@code mDicTraverseSessions}.
- private DicTraverseSession getTraverseSession(int traverseSessionId) {
+ private DicTraverseSession getTraverseSession(final int traverseSessionId) {
synchronized(mDicTraverseSessions) {
DicTraverseSession traverseSession = mDicTraverseSessions.get(traverseSessionId);
if (traverseSession == null) {
@@ -84,16 +71,13 @@ public final class BinaryDictionary extends Dictionary {
/**
* 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 useFullEditDistance whether to use the full edit distance in suggestions
* @param dictType the dictionary type, as a human-readable string
*/
- public BinaryDictionary(final Context context,
- final String filename, final long offset, final long length,
+ public BinaryDictionary(final String filename, final long offset, final long length,
final boolean useFullEditDistance, final Locale locale, final String dictType) {
super(dictType);
mLocale = locale;
@@ -105,41 +89,39 @@ public final class BinaryDictionary extends Dictionary {
JniUtils.loadNativeLibrary();
}
- private native long openNative(String sourceDir, long dictOffset, long dictSize,
- int typedLetterMultiplier, int fullWordMultiplier, int maxWordLength, int maxWords,
- int maxPredictions);
- private native void closeNative(long dict);
- private native int getFrequencyNative(long dict, int[] word);
- private native boolean isValidBigramNative(long dict, int[] word1, int[] word2);
- private native int getSuggestionsNative(long dict, long proximityInfo, long traverseSession,
- int[] xCoordinates, int[] yCoordinates, int[] times, int[] pointerIds,
- int[] inputCodePoints, int codesSize, int commitPoint, boolean isGesture,
- int[] prevWordCodePointArray, boolean useFullEditDistance, char[] outputChars,
- int[] outputScores, int[] outputIndices, int[] outputTypes);
- private static native float calcNormalizedScoreNative(char[] before, char[] after, int score);
- private static native int editDistanceNative(char[] before, char[] after);
+ private static native long openNative(String sourceDir, long dictOffset, long dictSize);
+ private static native void closeNative(long dict);
+ private static native int getFrequencyNative(long dict, int[] word);
+ private static native boolean isValidBigramNative(long dict, int[] word1, int[] word2);
+ private static native int getSuggestionsNative(long dict, long proximityInfo,
+ long traverseSession, int[] xCoordinates, int[] yCoordinates, int[] times,
+ int[] pointerIds, int[] inputCodePoints, int inputSize, int commitPoint,
+ boolean isGesture, int[] prevWordCodePointArray, boolean useFullEditDistance,
+ int[] outputCodePoints, int[] outputScores, int[] outputIndices, int[] outputTypes);
+ private static native float calcNormalizedScoreNative(int[] before, int[] after, int score);
+ private static native int editDistanceNative(int[] before, int[] after);
// TODO: Move native dict into session
- private final void loadDictionary(String path, long startOffset, long length) {
- mNativeDict = openNative(path, startOffset, length, TYPED_LETTER_MULTIPLIER,
- FULL_WORD_SCORE_MULTIPLIER, MAX_WORD_LENGTH, MAX_WORDS, MAX_PREDICTIONS);
+ private final void loadDictionary(final String path, final long startOffset,
+ final long length) {
+ mNativeDict = openNative(path, startOffset, length);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo) {
+ final String prevWord, final ProximityInfo proximityInfo) {
return getSuggestionsWithSessionId(composer, prevWord, proximityInfo, 0);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo, int sessionId) {
+ final String prevWord, final ProximityInfo proximityInfo, int sessionId) {
if (!isValidDictionary()) return null;
Arrays.fill(mInputCodePoints, Constants.NOT_A_CODE);
// TODO: toLowerCase in the native code
final int[] prevWordCodePointArray = (null == prevWord)
- ? null : StringUtils.toCodePointArray(prevWord.toString());
+ ? null : StringUtils.toCodePointArray(prevWord);
final int composerSize = composer.size();
final boolean isGesture = composer.isBatchMode();
@@ -151,67 +133,69 @@ public final class BinaryDictionary extends Dictionary {
}
final InputPointers ips = composer.getInputPointers();
- final int codesSize = isGesture ? ips.getPointerSize() : composerSize;
+ final int inputSize = isGesture ? ips.getPointerSize() : composerSize;
// proximityInfo and/or prevWordForBigrams may not be null.
- final int tmpCount = getSuggestionsNative(mNativeDict,
- proximityInfo.getNativeProximityInfo(), getTraverseSession(sessionId).getSession(),
- ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(),
- mInputCodePoints, codesSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray,
- mUseFullEditDistance, mOutputChars, mOutputScores, mSpaceIndices, mOutputTypes);
- final int count = Math.min(tmpCount, MAX_PREDICTIONS);
-
+ final int count = getSuggestionsNative(mNativeDict, proximityInfo.getNativeProximityInfo(),
+ getTraverseSession(sessionId).getSession(), ips.getXCoordinates(),
+ ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(), mInputCodePoints,
+ inputSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray,
+ mUseFullEditDistance, mOutputCodePoints, mOutputScores, mSpaceIndices,
+ mOutputTypes);
final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList();
for (int j = 0; j < count; ++j) {
if (composerSize > 0 && mOutputScores[j] < 1) break;
final int start = j * MAX_WORD_LENGTH;
int len = 0;
- while (len < MAX_WORD_LENGTH && mOutputChars[start + len] != 0) {
+ while (len < MAX_WORD_LENGTH && mOutputCodePoints[start + len] != 0) {
++len;
}
if (len > 0) {
final int score = SuggestedWordInfo.KIND_WHITELIST == mOutputTypes[j]
? SuggestedWordInfo.MAX_SCORE : mOutputScores[j];
- suggestions.add(new SuggestedWordInfo(
- new String(mOutputChars, start, len), score, mOutputTypes[j], mDictType));
+ suggestions.add(new SuggestedWordInfo(new String(mOutputCodePoints, start, len),
+ score, mOutputTypes[j], mDictType));
}
}
return suggestions;
}
- /* package for test */ boolean isValidDictionary() {
+ public boolean isValidDictionary() {
return mNativeDict != 0;
}
- public static float calcNormalizedScore(String before, String after, int score) {
- return calcNormalizedScoreNative(before.toCharArray(), after.toCharArray(), score);
+ public static float calcNormalizedScore(final String before, final String after,
+ final int score) {
+ return calcNormalizedScoreNative(StringUtils.toCodePointArray(before),
+ StringUtils.toCodePointArray(after), score);
}
- public static int editDistance(String before, String after) {
+ public static int editDistance(final String before, final String after) {
if (before == null || after == null) {
throw new IllegalArgumentException();
}
- return editDistanceNative(before.toCharArray(), after.toCharArray());
+ return editDistanceNative(StringUtils.toCodePointArray(before),
+ StringUtils.toCodePointArray(after));
}
@Override
- public boolean isValidWord(CharSequence word) {
+ public boolean isValidWord(final String word) {
return getFrequency(word) >= 0;
}
@Override
- public int getFrequency(CharSequence word) {
+ public int getFrequency(final String word) {
if (word == null) return -1;
- int[] codePoints = StringUtils.toCodePointArray(word.toString());
+ int[] codePoints = StringUtils.toCodePointArray(word);
return getFrequencyNative(mNativeDict, codePoints);
}
// TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni
// calls when checking for changes in an entire dictionary.
- public boolean isValidBigram(CharSequence word1, CharSequence word2) {
+ public boolean isValidBigram(final String word1, final String word2) {
if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false;
- int[] chars1 = StringUtils.toCodePointArray(word1.toString());
- int[] chars2 = StringUtils.toCodePointArray(word2.toString());
- return isValidBigramNative(mNativeDict, chars1, chars2);
+ final int[] codePoints1 = StringUtils.toCodePointArray(word1);
+ final int[] codePoints2 = StringUtils.toCodePointArray(word2);
+ return isValidBigramNative(mNativeDict, codePoints1, codePoints2);
}
@Override
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
index 9a3f88f52..0d0ce5756 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
@@ -1,36 +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
+ * 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
+ * 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.
+ * 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.ContentProviderClient;
import android.content.ContentResolver;
+import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
+import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
+import com.android.inputmethod.latin.DictionaryInfoUtils.DictionaryInfo;
+
import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
@@ -55,11 +62,24 @@ public final class BinaryDictionaryFileDumper {
private static final String DICTIONARY_PROJECTION[] = { "id" };
- public static final String QUERY_PARAMETER_MAY_PROMPT_USER = "mayPrompt";
- public static final String QUERY_PARAMETER_TRUE = "true";
- public static final String QUERY_PARAMETER_DELETE_RESULT = "result";
- public static final String QUERY_PARAMETER_SUCCESS = "success";
- public static final String QUERY_PARAMETER_FAILURE = "failure";
+ private static final String QUERY_PARAMETER_MAY_PROMPT_USER = "mayPrompt";
+ private static final String QUERY_PARAMETER_TRUE = "true";
+ private static final String QUERY_PARAMETER_DELETE_RESULT = "result";
+ private static final String QUERY_PARAMETER_SUCCESS = "success";
+ private static final String QUERY_PARAMETER_FAILURE = "failure";
+
+ // Using protocol version 2 to communicate with the dictionary pack
+ private static final String QUERY_PARAMETER_PROTOCOL = "protocol";
+ private static final String QUERY_PARAMETER_PROTOCOL_VALUE = "2";
+
+ // The path fragment to append after the client ID for dictionary info requests.
+ private static final String QUERY_PATH_DICT_INFO = "dict";
+ // The path fragment to append after the client ID for dictionary datafile requests.
+ private static final String QUERY_PATH_DATAFILE = "datafile";
+ // The path fragment to append after the client ID for updating the metadata URI.
+ private static final String QUERY_PATH_METADATA = "metadata";
+ private static final String INSERT_METADATA_CLIENT_ID_COLUMN = "clientid";
+ private static final String INSERT_METADATA_METADATA_URI_COLUMN = "uri";
// Prevents this class to be accidentally instantiated.
private BinaryDictionaryFileDumper() {
@@ -78,27 +98,67 @@ public final class BinaryDictionaryFileDumper {
}
/**
+ * Gets the content URI builder for a specified type.
+ *
+ * Supported types include QUERY_PATH_DICT_INFO, which takes the locale as
+ * the extraPath argument, and QUERY_PATH_DATAFILE, which needs a wordlist ID
+ * as the extraPath argument.
+ *
+ * @param clientId the clientId to use
+ * @param contentProviderClient the instance of content provider client
+ * @param queryPathType the path element encoding the type
+ * @param extraPath optional extra argument for this type (typically word list id)
+ * @return a builder that can build the URI for the best supported protocol version
+ * @throws RemoteException if the client can't be contacted
+ */
+ private static Uri.Builder getContentUriBuilderForType(final String clientId,
+ final ContentProviderClient contentProviderClient, final String queryPathType,
+ final String extraPath) throws RemoteException {
+ // Check whether protocol v2 is supported by building a v2 URI and calling getType()
+ // on it. If this returns null, v2 is not supported.
+ final Uri.Builder uriV2Builder = getProviderUriBuilder(clientId);
+ uriV2Builder.appendPath(queryPathType);
+ uriV2Builder.appendPath(extraPath);
+ uriV2Builder.appendQueryParameter(QUERY_PARAMETER_PROTOCOL,
+ QUERY_PARAMETER_PROTOCOL_VALUE);
+ if (null != contentProviderClient.getType(uriV2Builder.build())) return uriV2Builder;
+ // Protocol v2 is not supported, so create and return the protocol v1 uri.
+ return getProviderUriBuilder(extraPath);
+ }
+
+ /**
* Queries a content provider for the list of word lists for a specific locale
* available to copy into Latin IME.
*/
private static List<WordListInfo> getWordListWordListInfos(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
- final ContentResolver resolver = context.getContentResolver();
- final Uri.Builder builder = getProviderUriBuilder(locale.toString());
- if (!hasDefaultWordList) {
- builder.appendQueryParameter(QUERY_PARAMETER_MAY_PROMPT_USER, QUERY_PARAMETER_TRUE);
- }
- final Uri dictionaryPackUri = builder.build();
-
- final Cursor c = resolver.query(dictionaryPackUri, DICTIONARY_PROJECTION, null, null, null);
- if (null == c) return Collections.<WordListInfo>emptyList();
- if (c.getCount() <= 0 || !c.moveToFirst()) {
- c.close();
- return Collections.<WordListInfo>emptyList();
- }
+ final String clientId = context.getString(R.string.dictionary_pack_client_id);
+ final ContentProviderClient client = context.getContentResolver().
+ acquireContentProviderClient(getProviderUriBuilder("").build());
+ if (null == client) return Collections.<WordListInfo>emptyList();
try {
- final List<WordListInfo> list = CollectionUtils.newArrayList();
+ final Uri.Builder builder = getContentUriBuilderForType(clientId, client,
+ QUERY_PATH_DICT_INFO, locale.toString());
+ if (!hasDefaultWordList) {
+ builder.appendQueryParameter(QUERY_PARAMETER_MAY_PROMPT_USER,
+ QUERY_PARAMETER_TRUE);
+ }
+ final Uri queryUri = builder.build();
+ final boolean isProtocolV2 = (QUERY_PARAMETER_PROTOCOL_VALUE.equals(
+ queryUri.getQueryParameter(QUERY_PARAMETER_PROTOCOL)));
+
+ Cursor c = client.query(queryUri, DICTIONARY_PROJECTION, null, null, null);
+ if (isProtocolV2 && null == c) {
+ reinitializeClientRecordInDictionaryContentProvider(context, client, clientId);
+ c = client.query(queryUri, DICTIONARY_PROJECTION, null, null, null);
+ }
+ if (null == c) return Collections.<WordListInfo>emptyList();
+ if (c.getCount() <= 0 || !c.moveToFirst()) {
+ c.close();
+ return Collections.<WordListInfo>emptyList();
+ }
+ final ArrayList<WordListInfo> list = CollectionUtils.newArrayList();
do {
final String wordListId = c.getString(0);
final String wordListLocale = c.getString(1);
@@ -107,11 +167,20 @@ public final class BinaryDictionaryFileDumper {
} while (c.moveToNext());
c.close();
return list;
+ } catch (RemoteException e) {
+ // The documentation is unclear as to in which cases this may happen, but it probably
+ // happens when the content provider got suddenly killed because it crashed or because
+ // the user disabled it through Settings.
+ Log.e(TAG, "RemoteException: communication with the dictionary pack cut", e);
+ return Collections.<WordListInfo>emptyList();
} catch (Exception e) {
- // Just in case we hit a problem in communication with the dictionary pack.
- // We don't want to die.
- Log.e(TAG, "Exception communicating with the dictionary pack : " + e);
+ // A crash here is dangerous because crashing here would brick any encrypted device -
+ // we need the keyboard to be up and working to enter the password, so we don't want
+ // to die no matter what. So let's be as safe as possible.
+ Log.e(TAG, "Unexpected exception communicating with the dictionary pack", e);
return Collections.<WordListInfo>emptyList();
+ } finally {
+ client.release();
}
}
@@ -119,13 +188,18 @@ public final class BinaryDictionaryFileDumper {
/**
* Helper method to encapsulate exception handling.
*/
- private static AssetFileDescriptor openAssetFileDescriptor(final ContentResolver resolver,
- final Uri uri) {
+ private static AssetFileDescriptor openAssetFileDescriptor(
+ final ContentProviderClient providerClient, final Uri uri) {
try {
- return resolver.openAssetFileDescriptor(uri, "r");
+ return providerClient.openAssetFile(uri, "r");
} catch (FileNotFoundException e) {
- // I don't want to log the word list URI here for security concerns
- Log.e(TAG, "Could not find a word list from the dictionary provider.");
+ // I don't want to log the word list URI here for security concerns. The exception
+ // contains the name of the file, so let's not pass it to Log.e here.
+ Log.e(TAG, "Could not find a word list from the dictionary provider."
+ /* intentionally don't pass the exception (see comment above) */);
+ return null;
+ } catch (RemoteException e) {
+ Log.e(TAG, "Can't communicate with the dictionary pack", e);
return null;
}
}
@@ -135,9 +209,8 @@ public final class BinaryDictionaryFileDumper {
* to the cache file name designated by its id and locale, overwriting it if already present
* and creating it (and its containing directory) if necessary.
*/
- private static AssetFileAddress cacheWordList(final String id, final String locale,
- final ContentResolver resolver, final Context context) {
-
+ private static AssetFileAddress cacheWordList(final String wordlistId, final String locale,
+ final ContentProviderClient providerClient, final Context context) {
final int COMPRESSED_CRYPTED_COMPRESSED = 0;
final int CRYPTED_COMPRESSED = 1;
final int COMPRESSED_CRYPTED = 2;
@@ -147,23 +220,38 @@ public final class BinaryDictionaryFileDumper {
final int MODE_MIN = COMPRESSED_CRYPTED_COMPRESSED;
final int MODE_MAX = NONE;
- final Uri.Builder wordListUriBuilder = getProviderUriBuilder(id);
- final String finalFileName = BinaryDictionaryGetter.getCacheFileName(id, locale, context);
- final String tempFileName = BinaryDictionaryGetter.getTempFileName(id, context);
+ final String clientId = context.getString(R.string.dictionary_pack_client_id);
+ final Uri.Builder wordListUriBuilder;
+ try {
+ wordListUriBuilder = getContentUriBuilderForType(clientId,
+ providerClient, QUERY_PATH_DATAFILE, wordlistId /* extraPath */);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Can't communicate with the dictionary pack", e);
+ return null;
+ }
+ final String finalFileName =
+ DictionaryInfoUtils.getCacheFileName(wordlistId, locale, context);
+ String tempFileName;
+ try {
+ tempFileName = BinaryDictionaryGetter.getTempFileName(wordlistId, context);
+ } catch (IOException e) {
+ Log.e(TAG, "Can't open the temporary file", e);
+ return null;
+ }
for (int mode = MODE_MIN; mode <= MODE_MAX; ++mode) {
InputStream originalSourceStream = null;
InputStream inputStream = null;
InputStream uncompressedStream = null;
InputStream decryptedStream = null;
- BufferedInputStream bufferedStream = null;
+ BufferedInputStream bufferedInputStream = null;
File outputFile = null;
- FileOutputStream outputStream = null;
+ BufferedOutputStream bufferedOutputStream = null;
AssetFileDescriptor afd = null;
final Uri wordListUri = wordListUriBuilder.build();
try {
// Open input.
- afd = openAssetFileDescriptor(resolver, wordListUri);
+ afd = openAssetFileDescriptor(providerClient, wordListUri);
// If we can't open it at all, don't even try a number of times.
if (null == afd) return null;
originalSourceStream = afd.createInputStream();
@@ -172,7 +260,6 @@ public final class BinaryDictionaryFileDumper {
// Just to be sure, delete the file. This may fail silently, and return false: this
// is the right thing to do, as we just want to continue anyway.
outputFile.delete();
- outputStream = new FileOutputStream(outputFile);
// Get the appropriate decryption method for this try
switch (mode) {
case COMPRESSED_CRYPTED_COMPRESSED:
@@ -200,10 +287,11 @@ public final class BinaryDictionaryFileDumper {
inputStream = originalSourceStream;
break;
}
- bufferedStream = new BufferedInputStream(inputStream);
- checkMagicAndCopyFileTo(bufferedStream, outputStream);
- outputStream.flush();
- outputStream.close();
+ bufferedInputStream = new BufferedInputStream(inputStream);
+ bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
+ checkMagicAndCopyFileTo(bufferedInputStream, bufferedOutputStream);
+ bufferedOutputStream.flush();
+ bufferedOutputStream.close();
final File finalFile = new File(finalFileName);
finalFile.delete();
if (!outputFile.renameTo(finalFile)) {
@@ -211,15 +299,15 @@ public final class BinaryDictionaryFileDumper {
}
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_SUCCESS);
- if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
+ if (0 >= providerClient.delete(wordListUriBuilder.build(), null, null)) {
Log.e(TAG, "Could not have the dictionary pack delete a word list");
}
- BinaryDictionaryGetter.removeFilesWithIdExcept(context, id, finalFile);
+ BinaryDictionaryGetter.removeFilesWithIdExcept(context, wordlistId, finalFile);
// Success! Close files (through the finally{} clause) and return.
return AssetFileAddress.makeFromFileName(finalFileName);
} catch (Exception e) {
if (DEBUG) {
- Log.i(TAG, "Can't open word list in mode " + mode + " : " + e);
+ Log.i(TAG, "Can't open word list in mode " + mode, e);
}
if (null != outputFile) {
// This may or may not fail. The file may not have been created if the
@@ -235,14 +323,14 @@ public final class BinaryDictionaryFileDumper {
if (null != inputStream) inputStream.close();
if (null != uncompressedStream) uncompressedStream.close();
if (null != decryptedStream) decryptedStream.close();
- if (null != bufferedStream) bufferedStream.close();
+ if (null != bufferedInputStream) bufferedInputStream.close();
} catch (Exception e) {
- Log.e(TAG, "Exception while closing a file descriptor : " + e);
+ Log.e(TAG, "Exception while closing a file descriptor", e);
}
try {
- if (null != outputStream) outputStream.close();
+ if (null != bufferedOutputStream) bufferedOutputStream.close();
} catch (Exception e) {
- Log.e(TAG, "Exception while closing a file : " + e);
+ Log.e(TAG, "Exception while closing a file", e);
}
}
}
@@ -254,8 +342,12 @@ public final class BinaryDictionaryFileDumper {
// as invalid.
wordListUriBuilder.appendQueryParameter(QUERY_PARAMETER_DELETE_RESULT,
QUERY_PARAMETER_FAILURE);
- if (0 >= resolver.delete(wordListUriBuilder.build(), null, null)) {
- Log.e(TAG, "In addition, we were unable to delete it.");
+ try {
+ if (0 >= providerClient.delete(wordListUriBuilder.build(), null, null)) {
+ Log.e(TAG, "In addition, we were unable to delete it.");
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "In addition, communication with the dictionary provider was cut", e);
}
return null;
}
@@ -272,17 +364,27 @@ public final class BinaryDictionaryFileDumper {
*/
public static List<AssetFileAddress> cacheWordListsFromContentProvider(final Locale locale,
final Context context, final boolean hasDefaultWordList) {
- final ContentResolver resolver = context.getContentResolver();
- final List<WordListInfo> idList = getWordListWordListInfos(locale, context,
- hasDefaultWordList);
- final List<AssetFileAddress> fileAddressList = CollectionUtils.newArrayList();
- for (WordListInfo id : idList) {
- final AssetFileAddress afd = cacheWordList(id.mId, id.mLocale, resolver, context);
- if (null != afd) {
- fileAddressList.add(afd);
+ final ContentProviderClient providerClient = context.getContentResolver().
+ acquireContentProviderClient(getProviderUriBuilder("").build());
+ if (null == providerClient) {
+ Log.e(TAG, "Can't establish communication with the dictionary provider");
+ return CollectionUtils.newArrayList();
+ }
+ try {
+ final List<WordListInfo> idList = getWordListWordListInfos(locale, context,
+ hasDefaultWordList);
+ final ArrayList<AssetFileAddress> fileAddressList = CollectionUtils.newArrayList();
+ for (WordListInfo id : idList) {
+ final AssetFileAddress afd =
+ cacheWordList(id.mId, id.mLocale, providerClient, context);
+ if (null != afd) {
+ fileAddressList.add(afd);
+ }
}
+ return fileAddressList;
+ } finally {
+ providerClient.release();
}
- return fileAddressList;
}
/**
@@ -295,9 +397,8 @@ public final class BinaryDictionaryFileDumper {
* @param input the stream to be copied.
* @param output an output stream to copy the data to.
*/
- // TODO: make output a BufferedOutputStream
- private static void checkMagicAndCopyFileTo(final BufferedInputStream input,
- final FileOutputStream output) throws FileNotFoundException, IOException {
+ public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
+ final BufferedOutputStream output) throws FileNotFoundException, IOException {
// Check the magic number
final int length = MAGIC_NUMBER_VERSION_2.length;
final byte[] magicNumberBuffer = new byte[length];
@@ -318,4 +419,35 @@ public final class BinaryDictionaryFileDumper {
output.write(buffer, 0, readBytes);
input.close();
}
+
+ private static void reinitializeClientRecordInDictionaryContentProvider(final Context context,
+ final ContentProviderClient client, final String clientId) throws RemoteException {
+ final String metadataFileUri = context.getString(R.string.dictionary_pack_metadata_uri);
+ if (TextUtils.isEmpty(metadataFileUri)) return;
+ // Tell the content provider to reset all information about this client id
+ final Uri metadataContentUri = getProviderUriBuilder(clientId)
+ .appendPath(QUERY_PATH_METADATA)
+ .appendQueryParameter(QUERY_PARAMETER_PROTOCOL, QUERY_PARAMETER_PROTOCOL_VALUE)
+ .build();
+ client.delete(metadataContentUri, null, null);
+ // Update the metadata URI
+ final ContentValues metadataValues = new ContentValues();
+ metadataValues.put(INSERT_METADATA_CLIENT_ID_COLUMN, clientId);
+ metadataValues.put(INSERT_METADATA_METADATA_URI_COLUMN, metadataFileUri);
+ client.insert(metadataContentUri, metadataValues);
+
+ // Update the dictionary list.
+ final Uri dictionaryContentUriBase = getProviderUriBuilder(clientId)
+ .appendPath(QUERY_PATH_DICT_INFO)
+ .appendQueryParameter(QUERY_PARAMETER_PROTOCOL, QUERY_PARAMETER_PROTOCOL_VALUE)
+ .build();
+ final ArrayList<DictionaryInfo> dictionaryList =
+ DictionaryInfoUtils.getCurrentDictionaryFileNameAndVersionInfo(context);
+ final int length = dictionaryList.size();
+ for (int i = 0; i < length; ++i) {
+ final DictionaryInfo info = dictionaryList.get(i);
+ client.insert(Uri.withAppendedPath(dictionaryContentUriBase, info.mId),
+ info.toContentValues());
+ }
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
index c747dc673..e913f2852 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
@@ -1,21 +1,22 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.latin.define.ProductionFlag;
import com.android.inputmethod.latin.makedict.BinaryDictInputOutput;
import com.android.inputmethod.latin.makedict.FormatSpec;
@@ -55,7 +56,7 @@ final class BinaryDictionaryGetter {
private static final String COMMON_PREFERENCES_NAME = "LatinImeDictPrefs";
// Name of the category for the main dictionary
- private static final String MAIN_DICTIONARY_CATEGORY = "main";
+ public static final String MAIN_DICTIONARY_CATEGORY = "main";
public static final String ID_CATEGORY_SEPARATOR = ":";
// The key considered to read the version attribute in a dictionary file.
@@ -65,120 +66,21 @@ final class BinaryDictionaryGetter {
private BinaryDictionaryGetter() {}
/**
- * Returns whether we may want to use this character as part of a file name.
- *
- * This basically only accepts ascii letters and numbers, and rejects everything else.
- */
- private static boolean isFileNameCharacter(int codePoint) {
- if (codePoint >= 0x30 && codePoint <= 0x39) return true; // Digit
- if (codePoint >= 0x41 && codePoint <= 0x5A) return true; // Uppercase
- if (codePoint >= 0x61 && codePoint <= 0x7A) return true; // Lowercase
- return codePoint == '_'; // Underscore
- }
-
- /**
- * Escapes a string for any characters that may be suspicious for a file or directory name.
- *
- * Concretely this does a sort of URL-encoding except it will encode everything that's not
- * alphanumeric or underscore. (true URL-encoding leaves alone characters like '*', which
- * we cannot allow here)
- */
- // TODO: create a unit test for this method
- private static String replaceFileNameDangerousCharacters(final String name) {
- // This assumes '%' is fully available as a non-separator, normal
- // character in a file name. This is probably true for all file systems.
- final StringBuilder sb = new StringBuilder();
- final int nameLength = name.length();
- for (int i = 0; i < nameLength; i = name.offsetByCodePoints(i, 1)) {
- final int codePoint = name.codePointAt(i);
- if (isFileNameCharacter(codePoint)) {
- sb.appendCodePoint(codePoint);
- } else {
- // 6 digits - unicode is limited to 21 bits
- sb.append(String.format((Locale)null, "%%%1$06x", codePoint));
- }
- }
- return sb.toString();
- }
-
- /**
- * Reverse escaping done by replaceFileNameDangerousCharacters.
- */
- private static String getWordListIdFromFileName(final String fname) {
- final StringBuilder sb = new StringBuilder();
- final int fnameLength = fname.length();
- for (int i = 0; i < fnameLength; i = fname.offsetByCodePoints(i, 1)) {
- final int codePoint = fname.codePointAt(i);
- if ('%' != codePoint) {
- sb.appendCodePoint(codePoint);
- } else {
- final int encodedCodePoint = Integer.parseInt(fname.substring(i + 1, i + 7), 16);
- i += 6;
- sb.appendCodePoint(encodedCodePoint);
- }
- }
- return sb.toString();
- }
-
- /**
- * Helper method to get the top level cache directory.
- */
- private static String getWordListCacheDirectory(final Context context) {
- return context.getFilesDir() + File.separator + "dicts";
- }
-
- /**
- * Find out the cache directory associated with a specific locale.
- */
- private static String getCacheDirectoryForLocale(final String locale, final Context context) {
- final String relativeDirectoryName = replaceFileNameDangerousCharacters(locale);
- final String absoluteDirectoryName = getWordListCacheDirectory(context) + File.separator
- + relativeDirectoryName;
- final File directory = new File(absoluteDirectoryName);
- if (!directory.exists()) {
- if (!directory.mkdirs()) {
- Log.e(TAG, "Could not create the directory for locale" + locale);
- }
- }
- return absoluteDirectoryName;
- }
-
- /**
- * Generates a file name for the id and locale passed as an argument.
- *
- * In the current implementation the file name returned will always be unique for
- * any id/locale pair, but please do not expect that the id can be the same for
- * different dictionaries with different locales. An id should be unique for any
- * dictionary.
- * The file name is pretty much an URL-encoded version of the id inside a directory
- * named like the locale, except it will also escape characters that look dangerous
- * to some file systems.
- * @param id the id of the dictionary for which to get a file name
- * @param locale the locale for which to get the file name as a string
- * @param context the context to use for getting the directory
- * @return the name of the file to be created
- */
- public static String getCacheFileName(String id, String locale, Context context) {
- final String fileName = replaceFileNameDangerousCharacters(id);
- return getCacheDirectoryForLocale(locale, context) + File.separator + fileName;
- }
-
- /**
* Generates a unique temporary file name in the app cache directory.
- *
- * This is unique as long as it doesn't get called twice in the same millisecond by the same
- * thread, which should be more than enough for our purposes.
*/
- public static String getTempFileName(String id, Context context) {
- final String fileName = replaceFileNameDangerousCharacters(id);
- return context.getCacheDir() + File.separator + fileName + "."
- + Thread.currentThread().getId() + "." + System.currentTimeMillis();
+ public static String getTempFileName(final String id, final Context context)
+ throws IOException {
+ final String safeId = DictionaryInfoUtils.replaceFileNameDangerousCharacters(id);
+ // If the first argument is less than three chars, createTempFile throws a
+ // RuntimeException. We don't really care about what name we get, so just
+ // put a three-chars prefix makes us safe.
+ return File.createTempFile("xxx" + safeId, null).getAbsolutePath();
}
/**
* Returns a file address from a resource, or null if it cannot be opened.
*/
- private static AssetFileAddress loadFallbackResource(final Context context,
+ public static AssetFileAddress loadFallbackResource(final Context context,
final int fallbackResId) {
final AssetFileDescriptor afd = context.getResources().openRawResourceFd(fallbackResId);
if (afd == null) {
@@ -226,27 +128,6 @@ final class BinaryDictionaryGetter {
}
/**
- * Helper method to the list of cache directories, one for each distinct locale.
- */
- private static File[] getCachedDirectoryList(final Context context) {
- return new File(getWordListCacheDirectory(context)).listFiles();
- }
-
- /**
- * Returns the category for a given file name.
- *
- * This parses the file name, extracts the category, and returns it. See
- * {@link #getMainDictId(Locale)} and {@link #isMainWordListId(String)}.
- * @return The category as a string or null if it can't be found in the file name.
- */
- private static String getCategoryFromFileName(final String fileName) {
- final String id = getWordListIdFromFileName(fileName);
- final String[] idArray = id.split(ID_CATEGORY_SEPARATOR);
- if (2 != idArray.length) return null;
- return idArray[0];
- }
-
- /**
* Utility class for the {@link #getCachedWordLists} method
*/
private static final class FileAndMatchLevel {
@@ -272,20 +153,21 @@ final class BinaryDictionaryGetter {
* @param context the context on which to open the files upon.
* @return an array of binary dictionary files, which may be empty but may not be null.
*/
- private static File[] getCachedWordLists(final String locale,
- final Context context) {
- final File[] directoryList = getCachedDirectoryList(context);
+ public static File[] getCachedWordLists(final String locale, final Context context) {
+ final File[] directoryList = DictionaryInfoUtils.getCachedDirectoryList(context);
if (null == directoryList) return EMPTY_FILE_ARRAY;
final HashMap<String, FileAndMatchLevel> cacheFiles = CollectionUtils.newHashMap();
for (File directory : directoryList) {
if (!directory.isDirectory()) continue;
- final String dirLocale = getWordListIdFromFileName(directory.getName());
+ final String dirLocale =
+ DictionaryInfoUtils.getWordListIdFromFileName(directory.getName());
final int matchLevel = LocaleUtils.getMatchLevel(dirLocale, locale);
if (LocaleUtils.isMatch(matchLevel)) {
final File[] wordLists = directory.listFiles();
if (null != wordLists) {
for (File wordList : wordLists) {
- final String category = getCategoryFromFileName(wordList.getName());
+ final String category =
+ DictionaryInfoUtils.getCategoryFromFileName(wordList.getName());
final FileAndMatchLevel currentBestMatch = cacheFiles.get(category);
if (null == currentBestMatch || currentBestMatch.mMatchLevel < matchLevel) {
cacheFiles.put(category, new FileAndMatchLevel(wordList, matchLevel));
@@ -314,7 +196,7 @@ final class BinaryDictionaryGetter {
final File fileToKeep) {
try {
final File canonicalFileToKeep = fileToKeep.getCanonicalFile();
- final File[] directoryList = getCachedDirectoryList(context);
+ final File[] directoryList = DictionaryInfoUtils.getCachedDirectoryList(context);
if (null == directoryList) return;
for (File directory : directoryList) {
// There is one directory per locale. See #getCachedDirectoryList
@@ -322,7 +204,8 @@ final class BinaryDictionaryGetter {
final File[] wordLists = directory.listFiles();
if (null == wordLists) continue;
for (File wordList : wordLists) {
- final String fileId = getWordListIdFromFileName(wordList.getName());
+ final String fileId =
+ DictionaryInfoUtils.getWordListIdFromFileName(wordList.getName());
if (fileId.equals(id)) {
if (!canonicalFileToKeep.equals(wordList.getCanonicalFile())) {
wordList.delete();
@@ -331,32 +214,10 @@ final class BinaryDictionaryGetter {
}
}
} catch (java.io.IOException e) {
- Log.e(TAG, "IOException trying to cleanup files : " + e);
+ Log.e(TAG, "IOException trying to cleanup files", e);
}
}
-
- /**
- * Returns the id associated with the main word list for a specified locale.
- *
- * Word lists stored in Android Keyboard's resources are referred to as the "main"
- * word lists. Since they can be updated like any other list, we need to assign a
- * unique ID to them. This ID is just the name of the language (locale-wise) they
- * are for, and this method returns this ID.
- */
- private static String getMainDictId(final Locale locale) {
- // This works because we don't include by default different dictionaries for
- // different countries. This actually needs to return the id that we would
- // like to use for word lists included in resources, and the following is okay.
- return MAIN_DICTIONARY_CATEGORY + ID_CATEGORY_SEPARATOR + locale.getLanguage().toString();
- }
-
- private static boolean isMainWordListId(final String id) {
- final String[] idArray = id.split(ID_CATEGORY_SEPARATOR);
- if (2 != idArray.length) return false;
- return MAIN_DICTIONARY_CATEGORY.equals(idArray[0]);
- }
-
// ## HACK ## we prevent usage of a dictionary before version 18 for English only. The reason
// for this is, since those do not include whitelist entries, the new code with an old version
// of the dictionary would lose whitelist functionality.
@@ -427,19 +288,22 @@ final class BinaryDictionaryGetter {
// cacheWordListsFromContentProvider returns the list of files it copied to local
// storage, but we don't really care about what was copied NOW: what we want is the
// list of everything we ever cached, so we ignore the return value.
- BinaryDictionaryFileDumper.cacheWordListsFromContentProvider(locale, context,
- hasDefaultWordList);
+ // TODO: The experimental version is not supported by the Dictionary Pack Service yet
+ if (!ProductionFlag.IS_EXPERIMENTAL) {
+ BinaryDictionaryFileDumper.cacheWordListsFromContentProvider(locale, context,
+ hasDefaultWordList);
+ }
final File[] cachedWordLists = getCachedWordLists(locale.toString(), context);
- final String mainDictId = getMainDictId(locale);
+ final String mainDictId = DictionaryInfoUtils.getMainDictId(locale);
final DictPackSettings dictPackSettings = new DictPackSettings(context);
boolean foundMainDict = false;
final ArrayList<AssetFileAddress> fileList = CollectionUtils.newArrayList();
// cachedWordLists may not be null, see doc for getCachedDictionaryList
for (final File f : cachedWordLists) {
- final String wordListId = getWordListIdFromFileName(f.getName());
+ final String wordListId = DictionaryInfoUtils.getWordListIdFromFileName(f.getName());
final boolean canUse = f.canRead() && hackCanUseDictionaryFile(locale, f);
- if (canUse && isMainWordListId(wordListId)) {
+ if (canUse && DictionaryInfoUtils.isMainWordListId(wordListId)) {
foundMainDict = true;
}
if (!dictPackSettings.isWordListActive(wordListId)) continue;
@@ -452,7 +316,7 @@ final class BinaryDictionaryGetter {
if (!foundMainDict && dictPackSettings.isWordListActive(mainDictId)) {
final int fallbackResId =
- DictionaryFactory.getMainDictionaryResourceId(context.getResources(), locale);
+ DictionaryInfoUtils.getMainDictionaryResourceId(context.getResources(), locale);
final AssetFileAddress fallbackAsset = loadFallbackResource(context, fallbackResId);
if (null != fallbackAsset) {
fileList.add(fallbackAsset);
diff --git a/java/src/com/android/inputmethod/latin/BoundedTreeSet.java b/java/src/com/android/inputmethod/latin/BoundedTreeSet.java
index 7f7ff31c8..489a74ef1 100644
--- a/java/src/com/android/inputmethod/latin/BoundedTreeSet.java
+++ b/java/src/com/android/inputmethod/latin/BoundedTreeSet.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/CapsModeUtils.java b/java/src/com/android/inputmethod/latin/CapsModeUtils.java
new file mode 100644
index 000000000..1012cd519
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/CapsModeUtils.java
@@ -0,0 +1,266 @@
+/*
+ * Copyright (C) 2013 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.text.InputType;
+import android.text.TextUtils;
+
+import java.util.Locale;
+
+public final class CapsModeUtils {
+ private CapsModeUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ /**
+ * Apply an auto-caps mode to a string.
+ *
+ * This intentionally does NOT apply manual caps mode. It only changes the capitalization if
+ * the mode is one of the auto-caps modes.
+ * @param s The string to capitalize.
+ * @param capitalizeMode The mode in which to capitalize.
+ * @param locale The locale for capitalizing.
+ * @return The capitalized string.
+ */
+ public static String applyAutoCapsMode(final String s, final int capitalizeMode,
+ final Locale locale) {
+ if (WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED == capitalizeMode) {
+ return s.toUpperCase(locale);
+ } else if (WordComposer.CAPS_MODE_AUTO_SHIFTED == capitalizeMode) {
+ return StringUtils.toTitleCase(s, locale);
+ } else {
+ return s;
+ }
+ }
+
+ /**
+ * Return whether a constant represents an auto-caps mode (either auto-shift or auto-shift-lock)
+ * @param mode The mode to test for
+ * @return true if this represents an auto-caps mode, false otherwise
+ */
+ public static boolean isAutoCapsMode(final int mode) {
+ return WordComposer.CAPS_MODE_AUTO_SHIFTED == mode
+ || WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED == mode;
+ }
+
+ /**
+ * Determine what caps mode should be in effect at the current offset in
+ * the text. Only the mode bits set in <var>reqModes</var> will be
+ * checked. Note that the caps mode flags here are explicitly defined
+ * to match those in {@link InputType}.
+ *
+ * This code is a straight copy of TextUtils.getCapsMode (modulo namespace and formatting
+ * issues). This will change in the future as we simplify the code for our use and fix bugs.
+ *
+ * @param cs The text that should be checked for caps modes.
+ * @param reqModes The modes to be checked: may be any combination of
+ * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
+ * {@link TextUtils#CAP_MODE_SENTENCES}.
+ * @param locale The locale to consider for capitalization rules
+ * @param hasSpaceBefore Whether we should consider there is a space inserted at the end of cs
+ *
+ * @return Returns the actual capitalization modes that can be in effect
+ * at the current position, which is any combination of
+ * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
+ * {@link TextUtils#CAP_MODE_SENTENCES}.
+ */
+ public static int getCapsMode(final CharSequence cs, final int reqModes, final Locale locale,
+ final boolean hasSpaceBefore) {
+ // Quick description of what we want to do:
+ // CAP_MODE_CHARACTERS is always on.
+ // CAP_MODE_WORDS is on if there is some whitespace before the cursor.
+ // CAP_MODE_SENTENCES is on if there is some whitespace before the cursor, and the end
+ // of a sentence just before that.
+ // We ignore opening parentheses and the like just before the cursor for purposes of
+ // finding whitespace for WORDS and SENTENCES modes.
+ // The end of a sentence ends with a period, question mark or exclamation mark. If it's
+ // a period, it also needs not to be an abbreviation, which means it also needs to either
+ // be immediately preceded by punctuation, or by a string of only letters with single
+ // periods interleaved.
+
+ // Step 1 : check for cap MODE_CHARACTERS. If it's looked for, it's always on.
+ if ((reqModes & (TextUtils.CAP_MODE_WORDS | TextUtils.CAP_MODE_SENTENCES)) == 0) {
+ // Here we are not looking for MODE_WORDS or MODE_SENTENCES, so since we already
+ // evaluated MODE_CHARACTERS, we can return.
+ return TextUtils.CAP_MODE_CHARACTERS & reqModes;
+ }
+
+ // Step 2 : Skip (ignore at the end of input) any opening punctuation. This includes
+ // opening parentheses, brackets, opening quotes, everything that *opens* a span of
+ // text in the linguistic sense. In RTL languages, this is still an opening sign, although
+ // it may look like a right parenthesis for example. We also include double quote and
+ // single quote since they aren't start punctuation in the unicode sense, but should still
+ // be skipped for English. TODO: does this depend on the language?
+ int i;
+ if (hasSpaceBefore) {
+ i = cs.length() + 1;
+ } else {
+ for (i = cs.length(); i > 0; i--) {
+ final char c = cs.charAt(i - 1);
+ if (c != Constants.CODE_DOUBLE_QUOTE && c != Constants.CODE_SINGLE_QUOTE
+ && Character.getType(c) != Character.START_PUNCTUATION) {
+ break;
+ }
+ }
+ }
+
+ // We are now on the character that precedes any starting punctuation, so in the most
+ // frequent case this will be whitespace or a letter, although it may occasionally be a
+ // start of line, or some symbol.
+
+ // Step 3 : Search for the start of a paragraph. From the starting point computed in step 2,
+ // we go back over any space or tab char sitting there. We find the start of a paragraph
+ // if the first char that's not a space or tab is a start of line (as in \n, start of text,
+ // or some other similar characters).
+ int j = i;
+ char prevChar = Constants.CODE_SPACE;
+ if (hasSpaceBefore) --j;
+ while (j > 0) {
+ prevChar = cs.charAt(j - 1);
+ if (!Character.isSpaceChar(prevChar) && prevChar != Constants.CODE_TAB) break;
+ j--;
+ }
+ if (j <= 0 || Character.isWhitespace(prevChar)) {
+ // There are only spacing chars between the start of the paragraph and the cursor,
+ // defined as a isWhitespace() char that is neither a isSpaceChar() nor a tab. Both
+ // MODE_WORDS and MODE_SENTENCES should be active.
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
+ | TextUtils.CAP_MODE_SENTENCES) & reqModes;
+ }
+ if (i == j) {
+ // If we don't have whitespace before index i, it means neither MODE_WORDS
+ // nor mode sentences should be on so we can return right away.
+ return TextUtils.CAP_MODE_CHARACTERS & reqModes;
+ }
+ if ((reqModes & TextUtils.CAP_MODE_SENTENCES) == 0) {
+ // Here we know we have whitespace before the cursor (if not, we returned in the above
+ // if i == j clause), so we need MODE_WORDS to be on. And we don't need to evaluate
+ // MODE_SENTENCES so we can return right away.
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ }
+ // Please note that because of the reqModes & CAP_MODE_SENTENCES test a few lines above,
+ // we know that MODE_SENTENCES is being requested.
+
+ // Step 4 : Search for MODE_SENTENCES.
+ // English is a special case in that "American typography" rules, which are the most common
+ // in English, state that a sentence terminator immediately following a quotation mark
+ // should be swapped with it and de-duplicated (included in the quotation mark),
+ // e.g. <<Did he say, "let's go home?">>
+ // No other language has such a rule as far as I know, instead putting inside the quotation
+ // mark as the exact thing quoted and handling the surrounding punctuation independently,
+ // e.g. <<Did he say, "let's go home"?>>
+ // Hence, specifically for English, we treat this special case here.
+ if (Locale.ENGLISH.getLanguage().equals(locale.getLanguage())) {
+ for (; j > 0; j--) {
+ // Here we look to go over any closing punctuation. This is because in dominant
+ // variants of English, the final period is placed within double quotes and maybe
+ // other closing punctuation signs. This is generally not true in other languages.
+ final char c = cs.charAt(j - 1);
+ if (c != Constants.CODE_DOUBLE_QUOTE && c != Constants.CODE_SINGLE_QUOTE
+ && Character.getType(c) != Character.END_PUNCTUATION) {
+ break;
+ }
+ }
+ }
+
+ if (j <= 0) return TextUtils.CAP_MODE_CHARACTERS & reqModes;
+ char c = cs.charAt(--j);
+
+ // We found the next interesting chunk of text ; next we need to determine if it's the
+ // end of a sentence. If we have a question mark or an exclamation mark, it's the end of
+ // a sentence. If it's neither, the only remaining case is the period so we get the opposite
+ // case out of the way.
+ if (c == Constants.CODE_QUESTION_MARK || c == Constants.CODE_EXCLAMATION_MARK) {
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_SENTENCES) & reqModes;
+ }
+ if (c != Constants.CODE_PERIOD || j <= 0) {
+ return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ }
+
+ // We found out that we have a period. We need to determine if this is a full stop or
+ // otherwise sentence-ending period, or an abbreviation like "e.g.". An abbreviation
+ // looks like (\w\.){2,}
+ // To find out, we will have a simple state machine with the following states :
+ // START, WORD, PERIOD, ABBREVIATION
+ // On START : (just before the first period)
+ // letter => WORD
+ // whitespace => end with no caps (it was a stand-alone period)
+ // otherwise => end with caps (several periods/symbols in a row)
+ // On WORD : (within the word just before the first period)
+ // letter => WORD
+ // period => PERIOD
+ // otherwise => end with caps (it was a word with a full stop at the end)
+ // On PERIOD : (period within a potential abbreviation)
+ // letter => LETTER
+ // otherwise => end with caps (it was not an abbreviation)
+ // On LETTER : (letter within a potential abbreviation)
+ // letter => LETTER
+ // period => PERIOD
+ // otherwise => end with no caps (it was an abbreviation)
+ // "Not an abbreviation" in the above chart essentially covers cases like "...yes.". This
+ // should capitalize.
+
+ final int START = 0;
+ final int WORD = 1;
+ final int PERIOD = 2;
+ final int LETTER = 3;
+ final int caps = (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
+ | TextUtils.CAP_MODE_SENTENCES) & reqModes;
+ final int noCaps = (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ int state = START;
+ while (j > 0) {
+ c = cs.charAt(--j);
+ switch (state) {
+ case START:
+ if (Character.isLetter(c)) {
+ state = WORD;
+ } else if (Character.isWhitespace(c)) {
+ return noCaps;
+ } else {
+ return caps;
+ }
+ break;
+ case WORD:
+ if (Character.isLetter(c)) {
+ state = WORD;
+ } else if (c == Constants.CODE_PERIOD) {
+ state = PERIOD;
+ } else {
+ return caps;
+ }
+ break;
+ case PERIOD:
+ if (Character.isLetter(c)) {
+ state = LETTER;
+ } else {
+ return caps;
+ }
+ break;
+ case LETTER:
+ if (Character.isLetter(c)) {
+ state = LETTER;
+ } else if (c == Constants.CODE_PERIOD) {
+ state = PERIOD;
+ } else {
+ return noCaps;
+ }
+ }
+ }
+ // Here we arrived at the start of the line. This should behave exactly like whitespace.
+ return (START == state || LETTER == state) ? noCaps : caps;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/CollectionUtils.java b/java/src/com/android/inputmethod/latin/CollectionUtils.java
index c75f2df5c..a8623cc63 100644
--- a/java/src/com/android/inputmethod/latin/CollectionUtils.java
+++ b/java/src/com/android/inputmethod/latin/CollectionUtils.java
@@ -27,6 +27,7 @@ import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
+import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
@@ -39,6 +40,10 @@ public final class CollectionUtils {
return new HashMap<K,V>();
}
+ public static <K, V> WeakHashMap<K, V> newWeakHashMap() {
+ return new WeakHashMap<K, V>();
+ }
+
public static <K,V> TreeMap<K,V> newTreeMap() {
return new TreeMap<K,V>();
}
diff --git a/java/src/com/android/inputmethod/latin/Constants.java b/java/src/com/android/inputmethod/latin/Constants.java
index 57e12a64f..50e50233e 100644
--- a/java/src/com/android/inputmethod/latin/Constants.java
+++ b/java/src/com/android/inputmethod/latin/Constants.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -111,7 +111,7 @@ public final class Constants {
}
}
- public static class TextUtils {
+ public static final class TextUtils {
/**
* Capitalization mode for {@link android.text.TextUtils#getCapsMode}: don't capitalize
* characters. This value may be used with
@@ -126,7 +126,8 @@ public final class Constants {
}
}
- public static class Dictionary {
+ public static final class Dictionary {
+ // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h
public static final int MAX_WORD_LENGTH = 48;
private Dictionary() {
@@ -136,10 +137,85 @@ public final class Constants {
public static final int NOT_A_CODE = -1;
- // See {@link KeyboardActionListener.Adapter#isInvalidCoordinate(int)}.
public static final int NOT_A_COORDINATE = -1;
public static final int SUGGESTION_STRIP_COORDINATE = -2;
public static final int SPELL_CHECKER_COORDINATE = -3;
+ public static final int EXTERNAL_KEYBOARD_COORDINATE = -4;
+
+ public static boolean isValidCoordinate(final int coordinate) {
+ // Detect {@link NOT_A_COORDINATE}, {@link SUGGESTION_STRIP_COORDINATE},
+ // and {@link SPELL_CHECKER_COORDINATE}.
+ return coordinate >= 0;
+ }
+
+ /**
+ * Some common keys code. Must be positive.
+ */
+ public static final int CODE_ENTER = '\n';
+ 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 = '"';
+ public static final int CODE_QUESTION_MARK = '?';
+ public static final int CODE_EXCLAMATION_MARK = '!';
+ // TODO: Check how this should work for right-to-left languages. It seems to stand
+ // that for rtl languages, a closing parenthesis is a left parenthesis. Is this
+ // managed by the font? Or is it a different char?
+ public static final int CODE_CLOSING_PARENTHESIS = ')';
+ public static final int CODE_CLOSING_SQUARE_BRACKET = ']';
+ public static final int CODE_CLOSING_CURLY_BRACKET = '}';
+ public static final int CODE_CLOSING_ANGLE_BRACKET = '>';
+
+ /**
+ * Special keys code. Must be negative.
+ * These should be aligned with KeyboardCodesSet.ID_TO_NAME[],
+ * KeyboardCodesSet.DEFAULT[] and KeyboardCodesSet.RTL[]
+ */
+ public static final int CODE_SHIFT = -1;
+ public static final int CODE_SWITCH_ALPHA_SYMBOL = -2;
+ public static final int CODE_OUTPUT_TEXT = -3;
+ public static final int CODE_DELETE = -4;
+ public static final int CODE_SETTINGS = -5;
+ public static final int CODE_SHORTCUT = -6;
+ public static final int CODE_ACTION_NEXT = -7;
+ public static final int CODE_ACTION_PREVIOUS = -8;
+ public static final int CODE_LANGUAGE_SWITCH = -9;
+ public static final int CODE_RESEARCH = -10;
+ public static final int CODE_SHIFT_ENTER = -11;
+ // Code value representing the code is not specified.
+ public static final int CODE_UNSPECIFIED = -12;
+
+ public static boolean isLetterCode(final int code) {
+ return code >= CODE_SPACE;
+ }
+
+ public static String printableCode(final int code) {
+ switch (code) {
+ case CODE_SHIFT: return "shift";
+ case CODE_SWITCH_ALPHA_SYMBOL: return "symbol";
+ case CODE_OUTPUT_TEXT: return "text";
+ case CODE_DELETE: return "delete";
+ case CODE_SETTINGS: return "settings";
+ case CODE_SHORTCUT: return "shortcut";
+ case CODE_ACTION_NEXT: return "actionNext";
+ case CODE_ACTION_PREVIOUS: return "actionPrevious";
+ case CODE_LANGUAGE_SWITCH: return "languageSwitch";
+ case CODE_UNSPECIFIED: return "unspec";
+ case CODE_TAB: return "tab";
+ case CODE_ENTER: return "enter";
+ case CODE_RESEARCH: return "research";
+ default:
+ if (code < CODE_SPACE) return String.format("'\\u%02x'", code);
+ if (code < 0x100) return String.format("'%c'", code);
+ return String.format("'\\u%04x'", code);
+ }
+ }
+
+ // Constants for CSV parsing.
+ public static final char CSV_SEPARATOR = ',';
+ public static final char CSV_ESCAPE = '\\';
private Constants() {
// This utility class is not publicly instantiable.
diff --git a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java
index 5edc4314f..8b5a76a17 100644
--- a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java
@@ -1,15 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -24,8 +26,6 @@ import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.util.Log;
-import com.android.inputmethod.keyboard.Keyboard;
-
import java.util.Locale;
public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
@@ -62,7 +62,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
*/
private final boolean mUseFirstLastBigrams;
- public ContactsBinaryDictionary(final Context context, Locale locale) {
+ public ContactsBinaryDictionary(final Context context, final Locale locale) {
super(context, getFilenameWithLocale(NAME, locale.toString()), Dictionary.TYPE_CONTACTS);
mLocale = locale;
mUseFirstLastBigrams = useFirstLastBigramsForLocale(locale);
@@ -120,7 +120,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
}
}
- private boolean useFirstLastBigramsForLocale(Locale locale) {
+ private boolean useFirstLastBigramsForLocale(final Locale locale) {
// TODO: Add firstname/lastname bigram rules for other languages.
if (locale != null && locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
return true;
@@ -128,7 +128,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
return false;
}
- private void addWords(Cursor cursor) {
+ private void addWords(final Cursor cursor) {
clearFusionDictionary();
int count = 0;
while (!cursor.isAfterLast() && count < MAX_CONTACT_COUNT) {
@@ -160,7 +160,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
* Adds the words in a name (e.g., firstname/lastname) to the binary dictionary along with their
* bigrams depending on locale.
*/
- private void addName(String name) {
+ private void addName(final String name) {
int len = StringUtils.codePointCount(name);
String prevWord = null;
// TODO: Better tokenization for non-Latin writing systems
@@ -188,12 +188,13 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
/**
* Returns the index of the last letter in the word, starting from position startIndex.
*/
- private static int getWordEndPosition(String string, int len, int startIndex) {
+ private static int getWordEndPosition(final String string, final int len,
+ final int startIndex) {
int end;
int cp = 0;
for (end = startIndex + 1; end < len; end += Character.charCount(cp)) {
cp = string.codePointAt(end);
- if (!(cp == Keyboard.CODE_DASH || cp == Keyboard.CODE_SINGLE_QUOTE
+ if (!(cp == Constants.CODE_DASH || cp == Constants.CODE_SINGLE_QUOTE
|| Character.isLetter(cp))) {
break;
}
@@ -249,7 +250,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
return false;
}
- private static boolean isValidName(String name) {
+ private static boolean isValidName(final String name) {
if (name != null && -1 == name.indexOf('@')) {
return true;
}
@@ -259,7 +260,7 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary {
/**
* Checks if the words in a name are in the current binary dictionary.
*/
- private boolean isNameInDictionary(String name) {
+ private boolean isNameInDictionary(final String name) {
int len = StringUtils.codePointCount(name);
String prevWord = null;
for (int i = 0; i < len; i++) {
diff --git a/java/src/com/android/inputmethod/latin/CoordinateUtils.java b/java/src/com/android/inputmethod/latin/CoordinateUtils.java
new file mode 100644
index 000000000..af270e1e4
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/CoordinateUtils.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2012 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;
+
+public final class CoordinateUtils {
+ private static final int INDEX_X = 0;
+ private static final int INDEX_Y = 1;
+ private static final int ARRAY_SIZE = INDEX_Y + 1;
+
+ private CoordinateUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static int[] newInstance() {
+ return new int[ARRAY_SIZE];
+ }
+
+ public static int x(final int[] coords) {
+ return coords[INDEX_X];
+ }
+
+ public static int y(final int[] coords) {
+ return coords[INDEX_Y];
+ }
+
+ public static void set(final int[] coords, final int x, final int y) {
+ coords[INDEX_X] = x;
+ coords[INDEX_Y] = y;
+ }
+
+ public static void copy(final int[] destination, final int[] source) {
+ destination[INDEX_X] = source[INDEX_X];
+ destination[INDEX_Y] = source[INDEX_Y];
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/DebugSettings.java b/java/src/com/android/inputmethod/latin/DebugSettings.java
index 3af3cab2c..7df266ef2 100644
--- a/java/src/com/android/inputmethod/latin/DebugSettings.java
+++ b/java/src/com/android/inputmethod/latin/DebugSettings.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -25,6 +25,7 @@ import android.os.Process;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
+import android.preference.PreferenceScreen;
import android.util.Log;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
@@ -32,14 +33,18 @@ import com.android.inputmethod.research.ResearchLogger;
public final class DebugSettings extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener {
-
private static final String TAG = DebugSettings.class.getSimpleName();
- private static final String DEBUG_MODE_KEY = "debug_mode";
- public static final String FORCE_NON_DISTINCT_MULTITOUCH_KEY = "force_non_distinct_multitouch";
+
+ public static final String PREF_DEBUG_MODE = "debug_mode";
+ public static final String PREF_FORCE_NON_DISTINCT_MULTITOUCH = "force_non_distinct_multitouch";
public static final String PREF_USABILITY_STUDY_MODE = "usability_study_mode";
+ public static final String PREF_STATISTICS_LOGGING = "enable_logging";
+ private static final String PREF_READ_EXTERNAL_DICTIONARY = "read_external_dictionary";
+ private static final boolean SHOW_STATISTICS_LOGGING = false;
private boolean mServiceNeedsRestart = false;
private CheckBoxPreference mDebugMode;
+ private CheckBoxPreference mStatisticsLoggingPref;
@Override
public void onCreate(Bundle icicle) {
@@ -55,9 +60,31 @@ public final class DebugSettings extends PreferenceFragment
ResearchLogger.DEFAULT_USABILITY_STUDY_MODE));
checkbox.setSummary(R.string.settings_warning_researcher_mode);
}
+ final Preference statisticsLoggingPref = findPreference(PREF_STATISTICS_LOGGING);
+ if (statisticsLoggingPref instanceof CheckBoxPreference) {
+ mStatisticsLoggingPref = (CheckBoxPreference) statisticsLoggingPref;
+ if (!SHOW_STATISTICS_LOGGING) {
+ getPreferenceScreen().removePreference(statisticsLoggingPref);
+ }
+ }
+
+ PreferenceScreen readExternalDictionary =
+ (PreferenceScreen) findPreference(PREF_READ_EXTERNAL_DICTIONARY);
+ if (null != readExternalDictionary) {
+ readExternalDictionary.setOnPreferenceClickListener(
+ new Preference.OnPreferenceClickListener() {
+ @Override
+ public boolean onPreferenceClick(final Preference arg0) {
+ ExternalDictionaryGetterForDebug.chooseAndInstallDictionary(
+ getActivity());
+ mServiceNeedsRestart = true;
+ return true;
+ }
+ });
+ }
mServiceNeedsRestart = false;
- mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY);
+ mDebugMode = (CheckBoxPreference) findPreference(PREF_DEBUG_MODE);
updateDebugMode();
}
@@ -69,13 +96,21 @@ public final class DebugSettings extends PreferenceFragment
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
- if (key.equals(DEBUG_MODE_KEY)) {
+ if (key.equals(PREF_DEBUG_MODE)) {
if (mDebugMode != null) {
- mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false));
+ mDebugMode.setChecked(prefs.getBoolean(PREF_DEBUG_MODE, false));
+ final boolean checked = mDebugMode.isChecked();
+ if (mStatisticsLoggingPref != null) {
+ if (checked) {
+ getPreferenceScreen().addPreference(mStatisticsLoggingPref);
+ } else {
+ getPreferenceScreen().removePreference(mStatisticsLoggingPref);
+ }
+ }
updateDebugMode();
mServiceNeedsRestart = true;
}
- } else if (key.equals(FORCE_NON_DISTINCT_MULTITOUCH_KEY)
+ } else if (key.equals(PREF_FORCE_NON_DISTINCT_MULTITOUCH)
|| key.equals(KeyboardSwitcher.PREF_KEYBOARD_LAYOUT)) {
mServiceNeedsRestart = true;
}
@@ -89,6 +124,9 @@ public final class DebugSettings extends PreferenceFragment
String version = "";
try {
final Context context = getActivity();
+ if (context == null) {
+ return;
+ }
final String packageName = context.getPackageName();
PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
version = "Version " + info.versionName;
diff --git a/java/src/com/android/inputmethod/latin/DebugSettingsActivity.java b/java/src/com/android/inputmethod/latin/DebugSettingsActivity.java
index 6ef19ee82..2a501a665 100644
--- a/java/src/com/android/inputmethod/latin/DebugSettingsActivity.java
+++ b/java/src/com/android/inputmethod/latin/DebugSettingsActivity.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/DicTraverseSession.java b/java/src/com/android/inputmethod/latin/DicTraverseSession.java
index ce1b64660..534e2116b 100644
--- a/java/src/com/android/inputmethod/latin/DicTraverseSession.java
+++ b/java/src/com/android/inputmethod/latin/DicTraverseSession.java
@@ -23,10 +23,10 @@ public final class DicTraverseSession {
JniUtils.loadNativeLibrary();
}
- private native long setDicTraverseSessionNative(String locale);
- private native void initDicTraverseSessionNative(long nativeDicTraverseSession,
+ private static native long setDicTraverseSessionNative(String locale);
+ private static native void initDicTraverseSessionNative(long nativeDicTraverseSession,
long dictionary, int[] previousWord, int previousWordLength);
- private native void releaseDicTraverseSessionNative(long nativeDicTraverseSession);
+ private static native void releaseDicTraverseSessionNative(long nativeDicTraverseSession);
private long mNativeDicTraverseSession;
diff --git a/java/src/com/android/inputmethod/latin/Dictionary.java b/java/src/com/android/inputmethod/latin/Dictionary.java
index 88d0c09dd..ff3d83fad 100644
--- a/java/src/com/android/inputmethod/latin/Dictionary.java
+++ b/java/src/com/android/inputmethod/latin/Dictionary.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2008 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
+ * 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
+ * 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.
+ * 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;
@@ -26,11 +26,6 @@ import java.util.ArrayList;
* strokes.
*/
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_SCORE_MULTIPLIER = 2;
-
public static final int NOT_A_PROBABILITY = -1;
public static final String TYPE_USER_TYPED = "user_typed";
@@ -59,12 +54,12 @@ public abstract class Dictionary {
// TODO: pass more context than just the previous word, to enable better suggestions (n-gram
// and more)
abstract public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo);
+ final String prevWord, final ProximityInfo proximityInfo);
// The default implementation of this method ignores sessionId.
// Subclasses that want to use sessionId need to override this method.
public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo, int sessionId) {
+ final String prevWord, final ProximityInfo proximityInfo, final int sessionId) {
return getSuggestions(composer, prevWord, proximityInfo);
}
@@ -73,9 +68,9 @@ public abstract class Dictionary {
* @param word the word to search for. The search should be case-insensitive.
* @return true if the word exists, false otherwise
*/
- abstract public boolean isValidWord(CharSequence word);
+ abstract public boolean isValidWord(final String word);
- public int getFrequency(CharSequence word) {
+ public int getFrequency(final String word) {
return NOT_A_PROBABILITY;
}
@@ -87,7 +82,7 @@ public abstract class Dictionary {
* @param typedWord the word to compare with
* @return true if they are the same, false otherwise.
*/
- protected boolean same(final char[] word, final int length, final CharSequence typedWord) {
+ protected boolean same(final char[] word, final int length, final String typedWord) {
if (typedWord.length() != length) {
return false;
}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryCollection.java b/java/src/com/android/inputmethod/latin/DictionaryCollection.java
index d3b120989..2832ad43c 100644
--- a/java/src/com/android/inputmethod/latin/DictionaryCollection.java
+++ b/java/src/com/android/inputmethod/latin/DictionaryCollection.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -38,7 +38,7 @@ public final class DictionaryCollection extends Dictionary {
mDictionaries = CollectionUtils.newCopyOnWriteArrayList();
}
- public DictionaryCollection(final String dictType, Dictionary... dictionaries) {
+ public DictionaryCollection(final String dictType, final Dictionary... dictionaries) {
super(dictType);
if (null == dictionaries) {
mDictionaries = CollectionUtils.newCopyOnWriteArrayList();
@@ -48,7 +48,7 @@ public final class DictionaryCollection extends Dictionary {
}
}
- public DictionaryCollection(final String dictType, Collection<Dictionary> dictionaries) {
+ public DictionaryCollection(final String dictType, final Collection<Dictionary> dictionaries) {
super(dictType);
mDictionaries = CollectionUtils.newCopyOnWriteArrayList(dictionaries);
mDictionaries.removeAll(Collections.singleton(null));
@@ -56,7 +56,7 @@ public final class DictionaryCollection extends Dictionary {
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo) {
+ final String prevWord, final ProximityInfo proximityInfo) {
final CopyOnWriteArrayList<Dictionary> dictionaries = mDictionaries;
if (dictionaries.isEmpty()) return null;
// To avoid creating unnecessary objects, we get the list out of the first
@@ -74,14 +74,14 @@ public final class DictionaryCollection extends Dictionary {
}
@Override
- public boolean isValidWord(CharSequence word) {
+ public boolean isValidWord(final String word) {
for (int i = mDictionaries.size() - 1; i >= 0; --i)
if (mDictionaries.get(i).isValidWord(word)) return true;
return false;
}
@Override
- public int getFrequency(CharSequence word) {
+ public int getFrequency(final String word) {
int maxFreq = -1;
for (int i = mDictionaries.size() - 1; i >= 0; --i) {
final int tempFreq = mDictionaries.get(i).getFrequency(word);
diff --git a/java/src/com/android/inputmethod/latin/DictionaryFactory.java b/java/src/com/android/inputmethod/latin/DictionaryFactory.java
index f381973ae..40e51672a 100644
--- a/java/src/com/android/inputmethod/latin/DictionaryFactory.java
+++ b/java/src/com/android/inputmethod/latin/DictionaryFactory.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -31,9 +31,6 @@ import java.util.Locale;
*/
public final class DictionaryFactory {
private static final String TAG = DictionaryFactory.class.getSimpleName();
- // This class must be located in the same package as LatinIME.java.
- private static final String RESOURCE_PACKAGE_NAME =
- DictionaryFactory.class.getPackage().getName();
/**
* Initializes a main dictionary collection from a dictionary pack, with explicit flags.
@@ -58,9 +55,8 @@ public final class DictionaryFactory {
BinaryDictionaryGetter.getDictionaryFiles(locale, context);
if (null != assetFileList) {
for (final AssetFileAddress f : assetFileList) {
- final BinaryDictionary binaryDictionary =
- new BinaryDictionary(context, f.mFilename, f.mOffset, f.mLength,
- useFullEditDistance, locale, Dictionary.TYPE_MAIN);
+ final BinaryDictionary binaryDictionary = new BinaryDictionary(f.mFilename,
+ f.mOffset, f.mLength, useFullEditDistance, locale, Dictionary.TYPE_MAIN);
if (binaryDictionary.isValidDictionary()) {
dictList.add(binaryDictionary);
}
@@ -97,8 +93,8 @@ public final class DictionaryFactory {
final Locale locale) {
AssetFileDescriptor afd = null;
try {
- final int resId =
- getMainDictionaryResourceIdIfAvailableForLocale(context.getResources(), locale);
+ final int resId = DictionaryInfoUtils.getMainDictionaryResourceIdIfAvailableForLocale(
+ context.getResources(), locale);
if (0 == resId) return null;
afd = context.getResources().openRawResourceFd(resId);
if (afd == null) {
@@ -112,7 +108,7 @@ public final class DictionaryFactory {
Log.e(TAG, "sourceDir is not a file: " + sourceDir);
return null;
}
- return new BinaryDictionary(context, sourceDir, afd.getStartOffset(), afd.getLength(),
+ return new BinaryDictionary(sourceDir, afd.getStartOffset(), afd.getLength(),
false /* useFullEditDistance */, locale, Dictionary.TYPE_MAIN);
} catch (android.content.res.Resources.NotFoundException e) {
Log.e(TAG, "Could not find the resource");
@@ -130,17 +126,16 @@ public final class DictionaryFactory {
/**
* 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 useFullEditDistance whether to use the full edit distance in suggestions
* @return the created dictionary, or null.
*/
- public static Dictionary createDictionaryForTest(Context context, File dictionary,
- long startOffset, long length, final boolean useFullEditDistance, Locale locale) {
+ public static Dictionary createDictionaryForTest(File dictionary, long startOffset, long length,
+ final boolean useFullEditDistance, Locale locale) {
if (dictionary.isFile()) {
- return new BinaryDictionary(context, dictionary.getAbsolutePath(), startOffset, length,
+ return new BinaryDictionary(dictionary.getAbsolutePath(), startOffset, length,
useFullEditDistance, locale, Dictionary.TYPE_MAIN);
} else {
Log.e(TAG, "Could not find the file. path=" + dictionary.getAbsolutePath());
@@ -156,47 +151,7 @@ public final class DictionaryFactory {
*/
public static boolean isDictionaryAvailable(Context context, Locale locale) {
final Resources res = context.getResources();
- return 0 != getMainDictionaryResourceIdIfAvailableForLocale(res, locale);
- }
-
- private static final String DEFAULT_MAIN_DICT = "main";
- private static final String MAIN_DICT_PREFIX = "main_";
-
- /**
- * Helper method to return a dictionary res id for a locale, or 0 if none.
- * @param locale dictionary locale
- * @return main dictionary resource id
- */
- private static int getMainDictionaryResourceIdIfAvailableForLocale(final Resources res,
- final Locale locale) {
- int resId;
- // Try to find main_language_country dictionary.
- if (!locale.getCountry().isEmpty()) {
- final String dictLanguageCountry = MAIN_DICT_PREFIX + locale.toString().toLowerCase();
- if ((resId = res.getIdentifier(
- dictLanguageCountry, "raw", RESOURCE_PACKAGE_NAME)) != 0) {
- return resId;
- }
- }
-
- // Try to find main_language dictionary.
- final String dictLanguage = MAIN_DICT_PREFIX + locale.getLanguage();
- if ((resId = res.getIdentifier(dictLanguage, "raw", RESOURCE_PACKAGE_NAME)) != 0) {
- return resId;
- }
-
- // Not found, return 0
- return 0;
- }
-
- /**
- * Returns a main dictionary resource id
- * @param locale dictionary locale
- * @return main dictionary resource id
- */
- public static int getMainDictionaryResourceId(final Resources res, final Locale locale) {
- int resourceId = getMainDictionaryResourceIdIfAvailableForLocale(res, locale);
- if (0 != resourceId) return resourceId;
- return res.getIdentifier(DEFAULT_MAIN_DICT, "raw", RESOURCE_PACKAGE_NAME);
+ return 0 != DictionaryInfoUtils.getMainDictionaryResourceIdIfAvailableForLocale(
+ res, locale);
}
}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryInfoUtils.java b/java/src/com/android/inputmethod/latin/DictionaryInfoUtils.java
new file mode 100644
index 000000000..dcfa483f8
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/DictionaryInfoUtils.java
@@ -0,0 +1,355 @@
+/*
+ * Copyright (C) 2013 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.ContentValues;
+import android.content.Context;
+import android.content.res.AssetManager;
+import android.content.res.Resources;
+import android.text.format.DateUtils;
+import android.util.Log;
+
+import com.android.inputmethod.latin.makedict.BinaryDictIOUtils;
+import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader;
+import com.android.inputmethod.latin.makedict.UnsupportedFormatException;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Locale;
+
+/**
+ * This class encapsulates the logic for the Latin-IME side of dictionary information management.
+ */
+public class DictionaryInfoUtils {
+ private static final String TAG = DictionaryInfoUtils.class.getSimpleName();
+ // This class must be located in the same package as LatinIME.java.
+ private static final String RESOURCE_PACKAGE_NAME =
+ DictionaryInfoUtils.class.getPackage().getName();
+ private static final String DEFAULT_MAIN_DICT = "main";
+ private static final String MAIN_DICT_PREFIX = "main_";
+ // 6 digits - unicode is limited to 21 bits
+ private static final int MAX_HEX_DIGITS_FOR_CODEPOINT = 6;
+
+ public static class DictionaryInfo {
+ private static final String LOCALE_COLUMN = "locale";
+ private static final String WORDLISTID_COLUMN = "id";
+ private static final String LOCAL_FILENAME_COLUMN = "filename";
+ private static final String DESCRIPTION_COLUMN = "description";
+ private static final String DATE_COLUMN = "date";
+ private static final String FILESIZE_COLUMN = "filesize";
+ private static final String VERSION_COLUMN = "version";
+ public final String mId;
+ public final Locale mLocale;
+ public final String mDescription;
+ public final AssetFileAddress mFileAddress;
+ public final int mVersion;
+ public DictionaryInfo(final String id, final Locale locale, final String description,
+ final AssetFileAddress fileAddress, final int version) {
+ mId = id;
+ mLocale = locale;
+ mDescription = description;
+ mFileAddress = fileAddress;
+ mVersion = version;
+ }
+ public ContentValues toContentValues() {
+ final ContentValues values = new ContentValues();
+ values.put(WORDLISTID_COLUMN, mId);
+ values.put(LOCALE_COLUMN, mLocale.toString());
+ values.put(DESCRIPTION_COLUMN, mDescription);
+ values.put(LOCAL_FILENAME_COLUMN, mFileAddress.mFilename);
+ values.put(DATE_COLUMN,
+ new File(mFileAddress.mFilename).lastModified() / DateUtils.SECOND_IN_MILLIS);
+ values.put(FILESIZE_COLUMN, mFileAddress.mLength);
+ values.put(VERSION_COLUMN, mVersion);
+ return values;
+ }
+ }
+
+ private DictionaryInfoUtils() {
+ // Private constructor to forbid instantation of this helper class.
+ }
+
+ /**
+ * Returns whether we may want to use this character as part of a file name.
+ *
+ * This basically only accepts ascii letters and numbers, and rejects everything else.
+ */
+ private static boolean isFileNameCharacter(int codePoint) {
+ if (codePoint >= 0x30 && codePoint <= 0x39) return true; // Digit
+ if (codePoint >= 0x41 && codePoint <= 0x5A) return true; // Uppercase
+ if (codePoint >= 0x61 && codePoint <= 0x7A) return true; // Lowercase
+ return codePoint == '_'; // Underscore
+ }
+
+ /**
+ * Escapes a string for any characters that may be suspicious for a file or directory name.
+ *
+ * Concretely this does a sort of URL-encoding except it will encode everything that's not
+ * alphanumeric or underscore. (true URL-encoding leaves alone characters like '*', which
+ * we cannot allow here)
+ */
+ // TODO: create a unit test for this method
+ public static String replaceFileNameDangerousCharacters(final String name) {
+ // This assumes '%' is fully available as a non-separator, normal
+ // character in a file name. This is probably true for all file systems.
+ final StringBuilder sb = new StringBuilder();
+ final int nameLength = name.length();
+ for (int i = 0; i < nameLength; i = name.offsetByCodePoints(i, 1)) {
+ final int codePoint = name.codePointAt(i);
+ if (DictionaryInfoUtils.isFileNameCharacter(codePoint)) {
+ sb.appendCodePoint(codePoint);
+ } else {
+ sb.append(String.format((Locale)null, "%%%1$0" + MAX_HEX_DIGITS_FOR_CODEPOINT + "x",
+ codePoint));
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Helper method to get the top level cache directory.
+ */
+ private static String getWordListCacheDirectory(final Context context) {
+ return context.getFilesDir() + File.separator + "dicts";
+ }
+
+ /**
+ * Reverse escaping done by replaceFileNameDangerousCharacters.
+ */
+ public static String getWordListIdFromFileName(final String fname) {
+ final StringBuilder sb = new StringBuilder();
+ final int fnameLength = fname.length();
+ for (int i = 0; i < fnameLength; i = fname.offsetByCodePoints(i, 1)) {
+ final int codePoint = fname.codePointAt(i);
+ if ('%' != codePoint) {
+ sb.appendCodePoint(codePoint);
+ } else {
+ // + 1 to pass the % sign
+ final int encodedCodePoint = Integer.parseInt(
+ fname.substring(i + 1, i + 1 + MAX_HEX_DIGITS_FOR_CODEPOINT), 16);
+ i += MAX_HEX_DIGITS_FOR_CODEPOINT;
+ sb.appendCodePoint(encodedCodePoint);
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Helper method to the list of cache directories, one for each distinct locale.
+ */
+ public static File[] getCachedDirectoryList(final Context context) {
+ return new File(DictionaryInfoUtils.getWordListCacheDirectory(context)).listFiles();
+ }
+
+ /**
+ * Returns the category for a given file name.
+ *
+ * This parses the file name, extracts the category, and returns it. See
+ * {@link #getMainDictId(Locale)} and {@link #isMainWordListId(String)}.
+ * @return The category as a string or null if it can't be found in the file name.
+ */
+ public static String getCategoryFromFileName(final String fileName) {
+ final String id = getWordListIdFromFileName(fileName);
+ final String[] idArray = id.split(BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR);
+ // An id is supposed to be in format category:locale, so splitting on the separator
+ // should yield a 2-elements array
+ if (2 != idArray.length) return null;
+ return idArray[0];
+ }
+
+ /**
+ * Find out the cache directory associated with a specific locale.
+ */
+ private static String getCacheDirectoryForLocale(final String locale, final Context context) {
+ final String relativeDirectoryName = replaceFileNameDangerousCharacters(locale);
+ final String absoluteDirectoryName = getWordListCacheDirectory(context) + File.separator
+ + relativeDirectoryName;
+ final File directory = new File(absoluteDirectoryName);
+ if (!directory.exists()) {
+ if (!directory.mkdirs()) {
+ Log.e(TAG, "Could not create the directory for locale" + locale);
+ }
+ }
+ return absoluteDirectoryName;
+ }
+
+ /**
+ * Generates a file name for the id and locale passed as an argument.
+ *
+ * In the current implementation the file name returned will always be unique for
+ * any id/locale pair, but please do not expect that the id can be the same for
+ * different dictionaries with different locales. An id should be unique for any
+ * dictionary.
+ * The file name is pretty much an URL-encoded version of the id inside a directory
+ * named like the locale, except it will also escape characters that look dangerous
+ * to some file systems.
+ * @param id the id of the dictionary for which to get a file name
+ * @param locale the locale for which to get the file name as a string
+ * @param context the context to use for getting the directory
+ * @return the name of the file to be created
+ */
+ public static String getCacheFileName(String id, String locale, Context context) {
+ final String fileName = replaceFileNameDangerousCharacters(id);
+ return getCacheDirectoryForLocale(locale, context) + File.separator + fileName;
+ }
+
+ public static boolean isMainWordListId(final String id) {
+ final String[] idArray = id.split(BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR);
+ // An id is supposed to be in format category:locale, so splitting on the separator
+ // should yield a 2-elements array
+ if (2 != idArray.length) return false;
+ return BinaryDictionaryGetter.MAIN_DICTIONARY_CATEGORY.equals(idArray[0]);
+ }
+
+ /**
+ * Helper method to return a dictionary res id for a locale, or 0 if none.
+ * @param locale dictionary locale
+ * @return main dictionary resource id
+ */
+ public static int getMainDictionaryResourceIdIfAvailableForLocale(final Resources res,
+ final Locale locale) {
+ int resId;
+ // Try to find main_language_country dictionary.
+ if (!locale.getCountry().isEmpty()) {
+ final String dictLanguageCountry =
+ MAIN_DICT_PREFIX + locale.toString().toLowerCase(Locale.ROOT);
+ if ((resId = res.getIdentifier(
+ dictLanguageCountry, "raw", RESOURCE_PACKAGE_NAME)) != 0) {
+ return resId;
+ }
+ }
+
+ // Try to find main_language dictionary.
+ final String dictLanguage = MAIN_DICT_PREFIX + locale.getLanguage();
+ if ((resId = res.getIdentifier(dictLanguage, "raw", RESOURCE_PACKAGE_NAME)) != 0) {
+ return resId;
+ }
+
+ // Not found, return 0
+ return 0;
+ }
+
+ /**
+ * Returns a main dictionary resource id
+ * @param locale dictionary locale
+ * @return main dictionary resource id
+ */
+ public static int getMainDictionaryResourceId(final Resources res, final Locale locale) {
+ int resourceId = getMainDictionaryResourceIdIfAvailableForLocale(res, locale);
+ if (0 != resourceId) return resourceId;
+ return res.getIdentifier(DEFAULT_MAIN_DICT, "raw", RESOURCE_PACKAGE_NAME);
+ }
+
+ /**
+ * Returns the id associated with the main word list for a specified locale.
+ *
+ * Word lists stored in Android Keyboard's resources are referred to as the "main"
+ * word lists. Since they can be updated like any other list, we need to assign a
+ * unique ID to them. This ID is just the name of the language (locale-wise) they
+ * are for, and this method returns this ID.
+ */
+ public static String getMainDictId(final Locale locale) {
+ // This works because we don't include by default different dictionaries for
+ // different countries. This actually needs to return the id that we would
+ // like to use for word lists included in resources, and the following is okay.
+ return BinaryDictionaryGetter.MAIN_DICTIONARY_CATEGORY +
+ BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR + locale.getLanguage().toString();
+ }
+
+ public static FileHeader getDictionaryFileHeaderOrNull(final File file) {
+ try {
+ return BinaryDictIOUtils.getDictionaryFileHeader(file, 0, file.length());
+ } catch (UnsupportedFormatException e) {
+ return null;
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
+ private static DictionaryInfo createDictionaryInfoFromFileAddress(
+ final AssetFileAddress fileAddress) {
+ final FileHeader header = BinaryDictIOUtils.getDictionaryFileHeaderOrNull(
+ new File(fileAddress.mFilename), fileAddress.mOffset, fileAddress.mLength);
+ final String id = header.getId();
+ final Locale locale = LocaleUtils.constructLocaleFromString(header.getLocaleString());
+ final String description = header.getDescription();
+ final String version = header.getVersion();
+ return new DictionaryInfo(id, locale, description, fileAddress, Integer.parseInt(version));
+ }
+
+ private static void addOrUpdateDictInfo(final ArrayList<DictionaryInfo> dictList,
+ final DictionaryInfo newElement) {
+ for (final DictionaryInfo info : dictList) {
+ if (info.mLocale.equals(newElement.mLocale)) {
+ if (newElement.mVersion <= info.mVersion) {
+ return;
+ }
+ dictList.remove(info);
+ }
+ }
+ dictList.add(newElement);
+ }
+
+ public static ArrayList<DictionaryInfo> getCurrentDictionaryFileNameAndVersionInfo(
+ final Context context) {
+ final ArrayList<DictionaryInfo> dictList = CollectionUtils.newArrayList();
+
+ // Retrieve downloaded dictionaries
+ final File[] directoryList = getCachedDirectoryList(context);
+ if (null != directoryList) {
+ for (final File directory : directoryList) {
+ final String localeString = getWordListIdFromFileName(directory.getName());
+ File[] dicts = BinaryDictionaryGetter.getCachedWordLists(localeString, context);
+ for (final File dict : dicts) {
+ final String wordListId = getWordListIdFromFileName(dict.getName());
+ if (!DictionaryInfoUtils.isMainWordListId(wordListId)) continue;
+ final Locale locale = LocaleUtils.constructLocaleFromString(localeString);
+ final AssetFileAddress fileAddress = AssetFileAddress.makeFromFile(dict);
+ final DictionaryInfo dictionaryInfo =
+ createDictionaryInfoFromFileAddress(fileAddress);
+ // Protect against cases of a less-specific dictionary being found, like an
+ // en dictionary being used for an en_US locale. In this case, the en dictionary
+ // should be used for en_US but discounted for listing purposes.
+ if (!dictionaryInfo.mLocale.equals(locale)) continue;
+ addOrUpdateDictInfo(dictList, dictionaryInfo);
+ }
+ }
+ }
+
+ // Retrieve files from assets
+ final Resources resources = context.getResources();
+ final AssetManager assets = resources.getAssets();
+ for (final String localeString : assets.getLocales()) {
+ final Locale locale = LocaleUtils.constructLocaleFromString(localeString);
+ final int resourceId =
+ DictionaryInfoUtils.getMainDictionaryResourceIdIfAvailableForLocale(
+ context.getResources(), locale);
+ if (0 == resourceId) continue;
+ final AssetFileAddress fileAddress =
+ BinaryDictionaryGetter.loadFallbackResource(context, resourceId);
+ final DictionaryInfo dictionaryInfo = createDictionaryInfoFromFileAddress(fileAddress);
+ // Protect against cases of a less-specific dictionary being found, like an
+ // en dictionary being used for an en_US locale. In this case, the en dictionary
+ // should be used for en_US but discounted for listing purposes.
+ if (!dictionaryInfo.mLocale.equals(locale)) continue;
+ addOrUpdateDictInfo(dictList, dictionaryInfo);
+ }
+
+ return dictList;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java b/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java
index f2f3fbded..a8513ff45 100644
--- a/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java
+++ b/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java
index b93c17f11..97dc6a8ac 100644
--- a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java
@@ -1,15 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -51,10 +53,9 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
private static boolean DEBUG = false;
/**
- * The maximum length of a word in this dictionary. This is the same value as the binary
- * dictionary.
+ * The maximum length of a word in this dictionary.
*/
- protected static final int MAX_WORD_LENGTH = BinaryDictionary.MAX_WORD_LENGTH;
+ protected static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH;
/**
* A static map of locks, each of which controls access to a single binary dictionary file. They
@@ -198,7 +199,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo) {
+ final String prevWord, final ProximityInfo proximityInfo) {
asyncReloadDictionaryIfRequired();
if (mLocalDictionaryController.tryLock()) {
try {
@@ -213,12 +214,12 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
}
@Override
- public boolean isValidWord(final CharSequence word) {
+ public boolean isValidWord(final String word) {
asyncReloadDictionaryIfRequired();
return isValidWordInner(word);
}
- protected boolean isValidWordInner(final CharSequence word) {
+ protected boolean isValidWordInner(final String word) {
if (mLocalDictionaryController.tryLock()) {
try {
return isValidWordLocked(word);
@@ -229,17 +230,17 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
return false;
}
- protected boolean isValidWordLocked(final CharSequence word) {
+ protected boolean isValidWordLocked(final String word) {
if (mBinaryDictionary == null) return false;
return mBinaryDictionary.isValidWord(word);
}
- protected boolean isValidBigram(final CharSequence word1, final CharSequence word2) {
+ protected boolean isValidBigram(final String word1, final String word2) {
if (mBinaryDictionary == null) return false;
return mBinaryDictionary.isValidBigram(word1, word2);
}
- protected boolean isValidBigramInner(final CharSequence word1, final CharSequence word2) {
+ protected boolean isValidBigramInner(final String word1, final String word2) {
if (mLocalDictionaryController.tryLock()) {
try {
return isValidBigramLocked(word1, word2);
@@ -250,7 +251,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
return false;
}
- protected boolean isValidBigramLocked(final CharSequence word1, final CharSequence word2) {
+ protected boolean isValidBigramLocked(final String word1, final String word2) {
if (mBinaryDictionary == null) return false;
return mBinaryDictionary.isValidBigram(word1, word2);
}
@@ -280,9 +281,8 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
final long length = file.length();
// Build the new binary dictionary
- final BinaryDictionary newBinaryDictionary =
- new BinaryDictionary(mContext, filename, 0, length, true /* useFullEditDistance */,
- null, mDictType);
+ final BinaryDictionary newBinaryDictionary = new BinaryDictionary(filename, 0, length,
+ true /* useFullEditDistance */, null, mDictType);
if (mBinaryDictionary != null) {
// Ensure all threads accessing the current dictionary have finished before swapping in
@@ -321,9 +321,9 @@ abstract public class ExpandableBinaryDictionary extends Dictionary {
tempFile.renameTo(file);
clearFusionDictionary();
} catch (IOException e) {
- Log.e(TAG, "IO exception while writing file: " + e);
+ Log.e(TAG, "IO exception while writing file", e);
} catch (UnsupportedFormatException e) {
- Log.e(TAG, "Unsupported format: " + e);
+ Log.e(TAG, "Unsupported format", e);
} finally {
if (out != null) {
try {
diff --git a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java
index 8cdc2a0af..ae2ee577f 100644
--- a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java
+++ b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java
@@ -19,7 +19,6 @@ package com.android.inputmethod.latin;
import android.content.Context;
import android.text.TextUtils;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.UserHistoryForgettingCurveUtils.ForgettingCurveParams;
@@ -32,12 +31,16 @@ import java.util.LinkedList;
* be searched for suggestions and valid words.
*/
public class ExpandableDictionary extends Dictionary {
+ /**
+ * The weight to give to a word if it's length is the same as the number of typed characters.
+ */
+ private static final int FULL_WORD_SCORE_MULTIPLIER = 2;
// 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[BinaryDictionary.MAX_WORD_LENGTH];
+ private char[] mWordBuilder = new char[Constants.Dictionary.MAX_WORD_LENGTH];
private int mMaxDepth;
private int mInputLength;
@@ -69,7 +72,7 @@ public class ExpandableDictionary extends Dictionary {
mData = new Node[INCREMENT];
}
- void add(Node n) {
+ void add(final Node n) {
if (mLength + 1 > mData.length) {
Node[] tempData = new Node[mLength + INCREMENT];
if (mLength > 0) {
@@ -155,7 +158,7 @@ public class ExpandableDictionary extends Dictionary {
super(dictType);
mContext = context;
clearDictionary();
- mCodes = new int[BinaryDictionary.MAX_WORD_LENGTH][];
+ mCodes = new int[Constants.Dictionary.MAX_WORD_LENGTH][];
}
public void loadDictionary() {
@@ -172,7 +175,7 @@ public class ExpandableDictionary extends Dictionary {
}
}
- public void setRequiresReload(boolean reload) {
+ public void setRequiresReload(final boolean reload) {
synchronized (mUpdatingLock) {
mRequiresReload = reload;
}
@@ -192,18 +195,18 @@ public class ExpandableDictionary extends Dictionary {
}
public int getMaxWordLength() {
- return BinaryDictionary.MAX_WORD_LENGTH;
+ return Constants.Dictionary.MAX_WORD_LENGTH;
}
public void addWord(final String word, final String shortcutTarget, final int frequency) {
- if (word.length() >= BinaryDictionary.MAX_WORD_LENGTH) {
+ if (word.length() >= Constants.Dictionary.MAX_WORD_LENGTH) {
return;
}
addWordRec(mRoots, word, 0, shortcutTarget, frequency, null);
}
- private void addWordRec(NodeArray children, final String word, final int depth,
- final String shortcutTarget, final int frequency, Node parentNode) {
+ private void addWordRec(final NodeArray children, final String word, final int depth,
+ final String shortcutTarget, final int frequency, final Node parentNode) {
final int wordLength = word.length();
if (wordLength <= depth) return;
final char c = word.charAt(depth);
@@ -248,10 +251,10 @@ public class ExpandableDictionary extends Dictionary {
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo) {
+ final String prevWord, final ProximityInfo proximityInfo) {
if (reloadDictionaryIfRequired()) return null;
if (composer.size() > 1) {
- if (composer.size() >= BinaryDictionary.MAX_WORD_LENGTH) {
+ if (composer.size() >= Constants.Dictionary.MAX_WORD_LENGTH) {
return null;
}
final ArrayList<SuggestedWordInfo> suggestions =
@@ -267,8 +270,7 @@ public class ExpandableDictionary extends Dictionary {
// This reloads the dictionary if required, and returns whether it's currently updating its
// contents or not.
- // @VisibleForTesting
- boolean reloadDictionaryIfRequired() {
+ private boolean reloadDictionaryIfRequired() {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
@@ -277,7 +279,7 @@ public class ExpandableDictionary extends Dictionary {
}
protected ArrayList<SuggestedWordInfo> getWordsInner(final WordComposer codes,
- final CharSequence prevWordForBigrams, final ProximityInfo proximityInfo) {
+ final String prevWordForBigrams, final ProximityInfo proximityInfo) {
final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList();
mInputLength = codes.size();
if (mCodes.length < mInputLength) mCodes = new int[mInputLength][];
@@ -305,7 +307,7 @@ public class ExpandableDictionary extends Dictionary {
}
@Override
- public synchronized boolean isValidWord(CharSequence word) {
+ public synchronized boolean isValidWord(final String word) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
@@ -320,7 +322,7 @@ public class ExpandableDictionary extends Dictionary {
return (node == null) ? false : !node.mShortcutOnly;
}
- protected boolean removeBigram(String word1, String word2) {
+ protected boolean removeBigram(final String word1, final String word2) {
// Refer to addOrSetBigram() about word1.toLowerCase()
final Node firstWord = searchWord(mRoots, word1.toLowerCase(), 0, null);
final Node secondWord = searchWord(mRoots, word2, 0, null);
@@ -345,13 +347,13 @@ public class ExpandableDictionary extends Dictionary {
/**
* Returns the word's frequency or -1 if not found
*/
- protected int getWordFrequency(CharSequence word) {
+ protected int getWordFrequency(final String word) {
// Case-sensitive search
final Node node = searchNode(mRoots, word, 0, word.length());
return (node == null) ? -1 : node.mFrequency;
}
- protected NextWord getBigramWord(String word1, String word2) {
+ protected NextWord getBigramWord(final String word1, final String word2) {
// Refer to addOrSetBigram() about word1.toLowerCase()
final Node firstWord = searchWord(mRoots, word1.toLowerCase(), 0, null);
final Node secondWord = searchWord(mRoots, word2, 0, null);
@@ -368,7 +370,8 @@ public class ExpandableDictionary extends Dictionary {
return null;
}
- private static int computeSkippedWordFinalFreq(int freq, int snr, int inputLength) {
+ private static int computeSkippedWordFinalFreq(final int freq, final int snr,
+ final int inputLength) {
// The computation itself makes sense for >= 2, but the == 2 case returns 0
// anyway so we may as well test against 3 instead and return the constant
if (inputLength >= 3) {
@@ -431,9 +434,9 @@ public class ExpandableDictionary extends Dictionary {
* @param suggestions the list in which to add suggestions
*/
// TODO: Share this routine with the native code for BinaryDictionary
- protected void getWordsRec(NodeArray roots, final WordComposer codes, final char[] word,
- final int depth, final boolean completion, int snr, int inputIndex, int skipPos,
- final ArrayList<SuggestedWordInfo> suggestions) {
+ protected void getWordsRec(final NodeArray roots, final WordComposer codes, final char[] word,
+ final int depth, final boolean completion, final int snr, final int inputIndex,
+ final int skipPos, final ArrayList<SuggestedWordInfo> suggestions) {
final int count = roots.mLength;
final int codeSize = mInputLength;
// Optimization: Prune out words that are too long compared to how much was typed.
@@ -472,8 +475,8 @@ public class ExpandableDictionary extends Dictionary {
getWordsRec(children, codes, word, depth + 1, true, snr, inputIndex,
skipPos, suggestions);
}
- } else if ((c == Keyboard.CODE_SINGLE_QUOTE
- && currentChars[0] != Keyboard.CODE_SINGLE_QUOTE) || depth == skipPos) {
+ } else if ((c == Constants.CODE_SINGLE_QUOTE
+ && currentChars[0] != Constants.CODE_SINGLE_QUOTE) || depth == skipPos) {
// Skip the ' and continue deeper
word[depth] = c;
if (children != null) {
@@ -524,11 +527,13 @@ public class ExpandableDictionary extends Dictionary {
}
}
- public int setBigramAndGetFrequency(String word1, String word2, int frequency) {
+ public int setBigramAndGetFrequency(final String word1, final String word2,
+ final int frequency) {
return setBigramAndGetFrequency(word1, word2, frequency, null /* unused */);
}
- public int setBigramAndGetFrequency(String word1, String word2, ForgettingCurveParams fcp) {
+ public int setBigramAndGetFrequency(final String word1, final String word2,
+ final ForgettingCurveParams fcp) {
return setBigramAndGetFrequency(word1, word2, 0 /* unused */, fcp);
}
@@ -540,8 +545,8 @@ public class ExpandableDictionary extends Dictionary {
* @param fcp an instance of ForgettingCurveParams to use for decay policy
* @return returns the final bigram frequency
*/
- private int setBigramAndGetFrequency(
- String word1, String word2, int frequency, ForgettingCurveParams fcp) {
+ private int setBigramAndGetFrequency(final String word1, final String word2,
+ final int frequency, final ForgettingCurveParams fcp) {
// 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
@@ -572,7 +577,8 @@ public class ExpandableDictionary extends Dictionary {
* Searches for the word and add the word if it does not exist.
* @return Returns the terminal node of the word we are searching for.
*/
- private Node searchWord(NodeArray children, String word, int depth, Node parentNode) {
+ private Node searchWord(final NodeArray children, final String word, final int depth,
+ final Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
@@ -602,38 +608,19 @@ public class ExpandableDictionary extends Dictionary {
return searchWord(childNode.mChildren, word, depth + 1, childNode);
}
- private void runBigramReverseLookUp(final CharSequence previousWord,
+ private void runBigramReverseLookUp(final String previousWord,
final ArrayList<SuggestedWordInfo> suggestions) {
// 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,
+ final Node prevWord = searchNode(mRoots, previousWord.toLowerCase(), 0,
previousWord.length());
if (prevWord != null && prevWord.mNGrams != null) {
reverseLookUp(prevWord.mNGrams, suggestions);
}
}
- /**
- * Used for testing purposes and in the spell checker
- * This function will wait for loading from database to be done
- */
- void waitForDictionaryLoading() {
- while (mUpdatingDictionary) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- //
- }
- }
- }
-
- protected final void blockingReloadDictionaryIfRequired() {
- reloadDictionaryIfRequired();
- waitForDictionaryLoading();
- }
-
// Local to reverseLookUp, but do not allocate each time.
- private final char[] mLookedUpString = new char[BinaryDictionary.MAX_WORD_LENGTH];
+ private final char[] mLookedUpString = new char[Constants.Dictionary.MAX_WORD_LENGTH];
/**
* reverseLookUp retrieves the full word given a list of terminal nodes and adds those words
@@ -641,14 +628,14 @@ public class ExpandableDictionary extends Dictionary {
* @param terminalNodes list of terminal nodes we want to add
* @param suggestions the suggestion collection to add the word to
*/
- private void reverseLookUp(LinkedList<NextWord> terminalNodes,
+ private void reverseLookUp(final LinkedList<NextWord> terminalNodes,
final ArrayList<SuggestedWordInfo> suggestions) {
Node node;
int freq;
for (NextWord nextWord : terminalNodes) {
node = nextWord.getWordNode();
freq = nextWord.getFrequency();
- int index = BinaryDictionary.MAX_WORD_LENGTH;
+ int index = Constants.Dictionary.MAX_WORD_LENGTH;
do {
--index;
mLookedUpString[index] = node.mCode;
@@ -660,7 +647,7 @@ public class ExpandableDictionary extends Dictionary {
// to ignore the word in this case.
if (freq >= 0 && node == null) {
suggestions.add(new SuggestedWordInfo(new String(mLookedUpString, index,
- BinaryDictionary.MAX_WORD_LENGTH - index),
+ Constants.Dictionary.MAX_WORD_LENGTH - index),
freq, SuggestedWordInfo.KIND_CORRECTION, mDictType));
}
}
@@ -714,7 +701,7 @@ public class ExpandableDictionary extends Dictionary {
}
}
- private static char toLowerCase(char c) {
+ private static char toLowerCase(final char c) {
char baseChar = c;
if (c < BASE_CHARS.length) {
baseChar = BASE_CHARS[c];
diff --git a/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java b/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java
new file mode 100644
index 000000000..9f91639a2
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2013 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.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.os.Environment;
+
+import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Locale;
+
+/**
+ * A class to read a local file as a dictionary for debugging purposes.
+ */
+public class ExternalDictionaryGetterForDebug {
+ private static final String SOURCE_FOLDER = Environment.getExternalStorageDirectory().getPath()
+ + "/Download";
+
+ private static String[] findDictionariesInTheDownloadedFolder() {
+ final File[] files = new File(SOURCE_FOLDER).listFiles();
+ final ArrayList<String> eligibleList = CollectionUtils.newArrayList();
+ for (File f : files) {
+ final FileHeader header = DictionaryInfoUtils.getDictionaryFileHeaderOrNull(f);
+ if (null == header) continue;
+ eligibleList.add(f.getName());
+ }
+ return eligibleList.toArray(new String[0]);
+ }
+
+ public static void chooseAndInstallDictionary(final Context context) {
+ final String[] fileNames = findDictionariesInTheDownloadedFolder();
+ if (0 == fileNames.length) {
+ showNoFileDialog(context);
+ } else if (1 == fileNames.length) {
+ askInstallFile(context, fileNames[0]);
+ } else {
+ showChooseFileDialog(context, fileNames);
+ }
+ }
+
+ private static void showNoFileDialog(final Context context) {
+ new AlertDialog.Builder(context)
+ .setMessage(R.string.read_external_dictionary_no_files_message)
+ .setPositiveButton(android.R.string.ok, new OnClickListener() {
+ @Override
+ public void onClick(final DialogInterface dialog, final int which) {
+ dialog.dismiss();
+ }
+ }).create().show();
+ }
+
+ private static void showChooseFileDialog(final Context context, final String[] fileNames) {
+ final AlertDialog.Builder builder = new AlertDialog.Builder(context);
+ builder.setTitle(R.string.read_external_dictionary_multiple_files_title)
+ .setItems(fileNames, new OnClickListener() {
+ @Override
+ public void onClick(final DialogInterface dialog, final int which) {
+ askInstallFile(context, fileNames[which]);
+ }
+ })
+ .create().show();
+ }
+
+ private static void askInstallFile(final Context context, final String fileName) {
+ final File file = new File(SOURCE_FOLDER, fileName.toString());
+ final FileHeader header = DictionaryInfoUtils.getDictionaryFileHeaderOrNull(file);
+ final StringBuilder message = new StringBuilder();
+ final String locale = header.getLocaleString();
+ for (String key : header.mDictionaryOptions.mAttributes.keySet()) {
+ message.append(key + " = " + header.mDictionaryOptions.mAttributes.get(key));
+ message.append("\n");
+ }
+ final String languageName = LocaleUtils.constructLocaleFromString(locale)
+ .getDisplayName(Locale.getDefault());
+ final String title = String.format(
+ context.getString(R.string.read_external_dictionary_confirm_install_message),
+ languageName);
+ new AlertDialog.Builder(context)
+ .setTitle(title)
+ .setMessage(message)
+ .setNegativeButton(android.R.string.cancel, new OnClickListener() {
+ @Override
+ public void onClick(final DialogInterface dialog, final int which) {
+ dialog.dismiss();
+ }
+ }).setPositiveButton(android.R.string.ok, new OnClickListener() {
+ @Override
+ public void onClick(final DialogInterface dialog, final int which) {
+ installFile(context, file, header);
+ dialog.dismiss();
+ }
+ }).create().show();
+ }
+
+ private static void installFile(final Context context, final File file,
+ final FileHeader header) {
+ BufferedOutputStream outputStream = null;
+ File tempFile = null;
+ try {
+ final String locale = header.getLocaleString();
+ // Create the id for a main dictionary for this locale
+ final String id = BinaryDictionaryGetter.MAIN_DICTIONARY_CATEGORY
+ + BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR + locale;
+ final String finalFileName = DictionaryInfoUtils.getCacheFileName(id, locale, context);
+ final String tempFileName = BinaryDictionaryGetter.getTempFileName(id, context);
+ tempFile = new File(tempFileName);
+ tempFile.delete();
+ outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
+ final BufferedInputStream bufferedStream = new BufferedInputStream(
+ new FileInputStream(file));
+ BinaryDictionaryFileDumper.checkMagicAndCopyFileTo(bufferedStream, outputStream);
+ outputStream.flush();
+ final File finalFile = new File(finalFileName);
+ finalFile.delete();
+ if (!tempFile.renameTo(finalFile)) {
+ throw new IOException("Can't move the file to its final name");
+ }
+ } catch (IOException e) {
+ // There was an error: show a dialog
+ new AlertDialog.Builder(context)
+ .setTitle(R.string.error)
+ .setMessage(e.toString())
+ .setPositiveButton(android.R.string.ok, new OnClickListener() {
+ @Override
+ public void onClick(final DialogInterface dialog, final int which) {
+ dialog.dismiss();
+ }
+ }).create().show();
+ return;
+ } finally {
+ try {
+ if (null != outputStream) outputStream.close();
+ if (null != tempFile) tempFile.delete();
+ } catch (IOException e) {
+ // Don't do anything
+ }
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/FileTransforms.java b/java/src/com/android/inputmethod/latin/FileTransforms.java
index 09cf23a9b..692f3c7c1 100644
--- a/java/src/com/android/inputmethod/latin/FileTransforms.java
+++ b/java/src/com/android/inputmethod/latin/FileTransforms.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/ImfUtils.java b/java/src/com/android/inputmethod/latin/ImfUtils.java
deleted file mode 100644
index 2674e4575..000000000
--- a/java/src/com/android/inputmethod/latin/ImfUtils.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2012 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 static com.android.inputmethod.latin.Constants.Subtype.KEYBOARD_MODE;
-
-import android.content.Context;
-import android.view.inputmethod.InputMethodInfo;
-import android.view.inputmethod.InputMethodManager;
-import android.view.inputmethod.InputMethodSubtype;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Utility class for Input Method Framework
- */
-public final class ImfUtils {
- private ImfUtils() {
- // This utility class is not publicly instantiable.
- }
-
- private static InputMethodManager sInputMethodManager;
-
- public static InputMethodManager getInputMethodManager(Context context) {
- if (sInputMethodManager == null) {
- sInputMethodManager = (InputMethodManager)context.getSystemService(
- Context.INPUT_METHOD_SERVICE);
- }
- return sInputMethodManager;
- }
-
- private static InputMethodInfo sInputMethodInfoOfThisIme;
-
- public static InputMethodInfo getInputMethodInfoOfThisIme(Context context) {
- if (sInputMethodInfoOfThisIme == null) {
- final InputMethodManager imm = getInputMethodManager(context);
- final String packageName = context.getPackageName();
- for (final InputMethodInfo imi : imm.getInputMethodList()) {
- if (imi.getPackageName().equals(packageName))
- return imi;
- }
- throw new RuntimeException("Can not find input method id for " + packageName);
- }
- return sInputMethodInfoOfThisIme;
- }
-
- public static String getInputMethodIdOfThisIme(Context context) {
- return getInputMethodInfoOfThisIme(context).getId();
- }
-
- public static boolean checkIfSubtypeBelongsToThisImeAndEnabled(Context context,
- InputMethodSubtype ims) {
- final InputMethodInfo myImi = getInputMethodInfoOfThisIme(context);
- final InputMethodManager imm = getInputMethodManager(context);
- // TODO: Cache all subtypes of this IME for optimization
- final List<InputMethodSubtype> subtypes = imm.getEnabledInputMethodSubtypeList(myImi, true);
- for (final InputMethodSubtype subtype : subtypes) {
- if (subtype.equals(ims)) {
- return true;
- }
- }
- return false;
- }
-
- public static boolean checkIfSubtypeBelongsToThisIme(Context context,
- InputMethodSubtype ims) {
- final InputMethodInfo myImi = getInputMethodInfoOfThisIme(context);
- final int count = myImi.getSubtypeCount();
- for (int i = 0; i < count; i++) {
- final InputMethodSubtype subtype = myImi.getSubtypeAt(i);
- if (subtype.equals(ims)) {
- return true;
- }
- }
- return false;
- }
-
- public static InputMethodSubtype getCurrentInputMethodSubtype(Context context,
- InputMethodSubtype defaultSubtype) {
- final InputMethodManager imm = getInputMethodManager(context);
- final InputMethodSubtype currentSubtype = imm.getCurrentInputMethodSubtype();
- return (currentSubtype != null) ? currentSubtype : defaultSubtype;
- }
-
- public static boolean hasMultipleEnabledIMEsOrSubtypes(Context context,
- final boolean shouldIncludeAuxiliarySubtypes) {
- final InputMethodManager imm = getInputMethodManager(context);
- final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList();
- return hasMultipleEnabledSubtypes(context, shouldIncludeAuxiliarySubtypes, enabledImis);
- }
-
- public static boolean hasMultipleEnabledSubtypesInThisIme(Context context,
- final boolean shouldIncludeAuxiliarySubtypes) {
- final InputMethodInfo myImi = getInputMethodInfoOfThisIme(context);
- final List<InputMethodInfo> imiList = Collections.singletonList(myImi);
- return hasMultipleEnabledSubtypes(context, shouldIncludeAuxiliarySubtypes, imiList);
- }
-
- private static boolean hasMultipleEnabledSubtypes(Context context,
- final boolean shouldIncludeAuxiliarySubtypes, List<InputMethodInfo> imiList) {
- final InputMethodManager imm = getInputMethodManager(context);
-
- // Number of the filtered IMEs
- int filteredImisCount = 0;
-
- for (InputMethodInfo imi : imiList) {
- // We can return true immediately after we find two or more filtered IMEs.
- if (filteredImisCount > 1) return true;
- final List<InputMethodSubtype> subtypes =
- imm.getEnabledInputMethodSubtypeList(imi, true);
- // IMEs that have no subtypes should be counted.
- if (subtypes.isEmpty()) {
- ++filteredImisCount;
- continue;
- }
-
- int auxCount = 0;
- for (InputMethodSubtype subtype : subtypes) {
- if (subtype.isAuxiliary()) {
- ++auxCount;
- }
- }
- final int nonAuxCount = subtypes.size() - auxCount;
-
- // IMEs that have one or more non-auxiliary subtypes should be counted.
- // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
- // subtypes should be counted as well.
- if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
- ++filteredImisCount;
- continue;
- }
- }
-
- if (filteredImisCount > 1) {
- return true;
- }
- final List<InputMethodSubtype> subtypes = imm.getEnabledInputMethodSubtypeList(null, true);
- int keyboardCount = 0;
- // imm.getEnabledInputMethodSubtypeList(null, true) will return the current IME's
- // both explicitly and implicitly enabled input method subtype.
- // (The current IME should be LatinIME.)
- for (InputMethodSubtype subtype : subtypes) {
- if (KEYBOARD_MODE.equals(subtype.getMode())) {
- ++keyboardCount;
- }
- }
- return keyboardCount > 1;
- }
-
- public static InputMethodSubtype findSubtypeByLocaleAndKeyboardLayoutSet(
- Context context, String localeString, String keyboardLayoutSetName) {
- final InputMethodInfo imi = getInputMethodInfoOfThisIme(context);
- final int count = imi.getSubtypeCount();
- for (int i = 0; i < count; i++) {
- final InputMethodSubtype subtype = imi.getSubtypeAt(i);
- final String layoutName = SubtypeLocale.getKeyboardLayoutSetName(subtype);
- if (localeString.equals(subtype.getLocale())
- && keyboardLayoutSetName.equals(layoutName)) {
- return subtype;
- }
- }
- return null;
- }
-
- public static void setAdditionalInputMethodSubtypes(Context context,
- InputMethodSubtype[] subtypes) {
- final InputMethodManager imm = getInputMethodManager(context);
- final String imiId = getInputMethodIdOfThisIme(context);
- imm.setAdditionalInputMethodSubtypes(imiId, subtypes);
- }
-}
diff --git a/java/src/com/android/inputmethod/latin/InputAttributes.java b/java/src/com/android/inputmethod/latin/InputAttributes.java
index 422fc72d3..dd58db575 100644
--- a/java/src/com/android/inputmethod/latin/InputAttributes.java
+++ b/java/src/com/android/inputmethod/latin/InputAttributes.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -117,36 +117,56 @@ public final class InputAttributes {
if (inputClass == InputType.TYPE_CLASS_DATETIME)
Log.i(TAG, " TYPE_CLASS_DATETIME");
Log.i(TAG, "Variation:");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS))
- Log.i(TAG, " TYPE_TEXT_VARIATION_EMAIL_ADDRESS");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT))
- Log.i(TAG, " TYPE_TEXT_VARIATION_EMAIL_SUBJECT");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_FILTER))
- Log.i(TAG, " TYPE_TEXT_VARIATION_FILTER");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE))
- Log.i(TAG, " TYPE_TEXT_VARIATION_LONG_MESSAGE");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_NORMAL))
- Log.i(TAG, " TYPE_TEXT_VARIATION_NORMAL");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_PASSWORD))
- Log.i(TAG, " TYPE_TEXT_VARIATION_PASSWORD");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_PERSON_NAME))
- Log.i(TAG, " TYPE_TEXT_VARIATION_PERSON_NAME");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_PHONETIC))
- Log.i(TAG, " TYPE_TEXT_VARIATION_PHONETIC");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS))
- Log.i(TAG, " TYPE_TEXT_VARIATION_POSTAL_ADDRESS");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE))
- Log.i(TAG, " TYPE_TEXT_VARIATION_SHORT_MESSAGE");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_URI))
- Log.i(TAG, " TYPE_TEXT_VARIATION_URI");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD))
- Log.i(TAG, " TYPE_TEXT_VARIATION_VISIBLE_PASSWORD");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT))
- Log.i(TAG, " TYPE_TEXT_VARIATION_WEB_EDIT_TEXT");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS))
- Log.i(TAG, " TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS");
- if (0 != (inputType & InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD))
- Log.i(TAG, " TYPE_TEXT_VARIATION_WEB_PASSWORD");
+ switch (InputType.TYPE_MASK_VARIATION & inputType) {
+ case InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_EMAIL_ADDRESS");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_EMAIL_SUBJECT");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_FILTER:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_FILTER");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_LONG_MESSAGE");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_NORMAL:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_NORMAL");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_PASSWORD:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_PASSWORD");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_PERSON_NAME:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_PERSON_NAME");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_PHONETIC:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_PHONETIC");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_POSTAL_ADDRESS");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_SHORT_MESSAGE");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_URI:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_URI");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_VISIBLE_PASSWORD");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_WEB_EDIT_TEXT");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS");
+ break;
+ case InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD:
+ Log.i(TAG, " TYPE_TEXT_VARIATION_WEB_PASSWORD");
+ break;
+ default:
+ Log.i(TAG, " Unknown variation");
+ break;
+ }
Log.i(TAG, "Flags:");
if (0 != (inputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS))
Log.i(TAG, " TYPE_TEXT_FLAG_NO_SUGGESTIONS");
diff --git a/java/src/com/android/inputmethod/latin/InputPointers.java b/java/src/com/android/inputmethod/latin/InputPointers.java
index 6b48aabb3..81c833000 100644
--- a/java/src/com/android/inputmethod/latin/InputPointers.java
+++ b/java/src/com/android/inputmethod/latin/InputPointers.java
@@ -1,23 +1,28 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.annotations.UsedForTesting;
+
+import android.util.Log;
+
// TODO: This class is not thread-safe.
public final class InputPointers {
+ private static final String TAG = InputPointers.class.getSimpleName();
private final int mDefaultCapacity;
private final ResizableIntArray mXCoordinates;
private final ResizableIntArray mYCoordinates;
@@ -39,7 +44,8 @@ public final class InputPointers {
mTimes.add(index, time);
}
- public void addPointer(int x, int y, int pointerId, int time) {
+ @UsedForTesting
+ void addPointer(int x, int y, int pointerId, int time) {
mXCoordinates.add(x);
mYCoordinates.add(y);
mPointerIds.add(pointerId);
@@ -66,7 +72,8 @@ public final class InputPointers {
* @param startPos the starting index of the pointers in {@code src}.
* @param length the number of pointers to be appended.
*/
- public void append(InputPointers src, int startPos, int length) {
+ @UsedForTesting
+ void append(InputPointers src, int startPos, int length) {
if (length == 0) {
return;
}
@@ -122,6 +129,11 @@ public final class InputPointers {
}
public int[] getTimes() {
+ if (LatinImeLogger.sDBG) {
+ if (!isValidTimeStamps()) {
+ throw new RuntimeException("Time stamps are invalid.");
+ }
+ }
return mTimes.getPrimitiveArray();
}
@@ -130,4 +142,18 @@ public final class InputPointers {
return "size=" + getPointerSize() + " id=" + mPointerIds + " time=" + mTimes
+ " x=" + mXCoordinates + " y=" + mYCoordinates;
}
+
+ private boolean isValidTimeStamps() {
+ final int[] times = mTimes.getPrimitiveArray();
+ for (int i = 1; i < getPointerSize(); ++i) {
+ if (times[i] < times[i - 1]) {
+ // dump
+ for (int j = 0; j < times.length; ++j) {
+ Log.d(TAG, "--- (" + j + ") " + times[j]);
+ }
+ return false;
+ }
+ }
+ return true;
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/InputTypeUtils.java b/java/src/com/android/inputmethod/latin/InputTypeUtils.java
index 9a4503bf4..ecb20144b 100644
--- a/java/src/com/android/inputmethod/latin/InputTypeUtils.java
+++ b/java/src/com/android/inputmethod/latin/InputTypeUtils.java
@@ -1,22 +1,23 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.text.InputType;
+import android.view.inputmethod.EditorInfo;
public final class InputTypeUtils implements InputType {
private static final int WEB_TEXT_PASSWORD_INPUT_TYPE =
@@ -35,6 +36,7 @@ public final class InputTypeUtils implements InputType {
InputType.TYPE_TEXT_VARIATION_URI,
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD,
InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD };
+ public static final int IME_ACTION_CUSTOM_LABEL = EditorInfo.IME_MASK_ACTION + 1;
private InputTypeUtils() {
// This utility class is not publicly instantiable.
@@ -102,4 +104,15 @@ public final class InputTypeUtils implements InputType {
}
return true;
}
+
+ public static int getImeOptionsActionIdFromEditorInfo(final EditorInfo editorInfo) {
+ if ((editorInfo.imeOptions & EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
+ return EditorInfo.IME_ACTION_NONE;
+ } else if (editorInfo.actionLabel != null) {
+ return IME_ACTION_CUSTOM_LABEL;
+ } else {
+ // Note: this is different from editorInfo.actionId, hence "ImeOptionsActionId"
+ return editorInfo.imeOptions & EditorInfo.IME_MASK_ACTION;
+ }
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/InputView.java b/java/src/com/android/inputmethod/latin/InputView.java
index d7595bfbe..5359c8185 100644
--- a/java/src/com/android/inputmethod/latin/InputView.java
+++ b/java/src/com/android/inputmethod/latin/InputView.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/IntentUtils.java b/java/src/com/android/inputmethod/latin/IntentUtils.java
new file mode 100644
index 000000000..d175af504
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/IntentUtils.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 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.Intent;
+import android.text.TextUtils;
+
+public final class IntentUtils {
+ 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 IntentUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ public static Intent getInputLanguageSelectionIntent(final String inputMethodId,
+ final int flagsForSubtypeSettings) {
+ // Refer to android.provider.Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS
+ final String action = INPUT_METHOD_SUBTYPE_SETTINGS;
+ final Intent intent = new Intent(action);
+ if (!TextUtils.isEmpty(inputMethodId)) {
+ intent.putExtra(EXTRA_INPUT_METHOD_ID, inputMethodId);
+ }
+ if (flagsForSubtypeSettings > 0) {
+ intent.setFlags(flagsForSubtypeSettings);
+ }
+ return intent;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/LastComposedWord.java b/java/src/com/android/inputmethod/latin/LastComposedWord.java
index 94cdc9b85..826dc11e7 100644
--- a/java/src/com/android/inputmethod/latin/LastComposedWord.java
+++ b/java/src/com/android/inputmethod/latin/LastComposedWord.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -44,19 +44,22 @@ public final class LastComposedWord {
public final String mTypedWord;
public final String mCommittedWord;
public final String mSeparatorString;
- public final CharSequence mPrevWord;
- public final InputPointers mInputPointers = new InputPointers(BinaryDictionary.MAX_WORD_LENGTH);
+ public final String mPrevWord;
+ public final int mCapitalizedMode;
+ public final InputPointers mInputPointers =
+ new InputPointers(Constants.Dictionary.MAX_WORD_LENGTH);
private boolean mActive;
public static final LastComposedWord NOT_A_COMPOSED_WORD =
- new LastComposedWord(null, null, "", "", NOT_A_SEPARATOR, null);
+ new LastComposedWord(null, null, "", "", NOT_A_SEPARATOR, null,
+ WordComposer.CAPS_MODE_OFF);
// Warning: this is using the passed objects as is and fully expects them to be
// immutable. Do not fiddle with their contents after you passed them to this constructor.
public LastComposedWord(final int[] primaryKeyCodes, final InputPointers inputPointers,
- final String typedWord, final String committedWord,
- final String separatorString, final CharSequence prevWord) {
+ final String typedWord, final String committedWord, final String separatorString,
+ final String prevWord, final int capitalizedMode) {
mPrimaryKeyCodes = primaryKeyCodes;
if (inputPointers != null) {
mInputPointers.copy(inputPointers);
@@ -66,6 +69,7 @@ public final class LastComposedWord {
mSeparatorString = separatorString;
mActive = true;
mPrevWord = prevWord;
+ mCapitalizedMode = capitalizedMode;
}
public void deactivate() {
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index e2a76a456..bb7e2d1c2 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2008 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
+ * 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
+ * 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.
+ * 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;
@@ -35,6 +35,7 @@ import android.graphics.Rect;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.ConnectivityManager;
+import android.os.Build.VERSION_CODES;
import android.os.Debug;
import android.os.Handler;
import android.os.HandlerThread;
@@ -60,18 +61,16 @@ import android.view.inputmethod.InputMethodSubtype;
import com.android.inputmethod.accessibility.AccessibilityUtils;
import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
-import com.android.inputmethod.compat.CompatUtils;
-import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.compat.InputMethodServiceCompatUtils;
import com.android.inputmethod.compat.SuggestionSpanUtils;
+import com.android.inputmethod.event.EventInterpreter;
import com.android.inputmethod.keyboard.KeyDetector;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
-import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.MainKeyboardView;
-import com.android.inputmethod.latin.LocaleUtils.RunInLocale;
import com.android.inputmethod.latin.Utils.Stats;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.latin.suggestions.SuggestionStripView;
@@ -81,6 +80,7 @@ import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Locale;
+import java.util.TreeSet;
/**
* Input method implementation for Qwerty'ish keyboard.
@@ -126,22 +126,25 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// Current space state of the input method. This can be any of the above constants.
private int mSpaceState;
- private SettingsValues mCurrentSettings;
+ private final Settings mSettings;
private View mExtractArea;
private View mKeyPreviewBackingView;
private View mSuggestionsContainer;
private SuggestionStripView mSuggestionStripView;
- /* package for tests */ Suggest mSuggest;
+ // Never null
+ private SuggestedWords mSuggestedWords = SuggestedWords.EMPTY;
+ @UsedForTesting Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private ApplicationInfo mTargetApplicationInfo;
- private InputMethodManagerCompatWrapper mImm;
- private Resources mResources;
- private SharedPreferences mPrefs;
- /* package for tests */ final KeyboardSwitcher mKeyboardSwitcher;
+ private RichInputMethodManager mRichImm;
+ @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher;
private final SubtypeSwitcher mSubtypeSwitcher;
private final SubtypeState mSubtypeState = new SubtypeState();
+ // At start, create a default event interpreter that does nothing by passing it no decoder spec.
+ // The event interpreter should never be null.
+ private EventInterpreter mEventInterpreter = new EventInterpreter(this);
private boolean mIsMainDictionaryAvailable;
private UserBinaryDictionary mUserDictionary;
@@ -164,18 +167,19 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
private boolean mExpectingUpdateSelection;
private int mDeleteCount;
private long mLastKeyTime;
-
- private AudioAndHapticFeedbackManager mFeedbackManager;
+ private TreeSet<Long> mCurrentlyPressedHardwareKeys = CollectionUtils.newTreeSet();
// Member variables for remembering the current device orientation.
private int mDisplayOrientation;
// Object for reacting to adding/removing a dictionary pack.
+ // TODO: The experimental version is not supported by the Dictionary Pack Service yet.
private BroadcastReceiver mDictionaryPackInstallReceiver =
- new DictionaryPackInstallBroadcastReceiver(this);
+ ProductionFlag.IS_EXPERIMENTAL
+ ? null : new DictionaryPackInstallBroadcastReceiver(this);
// Keeps track of most recently inserted text (multi-character key) for reverting
- private CharSequence mEnteredText;
+ private String mEnteredText;
private boolean mIsAutoCorrectionIndicatorOn;
@@ -195,8 +199,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
private int mDelayUpdateSuggestions;
private int mDelayUpdateShiftState;
- private long mDoubleSpacesTurnIntoPeriodTimeout;
- private long mDoubleSpaceTimerStart;
+ private long mDoubleSpacePeriodTimeout;
+ private long mDoubleSpacePeriodTimerStart;
public UIHandler(final LatinIME outerInstance) {
super(outerInstance);
@@ -208,8 +212,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
res.getInteger(R.integer.config_delay_update_suggestions);
mDelayUpdateShiftState =
res.getInteger(R.integer.config_delay_update_shift_state);
- mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
- R.integer.config_double_spaces_turn_into_period_timeout);
+ mDoubleSpacePeriodTimeout =
+ res.getInteger(R.integer.config_double_space_period_timeout);
}
@Override
@@ -260,17 +264,17 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
.sendToTarget();
}
- public void startDoubleSpacesTimer() {
- mDoubleSpaceTimerStart = SystemClock.uptimeMillis();
+ public void startDoubleSpacePeriodTimer() {
+ mDoubleSpacePeriodTimerStart = SystemClock.uptimeMillis();
}
- public void cancelDoubleSpacesTimer() {
- mDoubleSpaceTimerStart = 0;
+ public void cancelDoubleSpacePeriodTimer() {
+ mDoubleSpacePeriodTimerStart = 0;
}
- public boolean isAcceptingDoubleSpaces() {
- return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart
- < mDoubleSpacesTurnIntoPeriodTimeout;
+ public boolean isAcceptingDoubleSpacePeriod() {
+ return SystemClock.uptimeMillis() - mDoubleSpacePeriodTimerStart
+ < mDoubleSpacePeriodTimeout;
}
// Working variables for the following methods.
@@ -375,9 +379,9 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mCurrentSubtypeUsed = true;
}
- public void switchSubtype(final IBinder token, final InputMethodManagerCompatWrapper imm,
- final Context context) {
- final InputMethodSubtype currentSubtype = imm.getCurrentInputMethodSubtype();
+ public void switchSubtype(final IBinder token, final RichInputMethodManager richImm) {
+ final InputMethodSubtype currentSubtype = richImm.getInputMethodManager()
+ .getCurrentInputMethodSubtype();
final InputMethodSubtype lastActiveSubtype = mLastActiveSubtype;
final boolean currentSubtypeUsed = mCurrentSubtypeUsed;
if (currentSubtypeUsed) {
@@ -385,18 +389,18 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mCurrentSubtypeUsed = false;
}
if (currentSubtypeUsed
- && ImfUtils.checkIfSubtypeBelongsToThisImeAndEnabled(context, lastActiveSubtype)
+ && richImm.checkIfSubtypeBelongsToThisImeAndEnabled(lastActiveSubtype)
&& !currentSubtype.equals(lastActiveSubtype)) {
- final String id = ImfUtils.getInputMethodIdOfThisIme(context);
- imm.setInputMethodAndSubtype(token, id, lastActiveSubtype);
+ richImm.setInputMethodAndSubtype(token, lastActiveSubtype);
return;
}
- imm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
+ richImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
}
}
public LatinIME() {
super();
+ mSettings = Settings.getInstance();
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mIsHardwareAcceleratedDrawingEnabled =
@@ -406,33 +410,27 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
@Override
public void onCreate() {
- final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
- mPrefs = prefs;
- LatinImeLogger.init(this, prefs);
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.getInstance().init(this, prefs);
- }
- InputMethodManagerCompatWrapper.init(this);
+ Settings.init(this);
+ LatinImeLogger.init(this);
+ RichInputMethodManager.init(this);
+ mRichImm = RichInputMethodManager.getInstance();
SubtypeSwitcher.init(this);
- KeyboardSwitcher.init(this, prefs);
+ KeyboardSwitcher.init(this);
+ AudioAndHapticFeedbackManager.init(this);
AccessibilityUtils.init(this);
super.onCreate();
- mImm = InputMethodManagerCompatWrapper.getInstance();
mHandler.onCreate();
DEBUG = LatinImeLogger.sDBG;
- final Resources res = getResources();
- mResources = res;
-
loadSettings();
-
- ImfUtils.setAdditionalInputMethodSubtypes(this, mCurrentSettings.getAdditionalSubtypes());
-
initSuggest();
- mDisplayOrientation = res.getConfiguration().orientation;
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.getInstance().init(this, mKeyboardSwitcher);
+ }
+ mDisplayOrientation = getResources().getConfiguration().orientation;
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
@@ -441,34 +439,28 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
- final IntentFilter packageFilter = new IntentFilter();
- packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
- packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
- packageFilter.addDataScheme(SCHEME_PACKAGE);
- registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
+ // TODO: The experimental version is not supported by the Dictionary Pack Service yet.
+ if (!ProductionFlag.IS_EXPERIMENTAL) {
+ 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);
+ final IntentFilter newDictFilter = new IntentFilter();
+ newDictFilter.addAction(
+ DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
+ registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
+ }
}
// Has to be package-visible for unit tests
- /* package for test */
+ @UsedForTesting
void loadSettings() {
- // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
- // is not guaranteed. It may even be called at the same time on a different thread.
- if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale();
final InputAttributes inputAttributes =
new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode());
- final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() {
- @Override
- protected SettingsValues job(Resources res) {
- return new SettingsValues(mPrefs, inputAttributes, LatinIME.this);
- }
- };
- mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale());
- mFeedbackManager = new AudioAndHapticFeedbackManager(this, mCurrentSettings);
+ mSettings.loadSettings(locale, inputAttributes);
resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary());
}
@@ -495,8 +487,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
mSuggest = new Suggest(this /* Context */, subtypeLocale,
this /* SuggestInitializationListener */);
- if (mCurrentSettings.mCorrectionEnabled) {
- mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
+ if (mSettings.getCurrent().mCorrectionEnabled) {
+ mSuggest.setAutoCorrectionThreshold(mSettings.getCurrent().mAutoCorrectionThreshold);
}
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
@@ -510,10 +502,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
resetContactsDictionary(oldContactsDictionary);
- // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
- // is not guaranteed. It may even be called at the same time on a different thread.
- if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
- mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs);
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
+ mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, prefs);
mSuggest.setUserHistoryDictionary(mUserHistoryDictionary);
}
@@ -526,7 +516,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
* @param oldContactsDictionary an optional dictionary to use, or null
*/
private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) {
- final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict);
+ final boolean shouldSetDictionary =
+ (null != mSuggest && mSettings.getCurrent().mUseContactsDict);
final ContactsBinaryDictionary dictionaryToUse;
if (!shouldSetDictionary) {
@@ -570,8 +561,12 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mSuggest.close();
mSuggest = null;
}
+ mSettings.onDestroy();
unregisterReceiver(mReceiver);
- unregisterReceiver(mDictionaryPackInstallReceiver);
+ // TODO: The experimental version is not supported by the Dictionary Pack Service yet.
+ if (!ProductionFlag.IS_EXPERIMENTAL) {
+ unregisterReceiver(mDictionaryPackInstallReceiver);
+ }
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
@@ -579,10 +574,6 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
@Override
public void onConfigurationChanged(final Configuration conf) {
- // System locale has been changed. Needs to reload keyboard.
- if (mSubtypeSwitcher.onConfigurationChanged(conf, this)) {
- loadKeyboard();
- }
// If orientation changed while predicting, commit the change
if (mDisplayOrientation != conf.orientation) {
mDisplayOrientation = conf.orientation;
@@ -648,7 +639,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
- mSubtypeSwitcher.updateSubtype(subtype);
+ mSubtypeSwitcher.onSubtypeChanged(subtype);
loadKeyboard();
}
@@ -661,6 +652,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
+ final SettingsValues currentSettings = mSettings.getCurrent();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
@@ -681,7 +673,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
+ ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, prefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
@@ -713,18 +706,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
- final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
+ final boolean inputTypeChanged = !currentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
- final boolean currentSubtypeEnabled = mSubtypeSwitcher
- .updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
- if (!currentSubtypeEnabled) {
- // Current subtype is disabled. Needs to update subtype and keyboard.
- final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
- this, mSubtypeSwitcher.getNoLanguageSubtype());
- mSubtypeSwitcher.updateSubtype(newSubtype);
- loadKeyboard();
- }
+ mSubtypeSwitcher.updateParametersOnStartInputView();
}
// The EditorInfo might have a flag that affects fullscreen mode.
@@ -738,12 +723,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
+ mCurrentlyPressedHardwareKeys.clear();
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
+ mSuggestedWords = SuggestedWords.EMPTY;
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
@@ -751,11 +738,11 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mainKeyboardView.closing();
loadSettings();
- if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
- mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
+ if (mSuggest != null && currentSettings.mCorrectionEnabled) {
+ mSuggest.setAutoCorrectionThreshold(currentSettings.mAutoCorrectionThreshold);
}
- switcher.loadKeyboard(editorInfo, mCurrentSettings);
+ switcher.loadKeyboard(editorInfo, currentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
@@ -773,21 +760,25 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mLastSelectionEnd = editorInfo.initialSelEnd;
mHandler.cancelUpdateSuggestionStrip();
- mHandler.cancelDoubleSpacesTimer();
+ mHandler.cancelDoubleSpacePeriodTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
- mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
- mCurrentSettings.mKeyPreviewPopupDismissDelay);
- mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
- mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
- mCurrentSettings.mGestureFloatingPreviewTextEnabled);
+ mainKeyboardView.setKeyPreviewPopupEnabled(currentSettings.mKeyPreviewPopupOn,
+ currentSettings.mKeyPreviewPopupDismissDelay);
+ mainKeyboardView.setSlidingKeyInputPreviewEnabled(
+ currentSettings.mSlidingKeyInputPreviewEnabled);
+ mainKeyboardView.setGestureHandlingEnabledByUser(
+ currentSettings.mGestureInputEnabled);
+ mainKeyboardView.setGesturePreviewMode(currentSettings.mGesturePreviewTrailEnabled,
+ currentSettings.mGestureFloatingPreviewTextEnabled);
// If we have a user dictionary addition in progress, we should check now if we should
// replace the previously committed string with the word that has actually been added
// to the user dictionary.
if (null != mPositionalInfoForUserDictPendingAddition
&& mPositionalInfoForUserDictPendingAddition.tryReplaceWithActualWord(
- mConnection, editorInfo, mLastSelectionEnd)) {
+ mConnection, editorInfo, mLastSelectionEnd,
+ mSubtypeSwitcher.getCurrentSubtypeLocale())) {
mPositionalInfoForUserDictPendingAddition = null;
}
// If tryReplaceWithActualWord returns false, we don't know what word was
@@ -821,10 +812,6 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
super.onFinishInput();
LatinImeLogger.commit();
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.getInstance().latinIME_onFinishInputInternal();
- }
-
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
@@ -840,6 +827,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestionStrip();
+ resetComposingState(true /* alsoResetLastComposedWord */);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.getInstance().latinIME_onFinishInputViewInternal();
+ }
}
@Override
@@ -938,7 +929,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
*/
@Override
public void onExtractedTextClicked() {
- if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
+ if (mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedTextClicked();
}
@@ -954,7 +945,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
*/
@Override
public void onExtractedCursorMovement(final int dx, final int dy) {
- if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
+ if (mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedCursorMovement(dx, dy);
}
@@ -964,6 +955,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
LatinImeLogger.commit();
mKeyboardSwitcher.onHideWindow();
+ if (AccessibilityUtils.getInstance().isAccessibilityEnabled()) {
+ AccessibleKeyboardViewProxy.getInstance().onHideWindow();
+ }
+
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
@@ -982,7 +977,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
}
}
- if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return;
+ if (!mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) return;
mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
if (applicationSpecifiedCompletions == null) {
clearSuggestionStrip();
@@ -1004,11 +999,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
false /* isPrediction */);
// When in fullscreen mode, show completions generated by the application
final boolean isAutoCorrection = false;
- setSuggestionStrip(suggestedWords, isAutoCorrection);
+ setSuggestedWords(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
- // TODO: is this the right thing to do? What should we auto-correct to in
- // this case? This says to keep whatever the user typed.
- mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
setSuggestionStripShown(true);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions);
@@ -1050,7 +1042,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
final int keyboardHeight = mainKeyboardView.getHeight();
final int suggestionsHeight = mSuggestionsContainer.getHeight();
- final int displayHeight = mResources.getDisplayMetrics().heightPixels;
+ final int displayHeight = getResources().getDisplayMetrics().heightPixels;
final Rect rect = new Rect();
mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect);
final int notificationBarHeight = rect.top;
@@ -1080,12 +1072,13 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0
: mSuggestionsContainer.getHeight();
final int extraHeight = extractHeight + backingHeight + suggestionsHeight;
- int touchY = extraHeight;
+ int visibleTopY = extraHeight;
// Need to set touchable region only if input view is being shown
if (mainKeyboardView.isShown()) {
if (mSuggestionsContainer.getVisibility() == View.VISIBLE) {
- touchY -= suggestionsHeight;
+ visibleTopY -= suggestionsHeight;
}
+ final int touchY = mainKeyboardView.isShowingMoreKeysPanel() ? 0 : visibleTopY;
final int touchWidth = mainKeyboardView.getWidth();
final int touchHeight = mainKeyboardView.getHeight() + extraHeight
// Extend touchable region below the keyboard.
@@ -1093,15 +1086,15 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight);
}
- outInsets.contentTopInsets = touchY;
- outInsets.visibleTopInsets = touchY;
+ outInsets.contentTopInsets = visibleTopY;
+ outInsets.visibleTopInsets = visibleTopY;
}
@Override
public boolean onEvaluateFullscreenMode() {
// Reread resource value here, because this method is called by framework anytime as needed.
final boolean isFullscreenModeAllowed =
- mCurrentSettings.isFullscreenModeAllowed(getResources());
+ Settings.readUseFullscreenMode(getResources());
if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) {
// TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI
// implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI
@@ -1128,10 +1121,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// the composing word, reset the last composed word, tell the inputconnection about it.
private void resetEntireInputState(final int newCursorPosition) {
resetComposingState(true /* alsoResetLastComposedWord */);
- if (mCurrentSettings.mBigramPredictionEnabled) {
+ if (mSettings.getCurrent().mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
- setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
+ setSuggestedWords(mSettings.getCurrent().mSuggestPuncList, false);
}
mConnection.resetCachesUponCursorMove(newCursorPosition);
}
@@ -1144,17 +1137,20 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
private void commitTyped(final String separatorString) {
if (!mWordComposer.isComposingWord()) return;
- final CharSequence typedWord = mWordComposer.getTypedWord();
+ final String typedWord = mWordComposer.getTypedWord();
if (typedWord.length() > 0) {
commitChosenWord(typedWord, LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD,
separatorString);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.getInstance().onWordFinished(typedWord, mWordComposer.isBatchMode());
+ }
}
}
// Called from the KeyboardSwitcher which needs to know auto caps state to display
// the right layout.
public int getCurrentAutoCapsState() {
- if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF;
+ if (!mSettings.getCurrent().mAutoCap) return Constants.TextUtils.CAP_MODE_OFF;
final EditorInfo ei = getCurrentInputEditorInfo();
if (ei == null) return Constants.TextUtils.CAP_MODE_OFF;
@@ -1178,46 +1174,53 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
private void swapSwapperAndSpace() {
- CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0);
+ final CharSequence lastTwo = mConnection.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) {
+ && lastTwo.charAt(0) == Constants.CODE_SPACE) {
mConnection.deleteSurroundingText(2, 0);
- mConnection.commitText(lastTwo.charAt(1) + " ", 1);
+ final String text = lastTwo.charAt(1) + " ";
+ mConnection.commitText(text, 1);
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_swapSwapperAndSpace();
+ ResearchLogger.latinIME_swapSwapperAndSpace(lastTwo, text);
}
mKeyboardSwitcher.updateShiftState();
}
}
- private boolean maybeDoubleSpace() {
- if (!mCurrentSettings.mCorrectionEnabled) return false;
- if (!mHandler.isAcceptingDoubleSpaces()) return false;
+ private boolean maybeDoubleSpacePeriod() {
+ if (!mSettings.getCurrent().mCorrectionEnabled) return false;
+ if (!mSettings.getCurrent().mUseDoubleSpacePeriod) return false;
+ if (!mHandler.isAcceptingDoubleSpacePeriod()) return false;
final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
- && canBeFollowedByPeriod(lastThree.charAt(0))
- && lastThree.charAt(1) == Keyboard.CODE_SPACE
- && lastThree.charAt(2) == Keyboard.CODE_SPACE) {
- mHandler.cancelDoubleSpacesTimer();
+ && canBeFollowedByDoubleSpacePeriod(lastThree.charAt(0))
+ && lastThree.charAt(1) == Constants.CODE_SPACE
+ && lastThree.charAt(2) == Constants.CODE_SPACE) {
+ mHandler.cancelDoubleSpacePeriodTimer();
mConnection.deleteSurroundingText(2, 0);
- mConnection.commitText(". ", 1);
+ final String textToInsert = ". ";
+ mConnection.commitText(textToInsert, 1);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_maybeDoubleSpacePeriod(textToInsert,
+ false /* isBatchMode */);
+ }
mKeyboardSwitcher.updateShiftState();
return true;
}
return false;
}
- private static boolean canBeFollowedByPeriod(final int codePoint) {
+ private static boolean canBeFollowedByDoubleSpacePeriod(final int codePoint) {
// TODO: Check again whether there really ain't a better way to check this.
// TODO: This should probably be language-dependant...
return Character.isLetterOrDigit(codePoint)
- || codePoint == Keyboard.CODE_SINGLE_QUOTE
- || codePoint == Keyboard.CODE_DOUBLE_QUOTE
- || codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
- || codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
- || codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
- || codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
+ || codePoint == Constants.CODE_SINGLE_QUOTE
+ || codePoint == Constants.CODE_DOUBLE_QUOTE
+ || codePoint == Constants.CODE_CLOSING_PARENTHESIS
+ || codePoint == Constants.CODE_CLOSING_SQUARE_BRACKET
+ || codePoint == Constants.CODE_CLOSING_CURLY_BRACKET
+ || codePoint == Constants.CODE_CLOSING_ANGLE_BRACKET;
}
// Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is
@@ -1229,10 +1232,17 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mPositionalInfoForUserDictPendingAddition = null;
return;
}
+ final String wordToEdit;
+ if (CapsModeUtils.isAutoCapsMode(mLastComposedWord.mCapitalizedMode)) {
+ wordToEdit = word.toLowerCase(mSubtypeSwitcher.getCurrentSubtypeLocale());
+ } else {
+ wordToEdit = word;
+ }
mPositionalInfoForUserDictPendingAddition =
new PositionalInfoForUserDictPendingAddition(
- word, mLastSelectionEnd, getCurrentInputEditorInfo());
- mUserDictionary.addWordToUserDictionary(word, 128);
+ wordToEdit, mLastSelectionEnd, getCurrentInputEditorInfo(),
+ mLastComposedWord.mCapitalizedMode);
+ mUserDictionary.addWordToUserDictionary(wordToEdit);
}
public void onWordAddedToUserDictionary(final String newSpelling) {
@@ -1245,7 +1255,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
mPositionalInfoForUserDictPendingAddition.setActualWordBeingAdded(newSpelling);
if (mPositionalInfoForUserDictPendingAddition.tryReplaceWithActualWord(
- mConnection, getCurrentInputEditorInfo(), mLastSelectionEnd)) {
+ mConnection, getCurrentInputEditorInfo(), mLastSelectionEnd,
+ mSubtypeSwitcher.getCurrentSubtypeLocale())) {
mPositionalInfoForUserDictPendingAddition = null;
}
}
@@ -1267,9 +1278,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
if (isShowingOptionDialog()) return false;
switch (requestCode) {
case CODE_SHOW_INPUT_METHOD_PICKER:
- if (ImfUtils.hasMultipleEnabledIMEsOrSubtypes(
- this, true /* include aux subtypes */)) {
- mImm.showInputMethodPicker();
+ if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) {
+ mRichImm.getInputMethodManager().showInputMethodPicker();
return true;
}
return false;
@@ -1281,10 +1291,6 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
- private static int getActionId(final Keyboard keyboard) {
- return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE;
- }
-
private void performEditorAction(final int actionId) {
mConnection.performEditorAction(actionId);
}
@@ -1292,11 +1298,11 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// TODO: Revise the language switch key behavior to make it much smarter and more reasonable.
private void handleLanguageSwitchKey() {
final IBinder token = getWindow().getWindow().getAttributes().token;
- if (mCurrentSettings.mIncludesOtherImesInLanguageSwitchList) {
- mImm.switchToNextInputMethod(token, false /* onlyCurrentIme */);
+ if (mSettings.getCurrent().mIncludesOtherImesInLanguageSwitchList) {
+ mRichImm.switchToNextInputMethod(token, false /* onlyCurrentIme */);
return;
}
- mSubtypeState.switchSubtype(token, mImm, this);
+ mSubtypeState.switchSubtype(token, mRichImm);
}
private void sendDownUpKeyEventForBackwardCompatibility(final int code) {
@@ -1310,20 +1316,18 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
private void sendKeyCodePoint(final int code) {
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_sendKeyCodePoint(code);
+ }
// TODO: Remove this special handling of digit letters.
// For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}.
if (code >= '0' && code <= '9') {
sendDownUpKeyEventForBackwardCompatibility(code - '0' + KeyEvent.KEYCODE_0);
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_sendKeyCodePoint(code);
- }
return;
}
- // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
- // we want to be able to compile against the Ice Cream Sandwich SDK.
- if (Keyboard.CODE_ENTER == code && mTargetApplicationInfo != null
- && mTargetApplicationInfo.targetSdkVersion < 16) {
+ if (Constants.CODE_ENTER == code && mTargetApplicationInfo != null
+ && mTargetApplicationInfo.targetSdkVersion < VERSION_CODES.JELLY_BEAN) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
@@ -1338,8 +1342,11 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// Implementation of {@link KeyboardActionListener}.
@Override
public void onCodeInput(final int primaryCode, final int x, final int y) {
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_onCodeInput(primaryCode, x, y);
+ }
final long when = SystemClock.uptimeMillis();
- if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
+ if (primaryCode != Constants.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
@@ -1353,115 +1360,147 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
final int spaceState = mSpaceState;
if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false;
- // TODO: Consolidate the double space timer, mLastKeyTime, and the space state.
- if (primaryCode != Keyboard.CODE_SPACE) {
- mHandler.cancelDoubleSpacesTimer();
+ // TODO: Consolidate the double-space period timer, mLastKeyTime, and the space state.
+ if (primaryCode != Constants.CODE_SPACE) {
+ mHandler.cancelDoubleSpacePeriodTimer();
}
boolean didAutoCorrect = false;
switch (primaryCode) {
- case Keyboard.CODE_DELETE:
+ case Constants.CODE_DELETE:
mSpaceState = SPACE_STATE_NONE;
handleBackspace(spaceState);
mDeleteCount++;
mExpectingUpdateSelection = true;
LatinImeLogger.logOnDelete(x, y);
break;
- case Keyboard.CODE_SHIFT:
- case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
+ case Constants.CODE_SHIFT:
+ case Constants.CODE_SWITCH_ALPHA_SYMBOL:
// Shift and symbol key is handled in onPressKey() and onReleaseKey().
break;
- case Keyboard.CODE_SETTINGS:
+ case Constants.CODE_SETTINGS:
onSettingsKeyPressed();
break;
- case Keyboard.CODE_SHORTCUT:
+ case Constants.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME(this);
break;
- case Keyboard.CODE_ACTION_ENTER:
- performEditorAction(getActionId(switcher.getKeyboard()));
- break;
- case Keyboard.CODE_ACTION_NEXT:
+ case Constants.CODE_ACTION_NEXT:
performEditorAction(EditorInfo.IME_ACTION_NEXT);
break;
- case Keyboard.CODE_ACTION_PREVIOUS:
+ case Constants.CODE_ACTION_PREVIOUS:
performEditorAction(EditorInfo.IME_ACTION_PREVIOUS);
break;
- case Keyboard.CODE_LANGUAGE_SWITCH:
+ case Constants.CODE_LANGUAGE_SWITCH:
handleLanguageSwitchKey();
break;
- case Keyboard.CODE_RESEARCH:
+ case Constants.CODE_RESEARCH:
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().onResearchKeySelected(this);
}
break;
- default:
- mSpaceState = SPACE_STATE_NONE;
- if (mCurrentSettings.isWordSeparator(primaryCode)) {
- didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState);
+ case Constants.CODE_ENTER:
+ final EditorInfo editorInfo = getCurrentInputEditorInfo();
+ final int imeOptionsActionId =
+ InputTypeUtils.getImeOptionsActionIdFromEditorInfo(editorInfo);
+ if (InputTypeUtils.IME_ACTION_CUSTOM_LABEL == imeOptionsActionId) {
+ // Either we have an actionLabel and we should performEditorAction with actionId
+ // regardless of its value.
+ performEditorAction(editorInfo.actionId);
+ } else if (EditorInfo.IME_ACTION_NONE != imeOptionsActionId) {
+ // We didn't have an actionLabel, but we had another action to execute.
+ // EditorInfo.IME_ACTION_NONE explicitly means no action. In contrast,
+ // EditorInfo.IME_ACTION_UNSPECIFIED is the default value for an action, so it
+ // means there should be an action and the app didn't bother to set a specific
+ // code for it - presumably it only handles one. It does not have to be treated
+ // in any specific way: anything that is not IME_ACTION_NONE should be sent to
+ // performEditorAction.
+ performEditorAction(imeOptionsActionId);
} else {
- if (SPACE_STATE_PHANTOM == spaceState) {
- if (ProductionFlag.IS_INTERNAL) {
- if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) {
- Stats.onAutoCorrection(
- "", mWordComposer.getTypedWord(), " ", mWordComposer);
- }
- }
- commitTyped(LastComposedWord.NOT_A_SEPARATOR);
- }
- final int keyX, keyY;
- final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
- if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) {
- keyX = x;
- keyY = y;
- } else {
- keyX = Constants.NOT_A_COORDINATE;
- keyY = Constants.NOT_A_COORDINATE;
- }
- handleCharacter(primaryCode, keyX, keyY, spaceState);
+ // No action label, and the action from imeOptions is NONE: this is a regular
+ // enter key that should input a carriage return.
+ didAutoCorrect = handleNonSpecialCharacter(Constants.CODE_ENTER, x, y, spaceState);
}
- mExpectingUpdateSelection = true;
+ break;
+ case Constants.CODE_SHIFT_ENTER:
+ didAutoCorrect = handleNonSpecialCharacter(Constants.CODE_ENTER, x, y, spaceState);
+ break;
+ default:
+ didAutoCorrect = handleNonSpecialCharacter(primaryCode, x, y, spaceState);
break;
}
switcher.onCodeInput(primaryCode);
// Reset after any single keystroke, except shift and symbol-shift
- if (!didAutoCorrect && primaryCode != Keyboard.CODE_SHIFT
- && primaryCode != Keyboard.CODE_SWITCH_ALPHA_SYMBOL)
+ if (!didAutoCorrect && primaryCode != Constants.CODE_SHIFT
+ && primaryCode != Constants.CODE_SWITCH_ALPHA_SYMBOL)
mLastComposedWord.deactivate();
- if (Keyboard.CODE_DELETE != primaryCode) {
+ if (Constants.CODE_DELETE != primaryCode) {
mEnteredText = null;
}
mConnection.endBatchEdit();
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_onCodeInput(primaryCode, x, y);
+ }
+
+ private boolean handleNonSpecialCharacter(final int primaryCode, final int x, final int y,
+ final int spaceState) {
+ mSpaceState = SPACE_STATE_NONE;
+ final boolean didAutoCorrect;
+ if (mSettings.getCurrent().isWordSeparator(primaryCode)) {
+ didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState);
+ } else {
+ didAutoCorrect = false;
+ if (SPACE_STATE_PHANTOM == spaceState) {
+ if (ProductionFlag.IS_INTERNAL) {
+ if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) {
+ Stats.onAutoCorrection(
+ "", mWordComposer.getTypedWord(), " ", mWordComposer);
+ }
+ }
+ commitTyped(LastComposedWord.NOT_A_SEPARATOR);
+ }
+ final int keyX, keyY;
+ final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
+ if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) {
+ keyX = x;
+ keyY = y;
+ } else {
+ keyX = Constants.NOT_A_COORDINATE;
+ keyY = Constants.NOT_A_COORDINATE;
+ }
+ handleCharacter(primaryCode, keyX, keyY, spaceState);
}
+ mExpectingUpdateSelection = true;
+ return didAutoCorrect;
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
- public void onTextInput(final CharSequence rawText) {
+ public void onTextInput(final String rawText) {
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
- commitCurrentAutoCorrection(rawText.toString());
+ commitCurrentAutoCorrection(rawText);
} else {
resetComposingState(true /* alsoResetLastComposedWord */);
}
mHandler.postUpdateSuggestionStrip();
- final CharSequence text = specificTldProcessingOnTextInput(rawText);
+ final String text = specificTldProcessingOnTextInput(rawText);
if (SPACE_STATE_PHANTOM == mSpaceState) {
promotePhantomSpace();
}
mConnection.commitText(text, 1);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_onTextInput(text, false /* isBatchMode */);
+ }
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_NONE;
mKeyboardSwitcher.updateShiftState();
- mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT);
+ mKeyboardSwitcher.onCodeInput(Constants.CODE_OUTPUT_TEXT);
mEnteredText = text;
}
@Override
public void onStartBatchInput() {
- BatchInputUpdater.getInstance().onStartBatchInput();
+ BatchInputUpdater.getInstance().onStartBatchInput(this);
+ mHandler.cancelUpdateSuggestionStrip();
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
if (ProductionFlag.IS_INTERNAL) {
@@ -1469,7 +1508,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
- if (mWordComposer.size() <= 1) {
+ final int wordComposerSize = mWordComposer.size();
+ // Since isComposingWord() is true, the size is at least 1.
+ final int lastChar = mWordComposer.getCodeAt(wordComposerSize - 1);
+ if (wordComposerSize <= 1) {
// We auto-correct the previous (typed, not gestured) string iff it's one character
// long. The reason for this is, even in the middle of gesture typing, you'll still
// tap one-letter words and you want them auto-corrected (typically, "i" in English
@@ -1483,16 +1525,17 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
mExpectingUpdateSelection = true;
// The following is necessary for the case where the user typed something but didn't
- // manual pick it and didn't input any separator.
- mSpaceState = SPACE_STATE_PHANTOM;
+ // manual pick it and didn't input any separator: we want to put a space between what
+ // has been entered and the coming gesture input result, so we go into phantom space
+ // state, which will be promoted to a space when the gesture result is committed. But if
+ // the current input ends in a word connector on the other hand, then we want to have
+ // the next input stick to the current input so we don't switch to phantom space state.
+ if (!mSettings.getCurrent().isWordConnector(lastChar)) {
+ mSpaceState = SPACE_STATE_PHANTOM;
+ }
} else {
final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor();
- // TODO: reverse this logic. We should have the means to determine whether a character
- // should usually be followed by a space, and it should be more readable.
- if (Constants.NOT_A_CODE != codePointBeforeCursor
- && !Character.isWhitespace(codePointBeforeCursor)
- && !mCurrentSettings.isPhantomSpacePromotingSymbol(codePointBeforeCursor)
- && !mCurrentSettings.isWeakSpaceStripper(codePointBeforeCursor)) {
+ if (mSettings.getCurrent().isUsuallyFollowedBySpace(codePointBeforeCursor)) {
mSpaceState = SPACE_STATE_PHANTOM;
}
}
@@ -1503,7 +1546,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
private static final class BatchInputUpdater implements Handler.Callback {
private final Handler mHandler;
private LatinIME mLatinIme;
- private boolean mInBatchInput; // synchornized using "this".
+ private boolean mInBatchInput; // synchronized using "this".
private BatchInputUpdater() {
final HandlerThread handlerThread = new HandlerThread(
@@ -1527,33 +1570,32 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
public boolean handleMessage(final Message msg) {
switch (msg.what) {
case MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
- updateBatchInput((InputPointers)msg.obj, mLatinIme);
+ updateBatchInput((InputPointers)msg.obj);
break;
}
return true;
}
// Run in the UI thread.
- public synchronized void onStartBatchInput() {
+ public synchronized void onStartBatchInput(final LatinIME latinIme) {
+ mHandler.removeMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP);
+ mLatinIme = latinIme;
mInBatchInput = true;
}
// Run in the Handler thread.
- private synchronized void updateBatchInput(final InputPointers batchPointers,
- final LatinIME latinIme) {
+ private synchronized void updateBatchInput(final InputPointers batchPointers) {
if (!mInBatchInput) {
- // Batch input has ended while the message was being delivered.
+ // Batch input has ended or canceled while the message was being delivered.
return;
}
- final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
- batchPointers, latinIme);
- latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
+ final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(batchPointers);
+ mLatinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, false /* dismissGestureFloatingPreviewText */);
}
// Run in the UI thread.
- public void onUpdateBatchInput(final InputPointers batchPointers, final LatinIME latinIme) {
- mLatinIme = latinIme;
+ public void onUpdateBatchInput(final InputPointers batchPointers) {
if (mHandler.hasMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP)) {
return;
}
@@ -1562,33 +1604,42 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
.sendToTarget();
}
+ public synchronized void onCancelBatchInput() {
+ mInBatchInput = false;
+ mLatinIme.mHandler.showGesturePreviewAndSuggestionStrip(
+ SuggestedWords.EMPTY, true /* dismissGestureFloatingPreviewText */);
+ }
+
// Run in the UI thread.
- public synchronized SuggestedWords onEndBatchInput(final InputPointers batchPointers,
- final LatinIME latinIme) {
+ public synchronized SuggestedWords onEndBatchInput(final InputPointers batchPointers) {
mInBatchInput = false;
- final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
- batchPointers, latinIme);
- latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
+ final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(batchPointers);
+ mLatinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, true /* dismissGestureFloatingPreviewText */);
return suggestedWords;
}
// {@link LatinIME#getSuggestedWords(int)} method calls with same session id have to
// be synchronized.
- private static SuggestedWords getSuggestedWordsGestureLocked(
- final InputPointers batchPointers, final LatinIME latinIme) {
- latinIme.mWordComposer.setBatchInputPointers(batchPointers);
- return latinIme.getSuggestedWords(Suggest.SESSION_GESTURE);
+ private SuggestedWords getSuggestedWordsGestureLocked(final InputPointers batchPointers) {
+ mLatinIme.mWordComposer.setBatchInputPointers(batchPointers);
+ final SuggestedWords suggestedWords =
+ mLatinIme.getSuggestedWords(Suggest.SESSION_GESTURE);
+ final int suggestionCount = suggestedWords.size();
+ if (suggestionCount <= 1) {
+ final String mostProbableSuggestion = (suggestionCount == 0) ? null
+ : suggestedWords.getWord(0);
+ return mLatinIme.getOlderSuggestions(mostProbableSuggestion);
+ }
+ return suggestedWords;
}
}
private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
- final String batchInputText = (suggestedWords.size() > 0)
- ? suggestedWords.getWord(0) : null;
- final KeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
- mainKeyboardView.showGestureFloatingPreviewText(batchInputText);
showSuggestionStrip(suggestedWords, null);
+ final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
+ mainKeyboardView.showGestureFloatingPreviewText(suggestedWords);
if (dismissGestureFloatingPreviewText) {
mainKeyboardView.dismissGestureFloatingPreviewText();
}
@@ -1596,15 +1647,15 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
@Override
public void onUpdateBatchInput(final InputPointers batchPointers) {
- BatchInputUpdater.getInstance().onUpdateBatchInput(batchPointers, this);
+ BatchInputUpdater.getInstance().onUpdateBatchInput(batchPointers);
}
@Override
public void onEndBatchInput(final InputPointers batchPointers) {
final SuggestedWords suggestedWords = BatchInputUpdater.getInstance().onEndBatchInput(
- batchPointers, this);
- final String batchInputText = (suggestedWords.size() > 0)
- ? suggestedWords.getWord(0) : null;
+ batchPointers);
+ final String batchInputText = suggestedWords.isEmpty()
+ ? null : suggestedWords.getWord(0);
if (TextUtils.isEmpty(batchInputText)) {
return;
}
@@ -1616,13 +1667,16 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mConnection.setComposingText(batchInputText, 1);
mExpectingUpdateSelection = true;
mConnection.endBatchEdit();
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_onEndBatchInput(batchInputText, 0, suggestedWords);
+ }
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
}
- private CharSequence specificTldProcessingOnTextInput(final CharSequence text) {
- if (text.length() <= 1 || text.charAt(0) != Keyboard.CODE_PERIOD
+ private String specificTldProcessingOnTextInput(final String text) {
+ if (text.length() <= 1 || text.charAt(0) != Constants.CODE_PERIOD
|| !Character.isLetter(text.charAt(1))) {
// Not a tld: do nothing.
return text;
@@ -1633,8 +1687,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// TODO: use getCodePointBeforeCursor instead to improve performance and simplify the code
final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
- && lastOne.charAt(0) == Keyboard.CODE_PERIOD) {
- return text.subSequence(1, text.length());
+ && lastOne.charAt(0) == Constants.CODE_PERIOD) {
+ return text.substring(1);
} else {
return text;
}
@@ -1647,6 +1701,11 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mKeyboardSwitcher.onCancelInput();
}
+ @Override
+ public void onCancelBatchInput() {
+ BatchInputUpdater.getInstance().onCancelBatchInput();
+ }
+
private void handleBackspace(final int spaceState) {
// In many cases, we may have to put the keyboard in auto-shift state again. However
// we want to wait a few milliseconds before doing it to avoid the keyboard flashing
@@ -1656,8 +1715,13 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
if (mWordComposer.isComposingWord()) {
final int length = mWordComposer.size();
if (length > 0) {
- // Immediately after a batch input.
- if (SPACE_STATE_PHANTOM == spaceState) {
+ if (mWordComposer.isBatchMode()) {
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ final String word = mWordComposer.getTypedWord();
+ ResearchLogger.latinIME_handleBackspace_batch(word, 1);
+ ResearchLogger.getInstance().uncommitCurrentLogUnit(
+ word, false /* dumpCurrentLogUnit */);
+ }
mWordComposer.reset();
} else {
mWordComposer.deleteLast();
@@ -1688,8 +1752,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
return;
}
if (SPACE_STATE_DOUBLE == spaceState) {
- mHandler.cancelDoubleSpacesTimer();
- if (mConnection.revertDoubleSpace()) {
+ mHandler.cancelDoubleSpacePeriodTimer();
+ if (mConnection.revertDoubleSpacePeriod()) {
// No need to reset mSpaceState, it has already be done (that's why we
// receive it as a parameter)
return;
@@ -1705,19 +1769,25 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// We should backspace one char and restart suggestion if at the end of a word.
if (mLastSelectionStart != mLastSelectionEnd) {
// If there is a selection, remove it.
- final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart;
+ final int numCharsDeleted = mLastSelectionEnd - mLastSelectionStart;
mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd);
- mConnection.deleteSurroundingText(lengthToDelete, 0);
+ // Reset mLastSelectionEnd to mLastSelectionStart. This is what is supposed to
+ // happen, and if it's wrong, the next call to onUpdateSelection will correct it,
+ // but we want to set it right away to avoid it being used with the wrong values
+ // later (typically, in a subsequent press on backspace).
+ mLastSelectionEnd = mLastSelectionStart;
+ mConnection.deleteSurroundingText(numCharsDeleted, 0);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_handleBackspace(numCharsDeleted);
+ }
} else {
// There is no selection, just delete one character.
if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) {
// This should never happen.
Log.e(TAG, "Backspace when we don't know the selection position");
}
- // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
- // we want to be able to compile against the Ice Cream Sandwich SDK.
if (mTargetApplicationInfo != null
- && mTargetApplicationInfo.targetSdkVersion < 16) {
+ && mTargetApplicationInfo.targetSdkVersion < VERSION_CODES.JELLY_BEAN) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
@@ -1726,35 +1796,38 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
} else {
mConnection.deleteSurroundingText(1, 0);
}
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_handleBackspace(1);
+ }
if (mDeleteCount > DELETE_ACCELERATE_AT) {
mConnection.deleteSurroundingText(1, 0);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_handleBackspace(1);
+ }
}
}
- if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
+ if (mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) {
restartSuggestionsOnWordBeforeCursorIfAtEndOfWord();
}
}
}
+ /*
+ * Strip a trailing space if necessary and returns whether it's a swap weak space situation.
+ */
private boolean maybeStripSpace(final int code,
final int spaceState, final boolean isFromSuggestionStrip) {
- if (Keyboard.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
+ if (Constants.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
mConnection.removeTrailingSpace();
return false;
- } else if ((SPACE_STATE_WEAK == spaceState
- || SPACE_STATE_SWAP_PUNCTUATION == spaceState)
+ }
+ if ((SPACE_STATE_WEAK == spaceState || SPACE_STATE_SWAP_PUNCTUATION == spaceState)
&& isFromSuggestionStrip) {
- if (mCurrentSettings.isWeakSpaceSwapper(code)) {
- return true;
- } else {
- if (mCurrentSettings.isWeakSpaceStripper(code)) {
- mConnection.removeTrailingSpace();
- }
- return false;
- }
- } else {
- return false;
+ if (mSettings.getCurrent().isUsuallyPrecededBySpace(code)) return false;
+ if (mSettings.getCurrent().isUsuallyFollowedBySpace(code)) return true;
+ mConnection.removeTrailingSpace();
}
+ return false;
}
private void handleCharacter(final int primaryCode, final int x,
@@ -1762,7 +1835,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
boolean isComposingWord = mWordComposer.isComposingWord();
if (SPACE_STATE_PHANTOM == spaceState &&
- !mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) {
+ !mSettings.getCurrent().isWordConnector(primaryCode)) {
if (isComposingWord) {
// Sanity check
throw new RuntimeException("Should not be composing here");
@@ -1774,14 +1847,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// dozen milliseconds. Avoid calling it as much as possible, since we are on the UI
// thread here.
if (!isComposingWord && (isAlphabet(primaryCode)
- || mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode))
- && mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) &&
- !mConnection.isCursorTouchingWord(mCurrentSettings)) {
+ || mSettings.getCurrent().isWordConnector(primaryCode))
+ && mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation) &&
+ !mConnection.isCursorTouchingWord(mSettings.getCurrent())) {
// Reset entirely the composing state anyway, then start composing a new word unless
// the character is a single quote. The idea here is, single quote is not a
// separator and it should be treated as a normal character, except in the first
// position where it should not start composing a word.
- isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != primaryCode);
+ isComposingWord = (Constants.CODE_SINGLE_QUOTE != primaryCode);
// Here we don't need to reset the last composed word. It will be reset
// when we commit this one, if we ever do; if on the other hand we backspace
// it entirely and resume suggestions on the previous word, we'd like to still
@@ -1790,15 +1863,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
if (isComposingWord) {
final int keyX, keyY;
- if (KeyboardActionListener.Adapter.isInvalidCoordinate(x)
- || KeyboardActionListener.Adapter.isInvalidCoordinate(y)) {
- keyX = x;
- keyY = y;
- } else {
+ if (Constants.isValidCoordinate(x) && Constants.isValidCoordinate(y)) {
final KeyDetector keyDetector =
mKeyboardSwitcher.getMainKeyboardView().getKeyDetector();
keyX = keyDetector.getTouchX(x);
keyY = keyDetector.getTouchY(y);
+ } else {
+ keyX = x;
+ keyY = y;
}
mWordComposer.add(primaryCode, keyX, keyY);
// If it's the first letter, make note of auto-caps state
@@ -1828,10 +1900,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// Returns true if we did an autocorrection, false otherwise.
private boolean handleSeparator(final int primaryCode, final int x, final int y,
final int spaceState) {
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.recordTimeForLogUnitSplit();
+ ResearchLogger.latinIME_handleSeparator(primaryCode, mWordComposer.isComposingWord());
+ }
boolean didAutoCorrect = false;
// Handle separator
if (mWordComposer.isComposingWord()) {
- if (mCurrentSettings.mCorrectionEnabled) {
+ if (mSettings.getCurrent().mCorrectionEnabled) {
// TODO: maybe cache Strings in an <String> sparse array or something
commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1));
didAutoCorrect = true;
@@ -1844,31 +1920,28 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
Constants.SUGGESTION_STRIP_COORDINATE == x);
if (SPACE_STATE_PHANTOM == spaceState &&
- mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
+ mSettings.getCurrent().isUsuallyPrecededBySpace(primaryCode)) {
promotePhantomSpace();
}
sendKeyCodePoint(primaryCode);
- if (Keyboard.CODE_SPACE == primaryCode) {
- if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
- if (maybeDoubleSpace()) {
+ if (Constants.CODE_SPACE == primaryCode) {
+ if (mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) {
+ if (maybeDoubleSpacePeriod()) {
mSpaceState = SPACE_STATE_DOUBLE;
} else if (!isShowingPunctuationList()) {
mSpaceState = SPACE_STATE_WEAK;
}
}
- mHandler.startDoubleSpacesTimer();
- if (!mConnection.isCursorTouchingWord(mCurrentSettings)) {
- mHandler.postUpdateSuggestionStrip();
- }
+ mHandler.startDoubleSpacePeriodTimer();
+ mHandler.postUpdateSuggestionStrip();
} else {
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_SWAP_PUNCTUATION;
} else if (SPACE_STATE_PHANTOM == spaceState
- && !mCurrentSettings.isWeakSpaceStripper(primaryCode)
- && !mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
+ && mSettings.getCurrent().isUsuallyFollowedBySpace(primaryCode)) {
// If we are in phantom space state, and the user presses a separator, we want to
// stay in phantom space state so that the next keypress has a chance to add the
// space. For example, if I type "Good dat", pick "day" from the suggestion strip
@@ -1894,13 +1967,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
return didAutoCorrect;
}
- private CharSequence getTextWithUnderline(final CharSequence text) {
+ private CharSequence getTextWithUnderline(final String text) {
return mIsAutoCorrectionIndicatorOn
? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text)
: text;
}
private void handleClose() {
+ // TODO: Verify that words are logged properly when IME is closed.
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
requestHideSelf(0);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
@@ -1911,10 +1985,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// TODO: make this private
// Outside LatinIME, only used by the test suite.
- /* package for tests */
+ @UsedForTesting
boolean isShowingPunctuationList() {
- if (mSuggestionStripView == null) return false;
- return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions();
+ if (mSuggestedWords == null) return false;
+ return mSettings.getCurrent().mSuggestPuncList == mSuggestedWords;
}
private boolean isSuggestionsStripVisible() {
@@ -1922,19 +1996,20 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
return false;
if (mSuggestionStripView.isShowingAddToDictionaryHint())
return true;
- if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation))
+ if (!mSettings.getCurrent().isSuggestionStripVisibleInOrientation(mDisplayOrientation))
return false;
- if (mCurrentSettings.isApplicationSpecifiedCompletionsOn())
+ if (mSettings.getCurrent().isApplicationSpecifiedCompletionsOn())
return true;
- return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation);
+ return mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation);
}
private void clearSuggestionStrip() {
- setSuggestionStrip(SuggestedWords.EMPTY, false);
+ setSuggestedWords(SuggestedWords.EMPTY, false);
setAutoCorrectionIndicator(false);
}
- private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) {
+ private void setSuggestedWords(final SuggestedWords words, final boolean isAutoCorrection) {
+ mSuggestedWords = words;
if (mSuggestionStripView != null) {
mSuggestionStripView.setSuggestions(words);
mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection);
@@ -1960,16 +2035,16 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mHandler.cancelUpdateSuggestionStrip();
// Check if we have a suggestion engine attached.
- if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
+ if (mSuggest == null
+ || !mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) {
if (mWordComposer.isComposingWord()) {
Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not "
+ "requested!");
- mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
}
return;
}
- if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) {
+ if (!mWordComposer.isComposingWord() && !mSettings.getCurrent().mBigramPredictionEnabled) {
setPunctuationSuggestions();
return;
}
@@ -1981,7 +2056,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
private SuggestedWords getSuggestedWords(final int sessionId) {
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
- if (keyboard == null) {
+ if (keyboard == null || mSuggest == null) {
return SuggestedWords.EMPTY;
}
final String typedWord = mWordComposer.getTypedWord();
@@ -1989,16 +2064,16 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we
// should just skip whitespace if any, so 1.
// TODO: this is slow (2-way IPC) - we should probably cache this instead.
- final CharSequence prevWord =
- mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators,
+ final String prevWord =
+ mConnection.getNthPreviousWord(mSettings.getCurrent().mWordSeparators,
mWordComposer.isComposingWord() ? 2 : 1);
final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer,
- prevWord, keyboard.getProximityInfo(), mCurrentSettings.mCorrectionEnabled,
+ prevWord, keyboard.getProximityInfo(), mSettings.getCurrent().mCorrectionEnabled,
sessionId);
return maybeRetrieveOlderSuggestions(typedWord, suggestedWords);
}
- private SuggestedWords maybeRetrieveOlderSuggestions(final CharSequence typedWord,
+ private SuggestedWords maybeRetrieveOlderSuggestions(final String typedWord,
final SuggestedWords suggestedWords) {
// TODO: consolidate this into getSuggestedWords
// We update the suggestion strip only when we have some suggestions to show, i.e. when
@@ -2008,45 +2083,47 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// old suggestions. Also, if we are showing the "add to dictionary" hint, we need to
// revert to suggestions - although it is unclear how we can come here if it's displayed.
if (suggestedWords.size() > 1 || typedWord.length() <= 1
- || !suggestedWords.mTypedWordValid
+ || suggestedWords.mTypedWordValid
|| mSuggestionStripView.isShowingAddToDictionaryHint()) {
return suggestedWords;
} else {
- SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions();
- if (previousSuggestions == mCurrentSettings.mSuggestPuncList) {
- previousSuggestions = SuggestedWords.EMPTY;
- }
- final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
- SuggestedWords.getTypedWordAndPreviousSuggestions(
- typedWord, previousSuggestions);
- return new SuggestedWords(typedWordAndPreviousSuggestions,
- false /* typedWordValid */,
- false /* hasAutoCorrectionCandidate */,
- false /* isPunctuationSuggestions */,
- true /* isObsoleteSuggestions */,
- false /* isPrediction */);
+ return getOlderSuggestions(typedWord);
}
}
- private void showSuggestionStrip(final SuggestedWords suggestedWords,
- final CharSequence typedWord) {
- if (null == suggestedWords || suggestedWords.size() <= 0) {
+ private SuggestedWords getOlderSuggestions(final String typedWord) {
+ SuggestedWords previousSuggestedWords = mSuggestedWords;
+ if (previousSuggestedWords == mSettings.getCurrent().mSuggestPuncList) {
+ previousSuggestedWords = SuggestedWords.EMPTY;
+ }
+ if (typedWord == null) {
+ return previousSuggestedWords;
+ }
+ final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
+ SuggestedWords.getTypedWordAndPreviousSuggestions(typedWord,
+ previousSuggestedWords);
+ return new SuggestedWords(typedWordAndPreviousSuggestions,
+ false /* typedWordValid */,
+ false /* hasAutoCorrectionCandidate */,
+ false /* isPunctuationSuggestions */,
+ true /* isObsoleteSuggestions */,
+ false /* isPrediction */);
+ }
+
+ private void showSuggestionStrip(final SuggestedWords suggestedWords, final String typedWord) {
+ if (suggestedWords.isEmpty()) {
clearSuggestionStrip();
return;
}
- final CharSequence autoCorrection;
- if (suggestedWords.size() > 0) {
- if (suggestedWords.mWillAutoCorrect) {
- autoCorrection = suggestedWords.getWord(1);
- } else {
- autoCorrection = typedWord;
- }
+ final String autoCorrection;
+ if (suggestedWords.mWillAutoCorrect) {
+ autoCorrection = suggestedWords.getWord(1);
} else {
- autoCorrection = null;
+ autoCorrection = typedWord;
}
mWordComposer.setAutoCorrection(autoCorrection);
final boolean isAutoCorrection = suggestedWords.willAutoCorrect();
- setSuggestionStrip(suggestedWords, isAutoCorrection);
+ setSuggestedWords(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
setSuggestionStripShown(isSuggestionsStripVisible());
}
@@ -2056,9 +2133,9 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
if (mHandler.hasPendingUpdateSuggestions()) {
updateSuggestionStrip();
}
- final CharSequence typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull();
+ final String typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull();
final String typedWord = mWordComposer.getTypedWord();
- final CharSequence autoCorrection = (typedAutoCorrection != null)
+ final String autoCorrection = (typedAutoCorrection != null)
? typedAutoCorrection : typedWord;
if (autoCorrection != null) {
if (TextUtils.isEmpty(typedWord)) {
@@ -2066,8 +2143,12 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
+ "is empty? Impossible! I must commit suicide.");
}
if (ProductionFlag.IS_INTERNAL) {
- Stats.onAutoCorrection(
- typedWord, autoCorrection.toString(), separatorString, mWordComposer);
+ Stats.onAutoCorrection(typedWord, autoCorrection, separatorString, mWordComposer);
+ }
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ final SuggestedWords suggestedWords = mSuggestedWords;
+ ResearchLogger.latinIme_commitCurrentAutoCorrection(typedWord, autoCorrection,
+ separatorString, mWordComposer.isBatchMode(), suggestedWords);
}
mExpectingUpdateSelection = true;
commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD,
@@ -2089,19 +2170,20 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
// interface
@Override
- public void pickSuggestionManually(final int index, final CharSequence suggestion) {
- final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
+ public void pickSuggestionManually(final int index, final String suggestion) {
+ final SuggestedWords suggestedWords = mSuggestedWords;
// If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
if (suggestion.length() == 1 && isShowingPunctuationList()) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
- LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords);
+ LatinImeLogger.logOnManualSuggestion("", suggestion, index, suggestedWords);
// Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
final int primaryCode = suggestion.charAt(0);
onCodeInput(primaryCode,
Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE);
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_punctuationSuggestion(index, suggestion);
+ ResearchLogger.latinIME_punctuationSuggestion(index, suggestion,
+ false /* isBatchMode */, suggestedWords.mIsPrediction);
}
return;
}
@@ -2111,16 +2193,17 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// In the batch input mode, a manually picked suggested word should just replace
// the current batch input text and there is no need for a phantom space.
&& !mWordComposer.isBatchMode()) {
- int firstChar = Character.codePointAt(suggestion, 0);
- if ((!mCurrentSettings.isWeakSpaceStripper(firstChar))
- && (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) {
+ final int firstChar = Character.codePointAt(suggestion, 0);
+ if (!mSettings.getCurrent().isWordSeparator(firstChar)
+ || mSettings.getCurrent().isUsuallyPrecededBySpace(firstChar)) {
promotePhantomSpace();
}
}
- if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()
+ if (mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()
&& mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
+ mSuggestedWords = SuggestedWords.EMPTY;
if (mSuggestionStripView != null) {
mSuggestionStripView.clear();
}
@@ -2134,14 +2217,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// We need to log before we commit, because the word composer will store away the user
// typed word.
- final String replacedWord = mWordComposer.getTypedWord().toString();
- LatinImeLogger.logOnManualSuggestion(replacedWord,
- suggestion.toString(), index, suggestedWords);
+ final String replacedWord = mWordComposer.getTypedWord();
+ LatinImeLogger.logOnManualSuggestion(replacedWord, suggestion, index, suggestedWords);
mExpectingUpdateSelection = true;
commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK,
LastComposedWord.NOT_A_SEPARATOR);
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion);
+ ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion,
+ mWordComposer.isBatchMode());
}
mConnection.endBatchEdit();
// Don't allow cancellation of manual pick
@@ -2159,12 +2242,12 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
&& !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true);
if (ProductionFlag.IS_INTERNAL) {
- Stats.onSeparator((char)Keyboard.CODE_SPACE,
+ Stats.onSeparator((char)Constants.CODE_SPACE,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) {
mSuggestionStripView.showAddToDictionaryHint(
- suggestion, mCurrentSettings.mHintToSaveText);
+ suggestion, mSettings.getCurrent().mHintToSaveText);
} else {
// If we're not showing the "Touch again to save", then update the suggestion strip.
mHandler.postUpdateSuggestionStrip();
@@ -2174,58 +2257,56 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
/**
* Commits the chosen word to the text field and saves it for later retrieval.
*/
- private void commitChosenWord(final CharSequence chosenWord, final int commitType,
+ private void commitChosenWord(final String chosenWord, final int commitType,
final String separatorString) {
- final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
+ final SuggestedWords suggestedWords = mSuggestedWords;
mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan(
this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1);
// Add the word to the user history dictionary
- final CharSequence prevWord = addToUserHistoryDictionary(chosenWord);
+ final String prevWord = addToUserHistoryDictionary(chosenWord);
// TODO: figure out here if this is an auto-correct or if the best word is actually
// what user typed. Note: currently this is done much later in
// LastComposedWord#didCommitTypedWord by string equality of the remembered
// strings.
- mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(),
- separatorString, prevWord);
+ mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord, separatorString,
+ prevWord);
}
private void setPunctuationSuggestions() {
- if (mCurrentSettings.mBigramPredictionEnabled) {
+ if (mSettings.getCurrent().mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
- setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
+ setSuggestedWords(mSettings.getCurrent().mSuggestPuncList, false);
}
setAutoCorrectionIndicator(false);
setSuggestionStripShown(isSuggestionsStripVisible());
}
- private CharSequence addToUserHistoryDictionary(final CharSequence suggestion) {
+ private String addToUserHistoryDictionary(final String suggestion) {
if (TextUtils.isEmpty(suggestion)) return null;
if (mSuggest == null) return null;
// If correction is not enabled, we don't add words to the user history dictionary.
// That's to avoid unintended additions in some sensitive fields, or fields that
// expect to receive non-words.
- if (!mCurrentSettings.mCorrectionEnabled) return null;
+ if (!mSettings.getCurrent().mCorrectionEnabled) return null;
final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary;
if (userHistoryDictionary != null) {
- final CharSequence prevWord
- = mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2);
+ final String prevWord
+ = mConnection.getNthPreviousWord(mSettings.getCurrent().mWordSeparators, 2);
final String secondWord;
if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) {
- secondWord = suggestion.toString().toLowerCase(
- mSubtypeSwitcher.getCurrentSubtypeLocale());
+ secondWord = suggestion.toLowerCase(mSubtypeSwitcher.getCurrentSubtypeLocale());
} else {
- secondWord = suggestion.toString();
+ secondWord = suggestion;
}
// We demote unrecognized words (frequency < 0, below) by specifying them as "invalid".
// We don't add words with 0-frequency (assuming they would be profanity etc.).
final int maxFreq = AutoCorrection.getMaxFrequency(
mSuggest.getUnigramDictionaries(), suggestion);
if (maxFreq == 0) return null;
- userHistoryDictionary.addToUserHistory(null == prevWord ? null : prevWord.toString(),
- secondWord, maxFreq > 0);
+ userHistoryDictionary.addToUserHistory(prevWord, secondWord, maxFreq > 0);
return prevWord;
}
return null;
@@ -2236,9 +2317,16 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
* word, else do nothing.
*/
private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() {
- final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings);
+ final CharSequence word =
+ mConnection.getWordBeforeCursorIfAtEndOfWord(mSettings.getCurrent());
if (null != word) {
restartSuggestionsOnWordBeforeCursor(word);
+ // TODO: Handle the case where the user manually moves the cursor and then backs up over
+ // a separator. In that case, the current log unit should not be uncommitted.
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.getInstance().uncommitCurrentLogUnit(word.toString(),
+ true /* dumpCurrentLogUnit */);
+ }
}
}
@@ -2251,9 +2339,9 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
private void revertCommit() {
- final CharSequence previousWord = mLastComposedWord.mPrevWord;
+ final String previousWord = mLastComposedWord.mPrevWord;
final String originallyTypedWord = mLastComposedWord.mTypedWord;
- final CharSequence committedWord = mLastComposedWord.mCommittedWord;
+ final String committedWord = mLastComposedWord.mCommittedWord;
final int cancelLength = committedWord.length();
final int separatorLength = LastComposedWord.getSeparatorLength(
mLastComposedWord.mSeparatorString);
@@ -2263,9 +2351,9 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
if (mWordComposer.isComposingWord()) {
throw new RuntimeException("revertCommit, but we are composing a word");
}
- final String wordBeforeCursor =
+ final CharSequence wordBeforeCursor =
mConnection.getTextBeforeCursor(deleteLength, 0)
- .subSequence(0, cancelLength).toString();
+ .subSequence(0, cancelLength);
if (!TextUtils.equals(committedWord, wordBeforeCursor)) {
throw new RuntimeException("revertCommit check failed: we thought we were "
+ "reverting \"" + committedWord
@@ -2274,8 +2362,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
mConnection.deleteSurroundingText(deleteLength, 0);
if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) {
- mUserHistoryDictionary.cancelAddingUserHistory(
- previousWord.toString(), committedWord.toString());
+ mUserHistoryDictionary.cancelAddingUserHistory(previousWord, committedWord);
}
mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1);
if (ProductionFlag.IS_INTERNAL) {
@@ -2283,7 +2370,10 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.latinIME_revertCommit(originallyTypedWord);
+ ResearchLogger.latinIME_revertCommit(committedWord, originallyTypedWord,
+ mWordComposer.isBatchMode(), mLastComposedWord.mSeparatorString);
+ ResearchLogger.getInstance().uncommitCurrentLogUnit(committedWord,
+ true /* dumpCurrentLogUnit */);
}
// Don't restart suggestion yet. We'll restart if the user deletes the
// separator.
@@ -2294,19 +2384,22 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// This essentially inserts a space, and that's it.
public void promotePhantomSpace() {
- if (mCurrentSettings.shouldInsertSpacesAutomatically()) {
- sendKeyCodePoint(Keyboard.CODE_SPACE);
+ if (mSettings.getCurrent().shouldInsertSpacesAutomatically()) {
+ sendKeyCodePoint(Constants.CODE_SPACE);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.latinIME_promotePhantomSpace();
+ }
}
}
// Used by the RingCharBuffer
public boolean isWordSeparator(final int code) {
- return mCurrentSettings.isWordSeparator(code);
+ return mSettings.getCurrent().isWordSeparator(code);
}
// TODO: Make this private
// Outside LatinIME, only used by the {@link InputTestsBase} test suite.
- /* package for test */
+ @UsedForTesting
void loadKeyboard() {
// When the device locale is changed in SetupWizard etc., this method may get called via
// onConfigurationChanged before SoftInputWindow is shown.
@@ -2314,7 +2407,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
loadSettings();
if (mKeyboardSwitcher.getMainKeyboardView() != null) {
// Reload keyboard because the current language has been changed.
- mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings);
+ mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent());
}
// Since we just changed languages, we should re-evaluate suggestions with whatever word
// we are currently composing. If we are not composing anything, we may want to display
@@ -2322,13 +2415,6 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
mHandler.postUpdateSuggestionStrip();
}
- // TODO: Remove this method from {@link LatinIME} and move {@link FeedbackManager} to
- // {@link KeyboardSwitcher}. Called from KeyboardSwitcher
- public void hapticAndAudioFeedback(final int primaryCode) {
- mFeedbackManager.hapticAndAudioFeedback(
- primaryCode, mKeyboardSwitcher.getMainKeyboardView());
- }
-
// Callback called by PointerTracker through the KeyboardActionListener. This is called when a
// key is depressed; release matching call is onReleaseKey below.
@Override
@@ -2345,16 +2431,16 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
// If accessibility is on, ensure the user receives keyboard state updates.
if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) {
switch (primaryCode) {
- case Keyboard.CODE_SHIFT:
+ case Constants.CODE_SHIFT:
AccessibleKeyboardViewProxy.getInstance().notifyShiftState();
break;
- case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
+ case Constants.CODE_SWITCH_ALPHA_SYMBOL:
AccessibleKeyboardViewProxy.getInstance().notifySymbolsState();
break;
}
}
- if (Keyboard.CODE_DELETE == primaryCode) {
+ if (Constants.CODE_DELETE == primaryCode) {
// This is a stopgap solution to avoid leaving a high surrogate alone in a text view.
// In the future, we need to deprecate deteleSurroundingText() and have a surrogate
// pair-friendly way of deleting characters in InputConnection.
@@ -2366,6 +2452,35 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
}
}
+ // Hooks for hardware keyboard
+ @Override
+ public boolean onKeyDown(final int keyCode, final KeyEvent event) {
+ if (!ProductionFlag.IS_HARDWARE_KEYBOARD_SUPPORTED) return super.onKeyDown(keyCode, event);
+ // onHardwareKeyEvent, like onKeyDown returns true if it handled the event, false if
+ // it doesn't know what to do with it and leave it to the application. For example,
+ // hardware key events for adjusting the screen's brightness are passed as is.
+ if (mEventInterpreter.onHardwareKeyEvent(event)) {
+ final long keyIdentifier = event.getDeviceId() << 32 + event.getKeyCode();
+ mCurrentlyPressedHardwareKeys.add(keyIdentifier);
+ return true;
+ }
+ return super.onKeyDown(keyCode, event);
+ }
+
+ @Override
+ public boolean onKeyUp(final int keyCode, final KeyEvent event) {
+ final long keyIdentifier = event.getDeviceId() << 32 + event.getKeyCode();
+ if (mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) {
+ return true;
+ }
+ return super.onKeyUp(keyCode, event);
+ }
+
+ // onKeyDown and onKeyUp are the main events we are interested in. There are two more events
+ // related to handling of hardware key events that we may want to implement in the future:
+ // boolean onKeyLongPress(final int keyCode, final KeyEvent event);
+ // boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event);
+
// receive ringer mode change and network state change.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
@@ -2374,7 +2489,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
} else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
- mFeedbackManager.onRingerModeChanged();
+ mKeyboardSwitcher.onRingerModeChanged();
}
}
};
@@ -2400,7 +2515,9 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
private void launchSubActivity(final Class<? extends Activity> activityClass) {
Intent intent = new Intent();
intent.setClass(LatinIME.this, activityClass);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
+ | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
+ | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@@ -2411,15 +2528,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
getString(R.string.language_selection_title),
getString(R.string.english_ime_settings),
};
- final Context context = this;
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
- Intent intent = CompatUtils.getInputLanguageSelectionIntent(
- ImfUtils.getInputMethodIdOfThisIme(context),
+ final Intent intent = IntentUtils.getInputLanguageSelectionIntent(
+ mRichImm.getInputMethodIdOfThisIme(),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
@@ -2457,13 +2573,19 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
dialog.show();
}
+ // TODO: can this be removed somehow without breaking the tests?
+ @UsedForTesting
+ /* package for test */ String getFirstSuggestedWord() {
+ return mSuggestedWords.size() > 0 ? mSuggestedWords.getWord(0) : null;
+ }
+
public void debugDumpStateAndCrashWithException(final String context) {
final StringBuilder s = new StringBuilder();
s.append("Target application : ").append(mTargetApplicationInfo.name)
.append("\nPackage : ").append(mTargetApplicationInfo.packageName)
.append("\nTarget app sdk version : ")
.append(mTargetApplicationInfo.targetSdkVersion)
- .append("\nAttributes : ").append(mCurrentSettings.getInputAttributesDebugString())
+ .append("\nAttributes : ").append(mSettings.getCurrent().mInputAttributes)
.append("\nContext : ").append(context);
throw new RuntimeException(s.toString());
}
@@ -2477,13 +2599,14 @@ public final class LatinIME extends InputMethodService implements KeyboardAction
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1;
p.println(" Keyboard mode = " + keyboardMode);
+ final SettingsValues settingsValues = mSettings.getCurrent();
p.println(" mIsSuggestionsSuggestionsRequested = "
- + mCurrentSettings.isSuggestionsRequested(mDisplayOrientation));
- p.println(" mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled);
+ + settingsValues.isSuggestionsRequested(mDisplayOrientation));
+ p.println(" mCorrectionEnabled=" + settingsValues.mCorrectionEnabled);
p.println(" isComposingWord=" + mWordComposer.isComposingWord());
- p.println(" mSoundOn=" + mCurrentSettings.mSoundOn);
- p.println(" mVibrateOn=" + mCurrentSettings.mVibrateOn);
- p.println(" mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn);
- p.println(" inputAttributes=" + mCurrentSettings.getInputAttributesDebugString());
+ p.println(" mSoundOn=" + settingsValues.mSoundOn);
+ p.println(" mVibrateOn=" + settingsValues.mVibrateOn);
+ p.println(" mKeyPreviewPopupOn=" + settingsValues.mKeyPreviewPopupOn);
+ p.println(" inputAttributes=" + settingsValues.mInputAttributes);
}
}
diff --git a/java/src/com/android/inputmethod/latin/LatinImeLogger.java b/java/src/com/android/inputmethod/latin/LatinImeLogger.java
index 394a9c7aa..e4e8b94b2 100644
--- a/java/src/com/android/inputmethod/latin/LatinImeLogger.java
+++ b/java/src/com/android/inputmethod/latin/LatinImeLogger.java
@@ -31,7 +31,7 @@ public final class LatinImeLogger implements SharedPreferences.OnSharedPreferenc
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
- public static void init(LatinIME context, SharedPreferences prefs) {
+ public static void init(LatinIME context) {
}
public static void commit() {
diff --git a/java/src/com/android/inputmethod/latin/LocaleUtils.java b/java/src/com/android/inputmethod/latin/LocaleUtils.java
index feb1b2d0e..5fde8158a 100644
--- a/java/src/com/android/inputmethod/latin/LocaleUtils.java
+++ b/java/src/com/android/inputmethod/latin/LocaleUtils.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -180,14 +180,15 @@ public final class LocaleUtils {
synchronized (sLockForRunInLocale) {
final Configuration conf = res.getConfiguration();
final Locale oldLocale = conf.locale;
+ final boolean needsChange = (newLocale != null && !newLocale.equals(oldLocale));
try {
- if (newLocale != null && !newLocale.equals(oldLocale)) {
+ if (needsChange) {
conf.locale = newLocale;
res.updateConfiguration(conf, null);
}
return job(res);
} finally {
- if (newLocale != null && !newLocale.equals(oldLocale)) {
+ if (needsChange) {
conf.locale = oldLocale;
res.updateConfiguration(conf, null);
}
diff --git a/java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java b/java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java
index 8a2d22256..a8800007a 100644
--- a/java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java
+++ b/java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java
@@ -1,23 +1,25 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.view.inputmethod.EditorInfo;
+import java.util.Locale;
+
/**
* Holder class for data about a word already committed but that may still be edited.
*
@@ -29,17 +31,19 @@ import android.view.inputmethod.EditorInfo;
* the IME needs to take a note of what it has to replace and where it is.
* This class encapsulates this data.
*/
-public class PositionalInfoForUserDictPendingAddition {
+public final class PositionalInfoForUserDictPendingAddition {
final private String mOriginalWord;
final private int mCursorPos; // Position of the cursor after the word
final private EditorInfo mEditorInfo; // On what binding this has been added
+ final private int mCapitalizedMode;
private String mActualWordBeingAdded;
public PositionalInfoForUserDictPendingAddition(final String word, final int cursorPos,
- final EditorInfo editorInfo) {
+ final EditorInfo editorInfo, final int capitalizedMode) {
mOriginalWord = word;
mCursorPos = cursorPos;
mEditorInfo = editorInfo;
+ mCapitalizedMode = capitalizedMode;
}
public void setActualWordBeingAdded(final String actualWordBeingAdded) {
@@ -68,10 +72,11 @@ public class PositionalInfoForUserDictPendingAddition {
* @param connection The RichInputConnection through which to contact the editor.
* @param editorInfo Information pertaining to the editor we are currently in.
* @param currentCursorPosition The current cursor position, for checking purposes.
+ * @param locale The locale for changing case, if necessary
* @return true if the edit has been successfully made, false if we need to try again later
*/
public boolean tryReplaceWithActualWord(final RichInputConnection connection,
- final EditorInfo editorInfo, final int currentCursorPosition) {
+ final EditorInfo editorInfo, final int currentCursorPosition, final Locale locale) {
// If we still don't know the actual word being added, we need to try again later.
if (null == mActualWordBeingAdded) return false;
// The entered text and the registered text were the same anyway : we can
@@ -90,9 +95,12 @@ public class PositionalInfoForUserDictPendingAddition {
// so that it won't be tried again
if (currentCursorPosition != mCursorPos) return true;
// We have made all the checks : do the replacement and report success
+ // If this was auto-capitalized, we need to restore the case before committing
+ final String wordWithCaseFixed = CapsModeUtils.applyAutoCapsMode(mActualWordBeingAdded,
+ mCapitalizedMode, locale);
connection.setComposingRegion(currentCursorPosition - mOriginalWord.length(),
currentCursorPosition);
- connection.commitText(mActualWordBeingAdded, mActualWordBeingAdded.length());
+ connection.commitText(wordWithCaseFixed, wordWithCaseFixed.length());
return true;
}
}
diff --git a/java/src/com/android/inputmethod/latin/ResizableIntArray.java b/java/src/com/android/inputmethod/latin/ResizableIntArray.java
index 9a46f160b..691f0602a 100644
--- a/java/src/com/android/inputmethod/latin/ResizableIntArray.java
+++ b/java/src/com/android/inputmethod/latin/ResizableIntArray.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/ResourceUtils.java b/java/src/com/android/inputmethod/latin/ResourceUtils.java
index 5021ad384..b74b979b5 100644
--- a/java/src/com/android/inputmethod/latin/ResourceUtils.java
+++ b/java/src/com/android/inputmethod/latin/ResourceUtils.java
@@ -19,11 +19,15 @@ package com.android.inputmethod.latin;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build;
+import android.util.Log;
import android.util.TypedValue;
import java.util.HashMap;
public final class ResourceUtils {
+ private static final String TAG = ResourceUtils.class.getSimpleName();
+ private static final boolean DEBUG = false;
+
public static final float UNDEFINED_RATIO = -1.0f;
public static final int UNDEFINED_DIMENSION = -1;
@@ -31,24 +35,44 @@ public final class ResourceUtils {
// This utility class is not publicly instantiable.
}
+ private static final String DEFAULT_PREFIX = "DEFAULT,";
private static final String HARDWARE_PREFIX = Build.HARDWARE + ",";
private static final HashMap<String, String> sDeviceOverrideValueMap =
CollectionUtils.newHashMap();
- public static String getDeviceOverrideValue(Resources res, int overrideResId, String defValue) {
+ public static String getDeviceOverrideValue(final Resources res, final int overrideResId) {
final int orientation = res.getConfiguration().orientation;
final String key = overrideResId + "-" + orientation;
- if (!sDeviceOverrideValueMap.containsKey(key)) {
- String overrideValue = defValue;
- for (final String element : res.getStringArray(overrideResId)) {
- if (element.startsWith(HARDWARE_PREFIX)) {
- overrideValue = element.substring(HARDWARE_PREFIX.length());
- break;
- }
+ if (sDeviceOverrideValueMap.containsKey(key)) {
+ return sDeviceOverrideValueMap.get(key);
+ }
+
+ final String[] overrideArray = res.getStringArray(overrideResId);
+ final String overrideValue = StringUtils.findPrefixedString(HARDWARE_PREFIX, overrideArray);
+ // The overrideValue might be an empty string.
+ if (overrideValue != null) {
+ if (DEBUG) {
+ Log.d(TAG, "Find override value:"
+ + " resource="+ res.getResourceEntryName(overrideResId)
+ + " Build.HARDWARE=" + Build.HARDWARE + " override=" + overrideValue);
}
sDeviceOverrideValueMap.put(key, overrideValue);
+ return overrideValue;
+ }
+
+ final String defaultValue = StringUtils.findPrefixedString(DEFAULT_PREFIX, overrideArray);
+ // The defaultValue might be an empty string.
+ if (defaultValue == null) {
+ Log.w(TAG, "Couldn't find override value nor default value:"
+ + " resource="+ res.getResourceEntryName(overrideResId)
+ + " Build.HARDWARE=" + Build.HARDWARE);
+ } else if (DEBUG) {
+ Log.d(TAG, "Found default value:"
+ + " resource="+ res.getResourceEntryName(overrideResId)
+ + " Build.HARDWARE=" + Build.HARDWARE + " default=" + defaultValue);
}
- return sDeviceOverrideValueMap.get(key);
+ sDeviceOverrideValueMap.put(key, defaultValue);
+ return defaultValue;
}
public static boolean isValidFraction(final float fraction) {
@@ -85,8 +109,8 @@ public final class ResourceUtils {
return a.getDimensionPixelSize(index, ResourceUtils.UNDEFINED_DIMENSION);
}
- public static float getDimensionOrFraction(TypedArray a, int index, int base,
- float defValue) {
+ public static float getDimensionOrFraction(final TypedArray a, final int index, final int base,
+ final float defValue) {
final TypedValue value = a.peekValue(index);
if (value == null) {
return defValue;
@@ -99,7 +123,7 @@ public final class ResourceUtils {
return defValue;
}
- public static int getEnumValue(TypedArray a, int index, int defValue) {
+ public static int getEnumValue(final TypedArray a, final int index, final int defValue) {
final TypedValue value = a.peekValue(index);
if (value == null) {
return defValue;
@@ -110,19 +134,19 @@ public final class ResourceUtils {
return defValue;
}
- public static boolean isFractionValue(TypedValue v) {
+ public static boolean isFractionValue(final TypedValue v) {
return v.type == TypedValue.TYPE_FRACTION;
}
- public static boolean isDimensionValue(TypedValue v) {
+ public static boolean isDimensionValue(final TypedValue v) {
return v.type == TypedValue.TYPE_DIMENSION;
}
- public static boolean isIntegerValue(TypedValue v) {
+ public static boolean isIntegerValue(final TypedValue v) {
return v.type >= TypedValue.TYPE_FIRST_INT && v.type <= TypedValue.TYPE_LAST_INT;
}
- public static boolean isStringValue(TypedValue v) {
+ public static boolean isStringValue(final TypedValue v) {
return v.type == TypedValue.TYPE_STRING;
}
}
diff --git a/java/src/com/android/inputmethod/latin/RichInputConnection.java b/java/src/com/android/inputmethod/latin/RichInputConnection.java
index 3b732278b..7300dbd23 100644
--- a/java/src/com/android/inputmethod/latin/RichInputConnection.java
+++ b/java/src/com/android/inputmethod/latin/RichInputConnection.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -26,7 +26,6 @@ import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
-import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.research.ResearchLogger;
@@ -47,7 +46,7 @@ public final class RichInputConnection {
private static final boolean DEBUG_PREVIOUS_TEXT = false;
private static final boolean DEBUG_BATCH_NESTING = false;
// Provision for a long word pair and a separator
- private static final int LOOKBACK_CHARACTER_NUM = BinaryDictionary.MAX_WORD_LENGTH * 2 + 1;
+ private static final int LOOKBACK_CHARACTER_NUM = Constants.Dictionary.MAX_WORD_LENGTH * 2 + 1;
private static final Pattern spaceRegex = Pattern.compile("\\s+");
private static final int INVALID_CURSOR_POSITION = -1;
@@ -66,12 +65,6 @@ public final class RichInputConnection {
* This contains the currently composing text, as LatinIME thinks the TextView is seeing it.
*/
private StringBuilder mComposingText = new StringBuilder();
- /**
- * This is a one-character string containing the character after the cursor. Since LatinIME
- * never touches it directly, it's never modified by any means other than re-reading from the
- * TextView when the cursor position is changed by the user.
- */
- private CharSequence mCharAfterTheCursor = "";
// A hint on how many characters to cache from the TextView. A good value of this is given by
// how many characters we need to be able to almost always find the caps mode.
private static final int DEFAULT_TEXT_CACHE_SIZE = 100;
@@ -147,7 +140,6 @@ public final class RichInputConnection {
mCommittedTextBeforeComposingText.setLength(0);
final CharSequence textBeforeCursor = getTextBeforeCursor(DEFAULT_TEXT_CACHE_SIZE, 0);
if (null != textBeforeCursor) mCommittedTextBeforeComposingText.append(textBeforeCursor);
- mCharAfterTheCursor = getTextAfterCursor(1, 0);
if (null != mIC) {
mIC.finishComposingText();
if (ProductionFlag.IS_EXPERIMENTAL) {
@@ -186,9 +178,6 @@ public final class RichInputConnection {
mComposingText.setLength(0);
if (null != mIC) {
mIC.commitText(text, i);
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.richInputConnection_commitText(text, i);
- }
}
}
@@ -232,7 +221,7 @@ public final class RichInputConnection {
}
// This never calls InputConnection#getCapsMode - in fact, it's a static method that
// never blocks or initiates IPC.
- return StringUtils.getCapsMode(mCommittedTextBeforeComposingText, inputType, locale,
+ return CapsModeUtils.getCapsMode(mCommittedTextBeforeComposingText, inputType, locale,
hasSpaceBefore);
}
@@ -295,40 +284,40 @@ public final class RichInputConnection {
if (DEBUG_BATCH_NESTING) checkBatchEdit();
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
- // This method is only called for enter or backspace when speaking to old
- // applications (target SDK <= 15), or for digits.
+ // This method is only called for enter or backspace when speaking to old applications
+ // (target SDK <= 15 (Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)), or for digits.
// When talking to new applications we never use this method because it's inherently
// racy and has unpredictable results, but for backward compatibility we continue
// sending the key events for only Enter and Backspace because some applications
// mistakenly catch them to do some stuff.
switch (keyEvent.getKeyCode()) {
- case KeyEvent.KEYCODE_ENTER:
- mCommittedTextBeforeComposingText.append("\n");
- mCurrentCursorPosition += 1;
- break;
- case KeyEvent.KEYCODE_DEL:
- if (0 == mComposingText.length()) {
- if (mCommittedTextBeforeComposingText.length() > 0) {
- mCommittedTextBeforeComposingText.delete(
- mCommittedTextBeforeComposingText.length() - 1,
- mCommittedTextBeforeComposingText.length());
- }
- } else {
- mComposingText.delete(mComposingText.length() - 1, mComposingText.length());
- }
- if (mCurrentCursorPosition > 0) mCurrentCursorPosition -= 1;
- break;
- case KeyEvent.KEYCODE_UNKNOWN:
- if (null != keyEvent.getCharacters()) {
- mCommittedTextBeforeComposingText.append(keyEvent.getCharacters());
- mCurrentCursorPosition += keyEvent.getCharacters().length();
+ case KeyEvent.KEYCODE_ENTER:
+ mCommittedTextBeforeComposingText.append("\n");
+ mCurrentCursorPosition += 1;
+ break;
+ case KeyEvent.KEYCODE_DEL:
+ if (0 == mComposingText.length()) {
+ if (mCommittedTextBeforeComposingText.length() > 0) {
+ mCommittedTextBeforeComposingText.delete(
+ mCommittedTextBeforeComposingText.length() - 1,
+ mCommittedTextBeforeComposingText.length());
}
- break;
- default:
- final String text = new String(new int[] { keyEvent.getUnicodeChar() }, 0, 1);
- mCommittedTextBeforeComposingText.append(text);
- mCurrentCursorPosition += text.length();
- break;
+ } else {
+ mComposingText.delete(mComposingText.length() - 1, mComposingText.length());
+ }
+ if (mCurrentCursorPosition > 0) mCurrentCursorPosition -= 1;
+ break;
+ case KeyEvent.KEYCODE_UNKNOWN:
+ if (null != keyEvent.getCharacters()) {
+ mCommittedTextBeforeComposingText.append(keyEvent.getCharacters());
+ mCurrentCursorPosition += keyEvent.getCharacters().length();
+ }
+ break;
+ default:
+ final String text = new String(new int[] { keyEvent.getUnicodeChar() }, 0, 1);
+ mCommittedTextBeforeComposingText.append(text);
+ mCurrentCursorPosition += text.length();
+ break;
}
}
if (null != mIC) {
@@ -394,9 +383,6 @@ public final class RichInputConnection {
// TextView flash the text for a second based on indices contained in the argument.
if (null != mIC) {
mIC.commitCorrection(correctionInfo);
- if (ProductionFlag.IS_EXPERIMENTAL) {
- ResearchLogger.richInputConnection_commitCorrection(correctionInfo);
- }
}
if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
}
@@ -417,7 +403,8 @@ public final class RichInputConnection {
if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug();
}
- public CharSequence getNthPreviousWord(final String sentenceSeperators, final int n) {
+ @SuppressWarnings("unused")
+ public String getNthPreviousWord(final String sentenceSeperators, final int n) {
mIC = mParent.getCurrentInputConnection();
if (null == mIC) return null;
final CharSequence prev = mIC.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0);
@@ -485,19 +472,22 @@ public final class RichInputConnection {
// (n = 2) "abc|" -> null
// (n = 2) "abc |" -> null
// (n = 2) "abc. def|" -> null
- public static CharSequence getNthPreviousWord(final CharSequence prev,
+ public static String getNthPreviousWord(final CharSequence prev,
final String sentenceSeperators, final int n) {
if (prev == null) return null;
- String[] w = spaceRegex.split(prev);
+ final String[] w = spaceRegex.split(prev);
// If we can't find n words, or we found an empty word, return null.
- if (w.length < n || w[w.length - n].length() <= 0) return null;
+ if (w.length < n) return null;
+ final String nthPrevWord = w[w.length - n];
+ final int length = nthPrevWord.length();
+ if (length <= 0) return null;
// If ends in a separator, return null
- char lastChar = w[w.length - n].charAt(w[w.length - n].length() - 1);
+ final char lastChar = nthPrevWord.charAt(length - 1);
if (sentenceSeperators.contains(String.valueOf(lastChar))) return null;
- return w[w.length - n];
+ return nthPrevWord;
}
/**
@@ -530,72 +520,68 @@ public final class RichInputConnection {
* be included in the returned range
* @return a range containing the text surrounding the cursor
*/
- public Range getWordRangeAtCursor(String sep, int additionalPrecedingWordsCount) {
+ public Range getWordRangeAtCursor(final String sep, final int additionalPrecedingWordsCount) {
mIC = mParent.getCurrentInputConnection();
if (mIC == null || sep == null) {
return null;
}
- CharSequence before = mIC.getTextBeforeCursor(1000, 0);
- CharSequence after = mIC.getTextAfterCursor(1000, 0);
+ final CharSequence before = mIC.getTextBeforeCursor(1000, 0);
+ final CharSequence after = mIC.getTextAfterCursor(1000, 0);
if (before == null || after == null) {
return null;
}
// Going backward, alternate skipping non-separators and separators until enough words
// have been read.
- int start = before.length();
+ int count = additionalPrecedingWordsCount;
+ int startIndexInBefore = before.length();
boolean isStoppingAtWhitespace = true; // toggles to indicate what to stop at
while (true) { // see comments below for why this is guaranteed to halt
- while (start > 0) {
- final int codePoint = Character.codePointBefore(before, start);
+ while (startIndexInBefore > 0) {
+ final int codePoint = Character.codePointBefore(before, startIndexInBefore);
if (isStoppingAtWhitespace == isSeparator(codePoint, sep)) {
break; // inner loop
}
- --start;
+ --startIndexInBefore;
if (Character.isSupplementaryCodePoint(codePoint)) {
- --start;
+ --startIndexInBefore;
}
}
// isStoppingAtWhitespace is true every other time through the loop,
// so additionalPrecedingWordsCount is guaranteed to become < 0, which
// guarantees outer loop termination
- if (isStoppingAtWhitespace && (--additionalPrecedingWordsCount < 0)) {
+ if (isStoppingAtWhitespace && (--count < 0)) {
break; // outer loop
}
isStoppingAtWhitespace = !isStoppingAtWhitespace;
}
// Find last word separator after the cursor
- int end = -1;
- while (++end < after.length()) {
- final int codePoint = Character.codePointAt(after, end);
+ int endIndexInAfter = -1;
+ while (++endIndexInAfter < after.length()) {
+ final int codePoint = Character.codePointAt(after, endIndexInAfter);
if (isSeparator(codePoint, sep)) {
break;
}
if (Character.isSupplementaryCodePoint(codePoint)) {
- ++end;
+ ++endIndexInAfter;
}
}
- int cursor = getCursorPosition();
- if (start >= 0 && cursor + end <= after.length() + before.length()) {
- String word = before.toString().substring(start, before.length())
- + after.toString().substring(0, end);
- return new Range(before.length() - start, end, word);
- }
-
- return null;
+ final String word = before.toString().substring(startIndexInBefore, before.length())
+ + after.toString().substring(0, endIndexInAfter);
+ return new Range(before.length() - startIndexInBefore, endIndexInAfter, word);
}
public boolean isCursorTouchingWord(final SettingsValues settingsValues) {
- CharSequence before = getTextBeforeCursor(1, 0);
- CharSequence after = getTextAfterCursor(1, 0);
+ final CharSequence before = getTextBeforeCursor(1, 0);
+ final CharSequence after = getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(before) && !settingsValues.isWordSeparator(before.charAt(0))
- && !settingsValues.isSymbolExcludedFromWordSeparators(before.charAt(0))) {
+ && !settingsValues.isWordConnector(before.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(after) && !settingsValues.isWordSeparator(after.charAt(0))
- && !settingsValues.isSymbolExcludedFromWordSeparators(after.charAt(0))) {
+ && !settingsValues.isWordConnector(after.charAt(0))) {
return true;
}
return false;
@@ -605,7 +591,7 @@ public final class RichInputConnection {
if (DEBUG_BATCH_NESTING) checkBatchEdit();
final CharSequence lastOne = getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
- && lastOne.charAt(0) == Keyboard.CODE_SPACE) {
+ && lastOne.charAt(0) == Constants.CODE_SPACE) {
deleteSurroundingText(1, 0);
}
}
@@ -631,7 +617,7 @@ public final class RichInputConnection {
CharSequence word = getWordAtCursor(settings.mWordSeparators);
// We don't suggest on leading single quotes, so we have to remove them from the word if
// it starts with single quotes.
- while (!TextUtils.isEmpty(word) && Keyboard.CODE_SINGLE_QUOTE == word.charAt(0)) {
+ while (!TextUtils.isEmpty(word) && Constants.CODE_SINGLE_QUOTE == word.charAt(0)) {
word = word.subSequence(1, word.length());
}
if (TextUtils.isEmpty(word)) return null;
@@ -647,31 +633,33 @@ public final class RichInputConnection {
final char firstChar = word.charAt(0); // we just tested that word is not empty
if (word.length() == 1 && !Character.isLetter(firstChar)) return null;
- // We only suggest on words that start with a letter or a symbol that is excluded from
- // word separators (see #handleCharacterWhileInBatchEdit).
- if (!(Character.isLetter(firstChar)
- || settings.isSymbolExcludedFromWordSeparators(firstChar))) {
- return null;
- }
+ // We don't restart suggestion if the first character is not a letter, because we don't
+ // start composing when the first character is not a letter.
+ if (!Character.isLetter(firstChar)) return null;
return word;
}
- public boolean revertDoubleSpace() {
+ public boolean revertDoubleSpacePeriod() {
if (DEBUG_BATCH_NESTING) checkBatchEdit();
// Here we test whether we indeed have a period and a space before us. This should not
// be needed, but it's there just in case something went wrong.
final CharSequence textBeforeCursor = getTextBeforeCursor(2, 0);
- if (!". ".equals(textBeforeCursor)) {
+ final String periodSpace = ". ";
+ if (!periodSpace.equals(textBeforeCursor)) {
// Theoretically we should not be coming here if there isn't ". " before the
// cursor, but the application may be changing the text while we are typing, so
// anything goes. We should not crash.
Log.d(TAG, "Tried to revert double-space combo but we didn't find "
- + "\". \" just before the cursor.");
+ + "\"" + periodSpace + "\" just before the cursor.");
return false;
}
deleteSurroundingText(2, 0);
- commitText(" ", 1);
+ final String doubleSpace = " ";
+ commitText(doubleSpace, 1);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.richInputConnection_revertDoubleSpacePeriod();
+ }
return true;
}
@@ -683,7 +671,7 @@ public final class RichInputConnection {
// NOTE: This does not work with surrogate pairs. Hopefully when the keyboard is able to
// enter surrogate pairs this code will have been removed.
if (TextUtils.isEmpty(textBeforeCursor)
- || (Keyboard.CODE_SPACE != textBeforeCursor.charAt(1))) {
+ || (Constants.CODE_SPACE != textBeforeCursor.charAt(1))) {
// We may only come here if the application is changing the text while we are typing.
// This is quite a broken case, but not logically impossible, so we shouldn't crash,
// but some debugging log may be in order.
@@ -692,7 +680,11 @@ public final class RichInputConnection {
return false;
}
deleteSurroundingText(2, 0);
- commitText(" " + textBeforeCursor.subSequence(0, 1), 1);
+ final String text = " " + textBeforeCursor.subSequence(0, 1);
+ commitText(text, 1);
+ if (ProductionFlag.IS_EXPERIMENTAL) {
+ ResearchLogger.richInputConnection_revertSwapPunctuation();
+ }
return true;
}
diff --git a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java
new file mode 100644
index 000000000..e39aae958
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 2012 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 static com.android.inputmethod.latin.Constants.Subtype.KEYBOARD_MODE;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.IBinder;
+import android.preference.PreferenceManager;
+import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.view.inputmethod.InputMethodSubtype;
+
+import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Enrichment class for InputMethodManager to simplify interaction and add functionality.
+ */
+public final class RichInputMethodManager {
+ private static final String TAG = RichInputMethodManager.class.getSimpleName();
+
+ private RichInputMethodManager() {
+ // This utility class is not publicly instantiable.
+ }
+
+ private static final RichInputMethodManager sInstance = new RichInputMethodManager();
+
+ private InputMethodManagerCompatWrapper mImmWrapper;
+ private InputMethodInfo mInputMethodInfoOfThisIme;
+
+ public static RichInputMethodManager getInstance() {
+ sInstance.checkInitialized();
+ return sInstance;
+ }
+
+ public static void init(final Context context) {
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ sInstance.initInternal(context, prefs);
+ }
+
+ private boolean isInitialized() {
+ return mImmWrapper != null;
+ }
+
+ private void checkInitialized() {
+ if (!isInitialized()) {
+ throw new RuntimeException(TAG + " is used before initialization");
+ }
+ }
+
+ private void initInternal(final Context context, final SharedPreferences prefs) {
+ if (isInitialized()) {
+ return;
+ }
+ mImmWrapper = new InputMethodManagerCompatWrapper(context);
+ mInputMethodInfoOfThisIme = getInputMethodInfoOfThisIme(context);
+
+ // Initialize additional subtypes.
+ SubtypeLocale.init(context);
+ final String prefAdditionalSubtypes = Settings.readPrefAdditionalSubtypes(
+ prefs, context.getResources());
+ final InputMethodSubtype[] additionalSubtypes =
+ AdditionalSubtype.createAdditionalSubtypesArray(prefAdditionalSubtypes);
+ setAdditionalInputMethodSubtypes(additionalSubtypes);
+ }
+
+ public InputMethodManager getInputMethodManager() {
+ checkInitialized();
+ return mImmWrapper.mImm;
+ }
+
+ private InputMethodInfo getInputMethodInfoOfThisIme(final Context context) {
+ final String packageName = context.getPackageName();
+ for (final InputMethodInfo imi : mImmWrapper.mImm.getInputMethodList()) {
+ if (imi.getPackageName().equals(packageName)) {
+ return imi;
+ }
+ }
+ throw new RuntimeException("Input method id for " + packageName + " not found.");
+ }
+
+ public boolean switchToNextInputMethod(final IBinder token, final boolean onlyCurrentIme) {
+ final boolean result = mImmWrapper.switchToNextInputMethod(token, onlyCurrentIme);
+ if (!result) {
+ mImmWrapper.mImm.switchToLastInputMethod(token);
+ return false;
+ }
+ return true;
+ }
+
+ public InputMethodInfo getInputMethodInfoOfThisIme() {
+ return mInputMethodInfoOfThisIme;
+ }
+
+ public String getInputMethodIdOfThisIme() {
+ return mInputMethodInfoOfThisIme.getId();
+ }
+
+ public boolean checkIfSubtypeBelongsToThisImeAndEnabled(final InputMethodSubtype subtype) {
+ return checkIfSubtypeBelongsToImeAndEnabled(mInputMethodInfoOfThisIme, subtype);
+ }
+
+ public boolean checkIfSubtypeBelongsToThisImeAndImplicitlyEnabled(
+ final InputMethodSubtype subtype) {
+ final boolean subtypeEnabled = checkIfSubtypeBelongsToThisImeAndEnabled(subtype);
+ final boolean subtypeExplicitlyEnabled = checkIfSubtypeBelongsToList(
+ subtype, mImmWrapper.mImm.getEnabledInputMethodSubtypeList(
+ mInputMethodInfoOfThisIme, false /* allowsImplicitlySelectedSubtypes */));
+ return subtypeEnabled && !subtypeExplicitlyEnabled;
+ }
+
+ public boolean checkIfSubtypeBelongsToImeAndEnabled(final InputMethodInfo imi,
+ final InputMethodSubtype subtype) {
+ return checkIfSubtypeBelongsToList(
+ subtype, mImmWrapper.mImm.getEnabledInputMethodSubtypeList(
+ imi, true /* allowsImplicitlySelectedSubtypes */));
+ }
+
+ private static boolean checkIfSubtypeBelongsToList(final InputMethodSubtype subtype,
+ final List<InputMethodSubtype> subtypes) {
+ for (final InputMethodSubtype ims : subtypes) {
+ if (ims.equals(subtype)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean checkIfSubtypeBelongsToThisIme(final InputMethodSubtype subtype) {
+ final InputMethodInfo myImi = mInputMethodInfoOfThisIme;
+ final int count = myImi.getSubtypeCount();
+ for (int i = 0; i < count; i++) {
+ final InputMethodSubtype ims = myImi.getSubtypeAt(i);
+ if (ims.equals(subtype)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public InputMethodSubtype getCurrentInputMethodSubtype(
+ final InputMethodSubtype defaultSubtype) {
+ final InputMethodSubtype currentSubtype = mImmWrapper.mImm.getCurrentInputMethodSubtype();
+ return (currentSubtype != null) ? currentSubtype : defaultSubtype;
+ }
+
+ public boolean hasMultipleEnabledIMEsOrSubtypes(final boolean shouldIncludeAuxiliarySubtypes) {
+ final List<InputMethodInfo> enabledImis = mImmWrapper.mImm.getEnabledInputMethodList();
+ return hasMultipleEnabledSubtypes(shouldIncludeAuxiliarySubtypes, enabledImis);
+ }
+
+ public boolean hasMultipleEnabledSubtypesInThisIme(
+ final boolean shouldIncludeAuxiliarySubtypes) {
+ final List<InputMethodInfo> imiList = Collections.singletonList(mInputMethodInfoOfThisIme);
+ return hasMultipleEnabledSubtypes(shouldIncludeAuxiliarySubtypes, imiList);
+ }
+
+ private boolean hasMultipleEnabledSubtypes(final boolean shouldIncludeAuxiliarySubtypes,
+ final List<InputMethodInfo> imiList) {
+ // Number of the filtered IMEs
+ int filteredImisCount = 0;
+
+ for (InputMethodInfo imi : imiList) {
+ // We can return true immediately after we find two or more filtered IMEs.
+ if (filteredImisCount > 1) return true;
+ final List<InputMethodSubtype> subtypes =
+ mImmWrapper.mImm.getEnabledInputMethodSubtypeList(imi, true);
+ // IMEs that have no subtypes should be counted.
+ if (subtypes.isEmpty()) {
+ ++filteredImisCount;
+ continue;
+ }
+
+ int auxCount = 0;
+ for (InputMethodSubtype subtype : subtypes) {
+ if (subtype.isAuxiliary()) {
+ ++auxCount;
+ }
+ }
+ final int nonAuxCount = subtypes.size() - auxCount;
+
+ // IMEs that have one or more non-auxiliary subtypes should be counted.
+ // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
+ // subtypes should be counted as well.
+ if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
+ ++filteredImisCount;
+ continue;
+ }
+ }
+
+ if (filteredImisCount > 1) {
+ return true;
+ }
+ final List<InputMethodSubtype> subtypes =
+ mImmWrapper.mImm.getEnabledInputMethodSubtypeList(null, true);
+ int keyboardCount = 0;
+ // imm.getEnabledInputMethodSubtypeList(null, true) will return the current IME's
+ // both explicitly and implicitly enabled input method subtype.
+ // (The current IME should be LatinIME.)
+ for (InputMethodSubtype subtype : subtypes) {
+ if (KEYBOARD_MODE.equals(subtype.getMode())) {
+ ++keyboardCount;
+ }
+ }
+ return keyboardCount > 1;
+ }
+
+ public InputMethodSubtype findSubtypeByLocaleAndKeyboardLayoutSet(final String localeString,
+ final String keyboardLayoutSetName) {
+ final InputMethodInfo myImi = mInputMethodInfoOfThisIme;
+ final int count = myImi.getSubtypeCount();
+ for (int i = 0; i < count; i++) {
+ final InputMethodSubtype subtype = myImi.getSubtypeAt(i);
+ final String layoutName = SubtypeLocale.getKeyboardLayoutSetName(subtype);
+ if (localeString.equals(subtype.getLocale())
+ && keyboardLayoutSetName.equals(layoutName)) {
+ return subtype;
+ }
+ }
+ return null;
+ }
+
+ public void setInputMethodAndSubtype(final IBinder token, final InputMethodSubtype subtype) {
+ mImmWrapper.mImm.setInputMethodAndSubtype(
+ token, mInputMethodInfoOfThisIme.getId(), subtype);
+ }
+
+ public void setAdditionalInputMethodSubtypes(final InputMethodSubtype[] subtypes) {
+ mImmWrapper.mImm.setAdditionalInputMethodSubtypes(
+ mInputMethodInfoOfThisIme.getId(), subtypes);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/SeekBarDialogPreference.java b/java/src/com/android/inputmethod/latin/SeekBarDialogPreference.java
new file mode 100644
index 000000000..9819a02ef
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/SeekBarDialogPreference.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2013 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.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.res.TypedArray;
+import android.preference.DialogPreference;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.SeekBar;
+import android.widget.TextView;
+
+public final class SeekBarDialogPreference extends DialogPreference
+ implements SeekBar.OnSeekBarChangeListener {
+ public interface ValueProxy {
+ public int readValue(final String key);
+ public int readDefaultValue(final String key);
+ public void writeValue(final int value, final String key);
+ public void feedbackValue(final int value);
+ }
+
+ private final int mValueFormatResId;
+ private final int mMaxValue;
+ private final int mMinValue;
+ private final int mStepValue;
+
+ private TextView mValueView;
+ private SeekBar mSeekBar;
+
+ private ValueProxy mValueProxy;
+
+ public SeekBarDialogPreference(final Context context, final AttributeSet attrs) {
+ super(context, attrs);
+ final TypedArray a = context.obtainStyledAttributes(
+ attrs, R.styleable.SeekBarDialogPreference, 0, 0);
+ mValueFormatResId = a.getResourceId(R.styleable.SeekBarDialogPreference_valueFormatText, 0);
+ mMaxValue = a.getInt(R.styleable.SeekBarDialogPreference_maxValue, 0);
+ mMinValue = a.getInt(R.styleable.SeekBarDialogPreference_minValue, 0);
+ mStepValue = a.getInt(R.styleable.SeekBarDialogPreference_stepValue, 0);
+ a.recycle();
+ setDialogLayoutResource(R.layout.seek_bar_dialog);
+ }
+
+ public void setInterface(final ValueProxy proxy) {
+ mValueProxy = proxy;
+ setSummary(getValueText(proxy.readValue(getKey())));
+ }
+
+ private String getValueText(final int value) {
+ if (mValueFormatResId == 0) {
+ return Integer.toString(value);
+ } else {
+ return getContext().getString(mValueFormatResId, value);
+ }
+ }
+
+ @Override
+ protected View onCreateDialogView() {
+ final View view = super.onCreateDialogView();
+ mSeekBar = (SeekBar)view.findViewById(R.id.seek_bar_dialog_bar);
+ mSeekBar.setMax(mMaxValue - mMinValue);
+ mSeekBar.setOnSeekBarChangeListener(this);
+ mValueView = (TextView)view.findViewById(R.id.seek_bar_dialog_value);
+ return view;
+ }
+
+ private int getProgressFromValue(final int value) {
+ return value - mMinValue;
+ }
+
+ private int getValueFromProgress(final int progress) {
+ return progress + mMinValue;
+ }
+
+ private int clipValue(final int value) {
+ final int clippedValue = Math.min(mMaxValue, Math.max(mMinValue, value));
+ if (mStepValue <= 1) {
+ return clippedValue;
+ }
+ return clippedValue - (clippedValue % mStepValue);
+ }
+
+ private int getClippedValueFromProgress(final int progress) {
+ return clipValue(getValueFromProgress(progress));
+ }
+
+ private void setValue(final int value, final boolean fromUser) {
+ mValueView.setText(getValueText(value));
+ if (!fromUser) {
+ mSeekBar.setProgress(getProgressFromValue(value));
+ }
+ }
+
+ @Override
+ protected void onBindDialogView(final View view) {
+ setValue(clipValue(mValueProxy.readValue(getKey())), false /* fromUser */);
+ }
+
+ @Override
+ protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) {
+ builder.setPositiveButton(android.R.string.ok, this)
+ .setNegativeButton(android.R.string.cancel, this)
+ .setNeutralButton(R.string.button_default, this);
+ }
+
+ @Override
+ public void onClick(final DialogInterface dialog, final int which) {
+ super.onClick(dialog, which);
+ if (which == DialogInterface.BUTTON_NEUTRAL) {
+ setValue(clipValue(mValueProxy.readDefaultValue(getKey())), false /* fromUser */);
+ }
+ if (which != DialogInterface.BUTTON_NEGATIVE) {
+ setSummary(mValueView.getText());
+ mValueProxy.writeValue(getClippedValueFromProgress(mSeekBar.getProgress()), getKey());
+ }
+ }
+
+ @Override
+ public void onProgressChanged(final SeekBar seekBar, final int progress,
+ final boolean fromUser) {
+ setValue(getClippedValueFromProgress(progress), fromUser);
+ }
+
+ @Override
+ public void onStartTrackingTouch(final SeekBar seekBar) {}
+
+ @Override
+ public void onStopTrackingTouch(final SeekBar seekBar) {
+ mValueProxy.feedbackValue(getClippedValueFromProgress(seekBar.getProgress()));
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/Settings.java b/java/src/com/android/inputmethod/latin/Settings.java
index 348928df8..435074bdb 100644
--- a/java/src/com/android/inputmethod/latin/Settings.java
+++ b/java/src/com/android/inputmethod/latin/Settings.java
@@ -1,49 +1,33 @@
/*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2013 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
+ * 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
+ * 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.
+ * 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.app.AlertDialog;
-import android.app.backup.BackupManager;
import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
import android.content.SharedPreferences;
+import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
-import android.media.AudioManager;
-import android.os.Bundle;
-import android.preference.CheckBoxPreference;
-import android.preference.ListPreference;
-import android.preference.Preference;
-import android.preference.Preference.OnPreferenceClickListener;
-import android.preference.PreferenceGroup;
-import android.preference.PreferenceScreen;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.inputmethod.InputMethodSubtype;
-import android.widget.SeekBar;
-import android.widget.SeekBar.OnSeekBarChangeListener;
-import android.widget.TextView;
-
-import com.android.inputmethod.latin.define.ProductionFlag;
-import com.android.inputmethodcommon.InputMethodSettingsFragment;
-
-public final class Settings extends InputMethodSettingsFragment
- implements SharedPreferences.OnSharedPreferenceChangeListener {
+import android.preference.PreferenceManager;
+import com.android.inputmethod.latin.LocaleUtils.RunInLocale;
+
+import java.util.HashMap;
+import java.util.Locale;
+
+public final class Settings implements SharedPreferences.OnSharedPreferenceChangeListener {
// In the same order as xml/prefs.xml
public static final String PREF_GENERAL_SETTINGS = "general_settings";
public static final String PREF_AUTO_CAP = "auto_cap";
@@ -60,6 +44,8 @@ public final class Settings extends InputMethodSettingsFragment
"last_user_dictionary_write_time";
public static final String PREF_ADVANCED_SETTINGS = "pref_advanced_settings";
public static final String PREF_KEY_USE_CONTACTS_DICT = "pref_key_use_contacts_dict";
+ public static final String PREF_KEY_USE_DOUBLE_SPACE_PERIOD =
+ "pref_key_use_double_space_period";
public static final String PREF_SHOW_LANGUAGE_SWITCH_KEY =
"pref_show_language_switch_key";
public static final String PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST =
@@ -70,6 +56,8 @@ public final class Settings extends InputMethodSettingsFragment
public static final String PREF_BIGRAM_PREDICTIONS = "next_word_prediction";
public static final String PREF_GESTURE_SETTINGS = "gesture_typing_settings";
public static final String PREF_GESTURE_INPUT = "gesture_input";
+ public static final String PREF_SLIDING_KEY_INPUT_PREVIEW = "pref_sliding_key_input_preview";
+ public static final String PREF_KEY_LONGPRESS_TIMEOUT = "pref_key_longpress_timeout";
public static final String PREF_VIBRATION_DURATION_SETTINGS =
"pref_vibration_duration_settings";
public static final String PREF_KEYPRESS_SOUND_VOLUME =
@@ -77,391 +65,213 @@ public final class Settings extends InputMethodSettingsFragment
public static final String PREF_GESTURE_PREVIEW_TRAIL = "pref_gesture_preview_trail";
public static final String PREF_GESTURE_FLOATING_PREVIEW_TEXT =
"pref_gesture_floating_preview_text";
+ public static final String PREF_SHOW_SETUP_WIZARD_ICON = "pref_show_setup_wizard_icon";
public static final String PREF_INPUT_LANGUAGE = "input_language";
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_DEBUG_SETTINGS = "debug_settings";
- private PreferenceScreen mKeypressVibrationDurationSettingsPref;
- private PreferenceScreen mKeypressSoundVolumeSettingsPref;
- private ListPreference mVoicePreference;
- private ListPreference mShowCorrectionSuggestionsPreference;
- private ListPreference mAutoCorrectionThresholdPreference;
- private ListPreference mKeyPreviewPopupDismissDelay;
- // Use bigrams to predict the next word when there is no input for it yet
- private CheckBoxPreference mBigramPrediction;
- private Preference mDebugSettingsPreference;
-
- private TextView mKeypressVibrationDurationSettingsTextView;
- private TextView mKeypressSoundVolumeSettingsTextView;
-
- private static void setPreferenceEnabled(final Preference preference, final boolean enabled) {
- if (preference != null) {
- preference.setEnabled(enabled);
- }
+ // This preference key is deprecated. Use {@link #PREF_SHOW_LANGUAGE_SWITCH_KEY} instead.
+ // This is being used only for the backward compatibility.
+ private static final String PREF_SUPPRESS_LANGUAGE_SWITCH_KEY =
+ "pref_suppress_language_switch_key";
+
+ private Resources mRes;
+ private SharedPreferences mPrefs;
+ private Locale mCurrentLocale;
+ private SettingsValues mSettingsValues;
+
+ private static final Settings sInstance = new Settings();
+
+ public static Settings getInstance() {
+ return sInstance;
}
- private void ensureConsistencyOfAutoCorrectionSettings() {
- final String autoCorrectionOff = getResources().getString(
- R.string.auto_correction_threshold_mode_index_off);
- final String currentSetting = mAutoCorrectionThresholdPreference.getValue();
- setPreferenceEnabled(mBigramPrediction, !currentSetting.equals(autoCorrectionOff));
+ public static void init(final Context context) {
+ sInstance.onCreate(context);
}
- @Override
- public void onCreate(final Bundle icicle) {
- super.onCreate(icicle);
- setInputMethodSettingsCategoryTitle(R.string.language_selection_title);
- setSubtypeEnablerTitle(R.string.select_language);
- addPreferencesFromResource(R.xml.prefs);
-
- final Resources res = getResources();
- final Context context = getActivity();
-
- // When we are called from the Settings application but we are not already running, the
- // {@link SubtypeLocale} class may not have been initialized. It is safe to call
- // {@link SubtypeLocale#init(Context)} multiple times.
- SubtypeLocale.init(context);
- mVoicePreference = (ListPreference) findPreference(PREF_VOICE_MODE);
- mShowCorrectionSuggestionsPreference =
- (ListPreference) findPreference(PREF_SHOW_SUGGESTIONS_SETTING);
- SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
- prefs.registerOnSharedPreferenceChangeListener(this);
-
- mAutoCorrectionThresholdPreference =
- (ListPreference) findPreference(PREF_AUTO_CORRECTION_THRESHOLD);
- mBigramPrediction = (CheckBoxPreference) findPreference(PREF_BIGRAM_PREDICTIONS);
- ensureConsistencyOfAutoCorrectionSettings();
-
- final PreferenceGroup generalSettings =
- (PreferenceGroup) findPreference(PREF_GENERAL_SETTINGS);
- final PreferenceGroup textCorrectionGroup =
- (PreferenceGroup) findPreference(PREF_CORRECTION_SETTINGS);
- final PreferenceGroup gestureTypingSettings =
- (PreferenceGroup) findPreference(PREF_GESTURE_SETTINGS);
- final PreferenceGroup miscSettings =
- (PreferenceGroup) findPreference(PREF_MISC_SETTINGS);
-
- mDebugSettingsPreference = findPreference(PREF_DEBUG_SETTINGS);
- if (mDebugSettingsPreference != null) {
- if (ProductionFlag.IS_INTERNAL) {
- final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN);
- debugSettingsIntent.setClassName(
- context.getPackageName(), DebugSettingsActivity.class.getName());
- mDebugSettingsPreference.setIntent(debugSettingsIntent);
- } else {
- miscSettings.removePreference(mDebugSettingsPreference);
- }
- }
+ private Settings() {
+ // Intentional empty constructor for singleton.
+ }
- final boolean showVoiceKeyOption = res.getBoolean(
- R.bool.config_enable_show_voice_key_option);
- if (!showVoiceKeyOption) {
- generalSettings.removePreference(mVoicePreference);
- }
+ private void onCreate(final Context context) {
+ mRes = context.getResources();
+ mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
+ mPrefs.registerOnSharedPreferenceChangeListener(this);
+ }
- final PreferenceGroup advancedSettings =
- (PreferenceGroup) findPreference(PREF_ADVANCED_SETTINGS);
- if (!VibratorUtils.getInstance(context).hasVibrator()) {
- generalSettings.removePreference(findPreference(PREF_VIBRATE_ON));
- if (null != advancedSettings) { // Theoretically advancedSettings cannot be null
- advancedSettings.removePreference(findPreference(PREF_VIBRATION_DURATION_SETTINGS));
- }
- }
+ public void onDestroy() {
+ mPrefs.unregisterOnSharedPreferenceChangeListener(this);
+ }
- final boolean showKeyPreviewPopupOption = res.getBoolean(
- R.bool.config_enable_show_popup_on_keypress_option);
- mKeyPreviewPopupDismissDelay =
- (ListPreference) findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY);
- if (!showKeyPreviewPopupOption) {
- generalSettings.removePreference(findPreference(PREF_POPUP_ON));
- if (null != advancedSettings) { // Theoretically advancedSettings cannot be null
- advancedSettings.removePreference(mKeyPreviewPopupDismissDelay);
- }
- } else {
- 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_key_preview_linger_timeout));
- mKeyPreviewPopupDismissDelay.setEntries(entries);
- mKeyPreviewPopupDismissDelay.setEntryValues(
- new String[] { "0", popupDismissDelayDefaultValue });
- if (null == mKeyPreviewPopupDismissDelay.getValue()) {
- mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue);
- }
- setPreferenceEnabled(mKeyPreviewPopupDismissDelay,
- SettingsValues.isKeyPreviewPopupEnabled(prefs, res));
- }
+ @Override
+ public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
+ loadSettings(mCurrentLocale, mSettingsValues.mInputAttributes);
+ }
- setPreferenceEnabled(findPreference(PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST),
- SettingsValues.showsLanguageSwitchKey(prefs));
+ public void loadSettings(final Locale locale, final InputAttributes inputAttributes) {
+ mCurrentLocale = locale;
+ final SharedPreferences prefs = mPrefs;
+ final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() {
+ @Override
+ protected SettingsValues job(final Resources res) {
+ return new SettingsValues(prefs, res, inputAttributes);
+ }
+ };
+ mSettingsValues = job.runInLocale(mRes, locale);
+ }
- final PreferenceScreen dictionaryLink =
- (PreferenceScreen) findPreference(PREF_CONFIGURE_DICTIONARIES_KEY);
- final Intent intent = dictionaryLink.getIntent();
+ // TODO: Remove this method and add proxy method to SettingsValues.
+ public SettingsValues getCurrent() {
+ return mSettingsValues;
+ }
- final int number = context.getPackageManager().queryIntentActivities(intent, 0).size();
- if (0 >= number) {
- textCorrectionGroup.removePreference(dictionaryLink);
- }
+ // Accessed from the settings interface, hence public
+ public static boolean readKeypressSoundEnabled(final SharedPreferences prefs,
+ final Resources res) {
+ return prefs.getBoolean(Settings.PREF_SOUND_ON,
+ res.getBoolean(R.bool.config_default_sound_enabled));
+ }
- final boolean gestureInputEnabledByBuildConfig = res.getBoolean(
- R.bool.config_gesture_input_enabled_by_build_config);
- if (!gestureInputEnabledByBuildConfig) {
- getPreferenceScreen().removePreference(gestureTypingSettings);
- }
+ public static boolean readVibrationEnabled(final SharedPreferences prefs,
+ final Resources res) {
+ final boolean hasVibrator = AudioAndHapticFeedbackManager.getInstance().hasVibrator();
+ return hasVibrator && prefs.getBoolean(PREF_VIBRATE_ON,
+ res.getBoolean(R.bool.config_default_vibration_enabled));
+ }
- mKeypressVibrationDurationSettingsPref =
- (PreferenceScreen) findPreference(PREF_VIBRATION_DURATION_SETTINGS);
- if (mKeypressVibrationDurationSettingsPref != null) {
- mKeypressVibrationDurationSettingsPref.setOnPreferenceClickListener(
- new OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference arg0) {
- showKeypressVibrationDurationSettingsDialog();
- return true;
- }
- });
- updateKeypressVibrationDurationSettingsSummary(prefs, res);
- }
+ public static boolean readAutoCorrectEnabled(final String currentAutoCorrectionSetting,
+ final Resources res) {
+ final String autoCorrectionOff = res.getString(
+ R.string.auto_correction_threshold_mode_index_off);
+ return !currentAutoCorrectionSetting.equals(autoCorrectionOff);
+ }
- mKeypressSoundVolumeSettingsPref =
- (PreferenceScreen) findPreference(PREF_KEYPRESS_SOUND_VOLUME);
- if (mKeypressSoundVolumeSettingsPref != null) {
- mKeypressSoundVolumeSettingsPref.setOnPreferenceClickListener(
- new OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference arg0) {
- showKeypressSoundVolumeSettingDialog();
- return true;
- }
- });
- updateKeypressSoundVolumeSummary(prefs, res);
- }
- refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, res);
+ public static boolean readFromBuildConfigIfGestureInputEnabled(final Resources res) {
+ return res.getBoolean(R.bool.config_gesture_input_enabled_by_build_config);
}
- @Override
- public void onResume() {
- super.onResume();
- final boolean isShortcutImeEnabled = SubtypeSwitcher.getInstance().isShortcutImeEnabled();
- if (isShortcutImeEnabled) {
- updateVoiceModeSummary();
- } else {
- getPreferenceScreen().removePreference(mVoicePreference);
- }
- updateShowCorrectionSuggestionsSummary();
- updateKeyPreviewPopupDelaySummary();
- updateCustomInputStylesSummary();
+ public static boolean readGestureInputEnabled(final SharedPreferences prefs,
+ final Resources res) {
+ return readFromBuildConfigIfGestureInputEnabled(res)
+ && prefs.getBoolean(Settings.PREF_GESTURE_INPUT, true);
}
- @Override
- public void onDestroy() {
- getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
- this);
- super.onDestroy();
+ public static boolean readFromBuildConfigIfToShowKeyPreviewPopupSettingsOption(
+ final Resources res) {
+ return res.getBoolean(R.bool.config_enable_show_option_of_key_preview_popup);
}
- @Override
- public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
- (new BackupManager(getActivity())).dataChanged();
- if (key.equals(PREF_POPUP_ON)) {
- setPreferenceEnabled(findPreference(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY),
- prefs.getBoolean(PREF_POPUP_ON, true));
- } else if (key.equals(PREF_SHOW_LANGUAGE_SWITCH_KEY)) {
- setPreferenceEnabled(findPreference(PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST),
- SettingsValues.showsLanguageSwitchKey(prefs));
- } else if (key.equals(PREF_GESTURE_INPUT)) {
- final boolean gestureInputEnabledByConfig = getResources().getBoolean(
- R.bool.config_gesture_input_enabled_by_build_config);
- if (gestureInputEnabledByConfig) {
- final boolean gestureInputEnabledByUser = prefs.getBoolean(
- PREF_GESTURE_INPUT, true);
- setPreferenceEnabled(findPreference(PREF_GESTURE_PREVIEW_TRAIL),
- gestureInputEnabledByUser);
- setPreferenceEnabled(findPreference(PREF_GESTURE_FLOATING_PREVIEW_TEXT),
- gestureInputEnabledByUser);
- }
+ public static boolean readKeyPreviewPopupEnabled(final SharedPreferences prefs,
+ final Resources res) {
+ final boolean defaultKeyPreviewPopup = res.getBoolean(
+ R.bool.config_default_key_preview_popup);
+ if (!readFromBuildConfigIfToShowKeyPreviewPopupSettingsOption(res)) {
+ return defaultKeyPreviewPopup;
}
- ensureConsistencyOfAutoCorrectionSettings();
- updateVoiceModeSummary();
- updateShowCorrectionSuggestionsSummary();
- updateKeyPreviewPopupDelaySummary();
- refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, getResources());
+ return prefs.getBoolean(PREF_POPUP_ON, defaultKeyPreviewPopup);
}
- private void updateShowCorrectionSuggestionsSummary() {
- mShowCorrectionSuggestionsPreference.setSummary(
- getResources().getStringArray(R.array.prefs_suggestion_visibilities)
- [mShowCorrectionSuggestionsPreference.findIndexOfValue(
- mShowCorrectionSuggestionsPreference.getValue())]);
+ public static int readKeyPreviewPopupDismissDelay(final SharedPreferences prefs,
+ final Resources res) {
+ return Integer.parseInt(prefs.getString(PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY,
+ Integer.toString(res.getInteger(
+ R.integer.config_key_preview_linger_timeout))));
}
- private void updateCustomInputStylesSummary() {
- final PreferenceScreen customInputStyles =
- (PreferenceScreen)findPreference(PREF_CUSTOM_INPUT_STYLES);
- final SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
- final Resources res = getResources();
- final String prefSubtype = SettingsValues.getPrefAdditionalSubtypes(prefs, res);
- final InputMethodSubtype[] subtypes =
- AdditionalSubtype.createAdditionalSubtypesArray(prefSubtype);
- final StringBuilder styles = new StringBuilder();
- for (final InputMethodSubtype subtype : subtypes) {
- if (styles.length() > 0) styles.append(", ");
- styles.append(SubtypeLocale.getSubtypeDisplayName(subtype, res));
+ public static boolean readShowsLanguageSwitchKey(final SharedPreferences prefs) {
+ if (prefs.contains(PREF_SUPPRESS_LANGUAGE_SWITCH_KEY)) {
+ final boolean suppressLanguageSwitchKey = prefs.getBoolean(
+ PREF_SUPPRESS_LANGUAGE_SWITCH_KEY, false);
+ final SharedPreferences.Editor editor = prefs.edit();
+ editor.remove(PREF_SUPPRESS_LANGUAGE_SWITCH_KEY);
+ editor.putBoolean(PREF_SHOW_LANGUAGE_SWITCH_KEY, !suppressLanguageSwitchKey);
+ editor.apply();
}
- customInputStyles.setSummary(styles);
+ return prefs.getBoolean(PREF_SHOW_LANGUAGE_SWITCH_KEY, true);
}
- private void updateKeyPreviewPopupDelaySummary() {
- final ListPreference lp = mKeyPreviewPopupDismissDelay;
- final CharSequence[] entries = lp.getEntries();
- if (entries == null || entries.length <= 0) return;
- lp.setSummary(entries[lp.findIndexOfValue(lp.getValue())]);
+ public static String readPrefAdditionalSubtypes(final SharedPreferences prefs,
+ final Resources res) {
+ final String predefinedPrefSubtypes = AdditionalSubtype.createPrefSubtypes(
+ res.getStringArray(R.array.predefined_subtypes));
+ return prefs.getString(PREF_CUSTOM_INPUT_STYLES, predefinedPrefSubtypes);
}
- private void updateVoiceModeSummary() {
- mVoicePreference.setSummary(
- getResources().getStringArray(R.array.voice_input_modes_summary)
- [mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]);
+ public static void writePrefAdditionalSubtypes(final SharedPreferences prefs,
+ final String prefSubtypes) {
+ prefs.edit().putString(Settings.PREF_CUSTOM_INPUT_STYLES, prefSubtypes).apply();
}
- private void refreshEnablingsOfKeypressSoundAndVibrationSettings(
- final SharedPreferences sp, final Resources res) {
- if (mKeypressVibrationDurationSettingsPref != null) {
- final boolean hasVibratorHardware = VibratorUtils.getInstance(getActivity())
- .hasVibrator();
- final boolean vibrateOnByUser = sp.getBoolean(Settings.PREF_VIBRATE_ON,
- res.getBoolean(R.bool.config_default_vibration_enabled));
- setPreferenceEnabled(mKeypressVibrationDurationSettingsPref,
- hasVibratorHardware && vibrateOnByUser);
- }
+ public static float readKeypressSoundVolume(final SharedPreferences prefs,
+ final Resources res) {
+ final float volume = prefs.getFloat(PREF_KEYPRESS_SOUND_VOLUME, -1.0f);
+ return (volume >= 0) ? volume : readDefaultKeypressSoundVolume(res);
+ }
- if (mKeypressSoundVolumeSettingsPref != null) {
- final boolean soundOn = sp.getBoolean(Settings.PREF_SOUND_ON,
- res.getBoolean(R.bool.config_default_sound_enabled));
- setPreferenceEnabled(mKeypressSoundVolumeSettingsPref, soundOn);
- }
+ public static float readDefaultKeypressSoundVolume(final Resources res) {
+ return Float.parseFloat(
+ ResourceUtils.getDeviceOverrideValue(res, R.array.keypress_volumes));
}
- private void updateKeypressVibrationDurationSettingsSummary(
- final SharedPreferences sp, final Resources res) {
- if (mKeypressVibrationDurationSettingsPref != null) {
- mKeypressVibrationDurationSettingsPref.setSummary(
- SettingsValues.getCurrentVibrationDuration(sp, res)
- + res.getString(R.string.settings_ms));
- }
+ public static int readKeyLongpressTimeout(final SharedPreferences prefs,
+ final Resources res) {
+ final int ms = prefs.getInt(PREF_KEY_LONGPRESS_TIMEOUT, -1);
+ return (ms >= 0) ? ms : readDefaultKeyLongpressTimeout(res);
}
- private void showKeypressVibrationDurationSettingsDialog() {
- final SharedPreferences sp = getPreferenceManager().getSharedPreferences();
- final Context context = getActivity();
- final Resources res = context.getResources();
- final AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(R.string.prefs_keypress_vibration_duration_settings);
- builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int whichButton) {
- final int ms = Integer.valueOf(
- mKeypressVibrationDurationSettingsTextView.getText().toString());
- sp.edit().putInt(Settings.PREF_VIBRATION_DURATION_SETTINGS, ms).apply();
- updateKeypressVibrationDurationSettingsSummary(sp, res);
- }
- });
- builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int whichButton) {
- dialog.dismiss();
- }
- });
- final View v = LayoutInflater.from(context).inflate(
- R.layout.vibration_settings_dialog, null);
- final int currentMs = SettingsValues.getCurrentVibrationDuration(
- getPreferenceManager().getSharedPreferences(), getResources());
- mKeypressVibrationDurationSettingsTextView = (TextView)v.findViewById(R.id.vibration_value);
- final SeekBar sb = (SeekBar)v.findViewById(R.id.vibration_settings);
- sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
- @Override
- public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
- final int tempMs = arg1;
- mKeypressVibrationDurationSettingsTextView.setText(String.valueOf(tempMs));
- }
+ public static int readDefaultKeyLongpressTimeout(final Resources res) {
+ return res.getInteger(R.integer.config_default_longpress_key_timeout);
+ }
- @Override
- public void onStartTrackingTouch(SeekBar arg0) {
- }
+ public static int readKeypressVibrationDuration(final SharedPreferences prefs,
+ final Resources res) {
+ final int ms = prefs.getInt(PREF_VIBRATION_DURATION_SETTINGS, -1);
+ return (ms >= 0) ? ms : readDefaultKeypressVibrationDuration(res);
+ }
- @Override
- public void onStopTrackingTouch(SeekBar arg0) {
- final int tempMs = arg0.getProgress();
- VibratorUtils.getInstance(context).vibrate(tempMs);
- }
- });
- sb.setProgress(currentMs);
- mKeypressVibrationDurationSettingsTextView.setText(String.valueOf(currentMs));
- builder.setView(v);
- builder.create().show();
+ public static int readDefaultKeypressVibrationDuration(final Resources res) {
+ return Integer.parseInt(
+ ResourceUtils.getDeviceOverrideValue(res, R.array.keypress_vibration_durations));
+ }
+
+ public static boolean readUsabilityStudyMode(final SharedPreferences prefs) {
+ return prefs.getBoolean(DebugSettings.PREF_USABILITY_STUDY_MODE, true);
}
- private void updateKeypressSoundVolumeSummary(final SharedPreferences sp, final Resources res) {
- if (mKeypressSoundVolumeSettingsPref != null) {
- mKeypressSoundVolumeSettingsPref.setSummary(String.valueOf(
- (int)(SettingsValues.getCurrentKeypressSoundVolume(sp, res) * 100)));
+ public static long readLastUserHistoryWriteTime(final SharedPreferences prefs,
+ final String locale) {
+ final String str = prefs.getString(PREF_LAST_USER_DICTIONARY_WRITE_TIME, "");
+ final HashMap<String, Long> map = LocaleUtils.localeAndTimeStrToHashMap(str);
+ if (map.containsKey(locale)) {
+ return map.get(locale);
}
+ return 0;
}
- private void showKeypressSoundVolumeSettingDialog() {
- final Context context = getActivity();
- final AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
- final SharedPreferences sp = getPreferenceManager().getSharedPreferences();
- final Resources res = context.getResources();
- final AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(R.string.prefs_keypress_sound_volume_settings);
- builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int whichButton) {
- final float volume =
- ((float)Integer.valueOf(
- mKeypressSoundVolumeSettingsTextView.getText().toString())) / 100;
- sp.edit().putFloat(Settings.PREF_KEYPRESS_SOUND_VOLUME, volume).apply();
- updateKeypressSoundVolumeSummary(sp, res);
- }
- });
- builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int whichButton) {
- dialog.dismiss();
- }
- });
- final View v = LayoutInflater.from(context).inflate(
- R.layout.sound_effect_volume_dialog, null);
- final int currentVolumeInt =
- (int)(SettingsValues.getCurrentKeypressSoundVolume(sp, res) * 100);
- mKeypressSoundVolumeSettingsTextView =
- (TextView)v.findViewById(R.id.sound_effect_volume_value);
- final SeekBar sb = (SeekBar)v.findViewById(R.id.sound_effect_volume_bar);
- sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
- @Override
- public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
- final int tempVolume = arg1;
- mKeypressSoundVolumeSettingsTextView.setText(String.valueOf(tempVolume));
- }
+ public static void writeLastUserHistoryWriteTime(final SharedPreferences prefs,
+ final String locale) {
+ final String oldStr = prefs.getString(PREF_LAST_USER_DICTIONARY_WRITE_TIME, "");
+ final HashMap<String, Long> map = LocaleUtils.localeAndTimeStrToHashMap(oldStr);
+ map.put(locale, System.currentTimeMillis());
+ final String newStr = LocaleUtils.localeAndTimeHashMapToStr(map);
+ prefs.edit().putString(PREF_LAST_USER_DICTIONARY_WRITE_TIME, newStr).apply();
+ }
- @Override
- public void onStartTrackingTouch(SeekBar arg0) {
- }
+ public static boolean readUseFullscreenMode(final Resources res) {
+ return res.getBoolean(R.bool.config_use_fullscreen_mode);
+ }
- @Override
- public void onStopTrackingTouch(SeekBar arg0) {
- final float tempVolume = ((float)arg0.getProgress()) / 100;
- am.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD, tempVolume);
- }
- });
- sb.setProgress(currentVolumeInt);
- mKeypressSoundVolumeSettingsTextView.setText(String.valueOf(currentVolumeInt));
- builder.setView(v);
- builder.create().show();
+ public static boolean readShowSetupWizardIcon(final SharedPreferences prefs,
+ final Context context) {
+ if (!prefs.contains(Settings.PREF_SHOW_SETUP_WIZARD_ICON)) {
+ final ApplicationInfo appInfo = context.getApplicationInfo();
+ final boolean isApplicationInSystemImage =
+ (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
+ // Default value
+ return !isApplicationInSystemImage;
+ }
+ return prefs.getBoolean(Settings.PREF_SHOW_SETUP_WIZARD_ICON, false);
}
}
diff --git a/java/src/com/android/inputmethod/latin/SettingsActivity.java b/java/src/com/android/inputmethod/latin/SettingsActivity.java
index 0d3c8ebb7..ed8cf6d8f 100644
--- a/java/src/com/android/inputmethod/latin/SettingsActivity.java
+++ b/java/src/com/android/inputmethod/latin/SettingsActivity.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
@@ -20,7 +20,7 @@ import android.content.Intent;
import android.preference.PreferenceActivity;
public final class SettingsActivity extends PreferenceActivity {
- private static final String DEFAULT_FRAGMENT = Settings.class.getName();
+ private static final String DEFAULT_FRAGMENT = SettingsFragment.class.getName();
@Override
public Intent getIntent() {
diff --git a/java/src/com/android/inputmethod/latin/SettingsFragment.java b/java/src/com/android/inputmethod/latin/SettingsFragment.java
new file mode 100644
index 000000000..4c90e485a
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/SettingsFragment.java
@@ -0,0 +1,363 @@
+/*
+ * Copyright (C) 2008 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.app.backup.BackupManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.res.Resources;
+import android.media.AudioManager;
+import android.os.Bundle;
+import android.preference.CheckBoxPreference;
+import android.preference.ListPreference;
+import android.preference.Preference;
+import android.preference.PreferenceGroup;
+import android.preference.PreferenceScreen;
+import android.view.inputmethod.InputMethodSubtype;
+
+import com.android.inputmethod.latin.define.ProductionFlag;
+import com.android.inputmethod.latin.setup.LauncherIconVisibilityManager;
+import com.android.inputmethodcommon.InputMethodSettingsFragment;
+
+public final class SettingsFragment extends InputMethodSettingsFragment
+ implements SharedPreferences.OnSharedPreferenceChangeListener {
+ private ListPreference mVoicePreference;
+ private ListPreference mShowCorrectionSuggestionsPreference;
+ private ListPreference mAutoCorrectionThresholdPreference;
+ private ListPreference mKeyPreviewPopupDismissDelay;
+ // Use bigrams to predict the next word when there is no input for it yet
+ private CheckBoxPreference mBigramPrediction;
+
+ private void setPreferenceEnabled(final String preferenceKey, final boolean enabled) {
+ final Preference preference = findPreference(preferenceKey);
+ if (preference != null) {
+ preference.setEnabled(enabled);
+ }
+ }
+
+ private static void removePreference(final String preferenceKey, final PreferenceGroup parent) {
+ if (parent == null) {
+ return;
+ }
+ final Preference preference = parent.findPreference(preferenceKey);
+ if (preference != null) {
+ parent.removePreference(preference);
+ }
+ }
+
+ @Override
+ public void onCreate(final Bundle icicle) {
+ super.onCreate(icicle);
+ setInputMethodSettingsCategoryTitle(R.string.language_selection_title);
+ setSubtypeEnablerTitle(R.string.select_language);
+ addPreferencesFromResource(R.xml.prefs);
+
+ final Resources res = getResources();
+ final Context context = getActivity();
+
+ // When we are called from the Settings application but we are not already running, the
+ // {@link SubtypeLocale} class may not have been initialized. It is safe to call
+ // {@link SubtypeLocale#init(Context)} multiple times.
+ SubtypeLocale.init(context);
+ mVoicePreference = (ListPreference) findPreference(Settings.PREF_VOICE_MODE);
+ mShowCorrectionSuggestionsPreference =
+ (ListPreference) findPreference(Settings.PREF_SHOW_SUGGESTIONS_SETTING);
+ final SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
+ prefs.registerOnSharedPreferenceChangeListener(this);
+
+ mAutoCorrectionThresholdPreference =
+ (ListPreference) findPreference(Settings.PREF_AUTO_CORRECTION_THRESHOLD);
+ mBigramPrediction = (CheckBoxPreference) findPreference(Settings.PREF_BIGRAM_PREDICTIONS);
+ ensureConsistencyOfAutoCorrectionSettings();
+
+ final PreferenceGroup generalSettings =
+ (PreferenceGroup) findPreference(Settings.PREF_GENERAL_SETTINGS);
+ final PreferenceGroup miscSettings =
+ (PreferenceGroup) findPreference(Settings.PREF_MISC_SETTINGS);
+
+ final Preference debugSettings = findPreference(Settings.PREF_DEBUG_SETTINGS);
+ if (debugSettings != null) {
+ if (ProductionFlag.IS_INTERNAL) {
+ final Intent debugSettingsIntent = new Intent(Intent.ACTION_MAIN);
+ debugSettingsIntent.setClassName(
+ context.getPackageName(), DebugSettingsActivity.class.getName());
+ debugSettings.setIntent(debugSettingsIntent);
+ } else {
+ miscSettings.removePreference(debugSettings);
+ }
+ }
+
+ final boolean showVoiceKeyOption = res.getBoolean(
+ R.bool.config_enable_show_voice_key_option);
+ if (!showVoiceKeyOption) {
+ generalSettings.removePreference(mVoicePreference);
+ }
+
+ final PreferenceGroup advancedSettings =
+ (PreferenceGroup) findPreference(Settings.PREF_ADVANCED_SETTINGS);
+ if (!AudioAndHapticFeedbackManager.getInstance().hasVibrator()) {
+ removePreference(Settings.PREF_VIBRATE_ON, generalSettings);
+ removePreference(Settings.PREF_VIBRATION_DURATION_SETTINGS, advancedSettings);
+ }
+
+ mKeyPreviewPopupDismissDelay =
+ (ListPreference) findPreference(Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY);
+ if (!Settings.readFromBuildConfigIfToShowKeyPreviewPopupSettingsOption(res)) {
+ removePreference(Settings.PREF_POPUP_ON, generalSettings);
+ removePreference(Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY, advancedSettings);
+ } else {
+ final String popupDismissDelayDefaultValue = Integer.toString(res.getInteger(
+ R.integer.config_key_preview_linger_timeout));
+ mKeyPreviewPopupDismissDelay.setEntries(new String[] {
+ res.getString(R.string.key_preview_popup_dismiss_no_delay),
+ res.getString(R.string.key_preview_popup_dismiss_default_delay),
+ });
+ mKeyPreviewPopupDismissDelay.setEntryValues(new String[] {
+ "0",
+ popupDismissDelayDefaultValue
+ });
+ if (null == mKeyPreviewPopupDismissDelay.getValue()) {
+ mKeyPreviewPopupDismissDelay.setValue(popupDismissDelayDefaultValue);
+ }
+ mKeyPreviewPopupDismissDelay.setEnabled(
+ Settings.readKeyPreviewPopupEnabled(prefs, res));
+ }
+
+ setPreferenceEnabled(Settings.PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST,
+ Settings.readShowsLanguageSwitchKey(prefs));
+
+ final PreferenceGroup textCorrectionGroup =
+ (PreferenceGroup) findPreference(Settings.PREF_CORRECTION_SETTINGS);
+ final PreferenceScreen dictionaryLink =
+ (PreferenceScreen) findPreference(Settings.PREF_CONFIGURE_DICTIONARIES_KEY);
+ final Intent intent = dictionaryLink.getIntent();
+ final int number = context.getPackageManager().queryIntentActivities(intent, 0).size();
+ // TODO: The experimental version is not supported by the Dictionary Pack Service yet
+ if (ProductionFlag.IS_EXPERIMENTAL || 0 >= number) {
+ textCorrectionGroup.removePreference(dictionaryLink);
+ }
+
+ if (!Settings.readFromBuildConfigIfGestureInputEnabled(res)) {
+ removePreference(Settings.PREF_GESTURE_SETTINGS, getPreferenceScreen());
+ }
+
+ final CheckBoxPreference showSetupWizardIcon =
+ (CheckBoxPreference)findPreference(Settings.PREF_SHOW_SETUP_WIZARD_ICON);
+ showSetupWizardIcon.setChecked(Settings.readShowSetupWizardIcon(prefs, context));
+
+ setupKeyLongpressTimeoutSettings(prefs, res);
+ setupKeypressVibrationDurationSettings(prefs, res);
+ setupKeypressSoundVolumeSettings(prefs, res);
+ refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, res);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ final boolean isShortcutImeEnabled = SubtypeSwitcher.getInstance().isShortcutImeEnabled();
+ if (isShortcutImeEnabled) {
+ updateVoiceModeSummary();
+ } else {
+ getPreferenceScreen().removePreference(mVoicePreference);
+ }
+ updateShowCorrectionSuggestionsSummary();
+ updateKeyPreviewPopupDelaySummary();
+ updateCustomInputStylesSummary();
+ }
+
+ @Override
+ public void onDestroy() {
+ getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
+ this);
+ super.onDestroy();
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
+ (new BackupManager(getActivity())).dataChanged();
+ final Resources res = getResources();
+ if (key.equals(Settings.PREF_POPUP_ON)) {
+ setPreferenceEnabled(Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY,
+ Settings.readKeyPreviewPopupEnabled(prefs, res));
+ } else if (key.equals(Settings.PREF_SHOW_LANGUAGE_SWITCH_KEY)) {
+ setPreferenceEnabled(Settings.PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST,
+ Settings.readShowsLanguageSwitchKey(prefs));
+ } else if (key.equals(Settings.PREF_GESTURE_INPUT)) {
+ final boolean gestureInputEnabled = Settings.readGestureInputEnabled(prefs, res);
+ setPreferenceEnabled(Settings.PREF_GESTURE_PREVIEW_TRAIL, gestureInputEnabled);
+ setPreferenceEnabled(Settings.PREF_GESTURE_FLOATING_PREVIEW_TEXT, gestureInputEnabled);
+ } else if (key.equals(Settings.PREF_SHOW_SETUP_WIZARD_ICON)) {
+ LauncherIconVisibilityManager.updateSetupWizardIconVisibility(getActivity());
+ }
+ ensureConsistencyOfAutoCorrectionSettings();
+ updateVoiceModeSummary();
+ updateShowCorrectionSuggestionsSummary();
+ updateKeyPreviewPopupDelaySummary();
+ refreshEnablingsOfKeypressSoundAndVibrationSettings(prefs, getResources());
+ }
+
+ private void ensureConsistencyOfAutoCorrectionSettings() {
+ final String autoCorrectionOff = getResources().getString(
+ R.string.auto_correction_threshold_mode_index_off);
+ final String currentSetting = mAutoCorrectionThresholdPreference.getValue();
+ mBigramPrediction.setEnabled(!currentSetting.equals(autoCorrectionOff));
+ }
+
+ private void updateShowCorrectionSuggestionsSummary() {
+ mShowCorrectionSuggestionsPreference.setSummary(
+ getResources().getStringArray(R.array.prefs_suggestion_visibilities)
+ [mShowCorrectionSuggestionsPreference.findIndexOfValue(
+ mShowCorrectionSuggestionsPreference.getValue())]);
+ }
+
+ private void updateCustomInputStylesSummary() {
+ final PreferenceScreen customInputStyles =
+ (PreferenceScreen)findPreference(Settings.PREF_CUSTOM_INPUT_STYLES);
+ final SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
+ final Resources res = getResources();
+ final String prefSubtype = Settings.readPrefAdditionalSubtypes(prefs, res);
+ final InputMethodSubtype[] subtypes =
+ AdditionalSubtype.createAdditionalSubtypesArray(prefSubtype);
+ final StringBuilder styles = new StringBuilder();
+ for (final InputMethodSubtype subtype : subtypes) {
+ if (styles.length() > 0) styles.append(", ");
+ styles.append(SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype));
+ }
+ customInputStyles.setSummary(styles);
+ }
+
+ private void updateKeyPreviewPopupDelaySummary() {
+ final ListPreference lp = mKeyPreviewPopupDismissDelay;
+ final CharSequence[] entries = lp.getEntries();
+ if (entries == null || entries.length <= 0) return;
+ lp.setSummary(entries[lp.findIndexOfValue(lp.getValue())]);
+ }
+
+ private void updateVoiceModeSummary() {
+ mVoicePreference.setSummary(
+ getResources().getStringArray(R.array.voice_input_modes_summary)
+ [mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]);
+ }
+
+ private void refreshEnablingsOfKeypressSoundAndVibrationSettings(
+ final SharedPreferences sp, final Resources res) {
+ setPreferenceEnabled(Settings.PREF_VIBRATION_DURATION_SETTINGS,
+ Settings.readVibrationEnabled(sp, res));
+ setPreferenceEnabled(Settings.PREF_KEYPRESS_SOUND_VOLUME,
+ Settings.readKeypressSoundEnabled(sp, res));
+ }
+
+ private void setupKeypressVibrationDurationSettings(final SharedPreferences sp,
+ final Resources res) {
+ final SeekBarDialogPreference pref = (SeekBarDialogPreference)findPreference(
+ Settings.PREF_VIBRATION_DURATION_SETTINGS);
+ if (pref == null) {
+ return;
+ }
+ pref.setInterface(new SeekBarDialogPreference.ValueProxy() {
+ @Override
+ public void writeValue(final int value, final String key) {
+ sp.edit().putInt(key, value).apply();
+ }
+
+ @Override
+ public int readValue(final String key) {
+ return Settings.readKeypressVibrationDuration(sp, res);
+ }
+
+ @Override
+ public int readDefaultValue(final String key) {
+ return Settings.readDefaultKeypressVibrationDuration(res);
+ }
+
+ @Override
+ public void feedbackValue(final int value) {
+ AudioAndHapticFeedbackManager.getInstance().vibrate(value);
+ }
+ });
+ }
+
+ private void setupKeyLongpressTimeoutSettings(final SharedPreferences sp,
+ final Resources res) {
+ final SeekBarDialogPreference pref = (SeekBarDialogPreference)findPreference(
+ Settings.PREF_KEY_LONGPRESS_TIMEOUT);
+ if (pref == null) {
+ return;
+ }
+ pref.setInterface(new SeekBarDialogPreference.ValueProxy() {
+ @Override
+ public void writeValue(final int value, final String key) {
+ sp.edit().putInt(key, value).apply();
+ }
+
+ @Override
+ public int readValue(final String key) {
+ return Settings.readKeyLongpressTimeout(sp, res);
+ }
+
+ @Override
+ public int readDefaultValue(final String key) {
+ return Settings.readDefaultKeyLongpressTimeout(res);
+ }
+
+ @Override
+ public void feedbackValue(final int value) {}
+ });
+ }
+
+ private void setupKeypressSoundVolumeSettings(final SharedPreferences sp, final Resources res) {
+ final SeekBarDialogPreference pref = (SeekBarDialogPreference)findPreference(
+ Settings.PREF_KEYPRESS_SOUND_VOLUME);
+ if (pref == null) {
+ return;
+ }
+ final AudioManager am = (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);
+ pref.setInterface(new SeekBarDialogPreference.ValueProxy() {
+ private static final float PERCENTAGE_FLOAT = 100.0f;
+
+ private float getValueFromPercentage(final int percentage) {
+ return percentage / PERCENTAGE_FLOAT;
+ }
+
+ private int getPercentageFromValue(final float floatValue) {
+ return (int)(floatValue * PERCENTAGE_FLOAT);
+ }
+
+ @Override
+ public void writeValue(final int value, final String key) {
+ sp.edit().putFloat(key, getValueFromPercentage(value)).apply();
+ }
+
+ @Override
+ public int readValue(final String key) {
+ return getPercentageFromValue(Settings.readKeypressSoundVolume(sp, res));
+ }
+
+ @Override
+ public int readDefaultValue(final String key) {
+ return getPercentageFromValue(Settings.readDefaultKeypressSoundVolume(res));
+ }
+
+ @Override
+ public void feedbackValue(final int value) {
+ am.playSoundEffect(
+ AudioManager.FX_KEYPRESS_STANDARD, getValueFromPercentage(value));
+ }
+ });
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/SettingsValues.java b/java/src/com/android/inputmethod/latin/SettingsValues.java
index 2f49fe92e..d05868029 100644
--- a/java/src/com/android/inputmethod/latin/SettingsValues.java
+++ b/java/src/com/android/inputmethod/latin/SettingsValues.java
@@ -1,35 +1,32 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.Configuration;
import android.content.res.Resources;
import android.util.Log;
import android.view.inputmethod.EditorInfo;
-import android.view.inputmethod.InputMethodSubtype;
import com.android.inputmethod.keyboard.internal.KeySpecParser;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
/**
* When you call the constructor of this class, you may want to change the current system locale by
@@ -38,26 +35,12 @@ import java.util.HashMap;
public final class SettingsValues {
private static final String TAG = SettingsValues.class.getSimpleName();
- private static final int SUGGESTION_VISIBILITY_SHOW_VALUE
- = R.string.prefs_suggestion_visibility_show_value;
- private static final int SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE
- = R.string.prefs_suggestion_visibility_show_only_portrait_value;
- private static final int SUGGESTION_VISIBILITY_HIDE_VALUE
- = R.string.prefs_suggestion_visibility_hide_value;
-
- private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] {
- SUGGESTION_VISIBILITY_SHOW_VALUE,
- SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE,
- SUGGESTION_VISIBILITY_HIDE_VALUE
- };
-
// From resources:
public final int mDelayUpdateOldSuggestions;
- public final String mWeakSpaceStrippers;
- public final String mWeakSpaceSwappers;
- private final String mPhantomSpacePromotingSymbols;
+ public final int[] mSymbolsPrecededBySpace;
+ public final int[] mSymbolsFollowedBySpace;
+ public final int[] mWordConnectors;
public final SuggestedWords mSuggestPuncList;
- private final String mSymbolsExcludedFromWordSeparators;
public final String mWordSeparators;
public final CharSequence mHintToSaveText;
@@ -67,32 +50,24 @@ public final class SettingsValues {
public final boolean mSoundOn;
public final boolean mKeyPreviewPopupOn;
private final String mVoiceMode;
- private final String mAutoCorrectionThresholdRawValue;
- public final String mShowSuggestionsSetting;
- @SuppressWarnings("unused") // TODO: Use this
- private final boolean mUsabilityStudyMode;
public final boolean mIncludesOtherImesInLanguageSwitchList;
public final boolean mShowsLanguageSwitchKey;
- @SuppressWarnings("unused") // TODO: Use this
- private final String mKeyPreviewPopupDismissDelayRawValue;
public final boolean mUseContactsDict;
+ public final boolean mUseDoubleSpacePeriod;
// Use bigrams to predict the next word when there is no input for it yet
public final boolean mBigramPredictionEnabled;
- @SuppressWarnings("unused") // TODO: Use this
- private final int mVibrationDurationSettingsRawValue;
- @SuppressWarnings("unused") // TODO: Use this
- private final float mKeypressSoundVolumeRawValue;
- private final InputMethodSubtype[] mAdditionalSubtypes;
public final boolean mGestureInputEnabled;
public final boolean mGesturePreviewTrailEnabled;
public final boolean mGestureFloatingPreviewTextEnabled;
+ public final boolean mSlidingKeyInputPreviewEnabled;
+ public final int mKeyLongpressTimeout;
// From the input box
- private final InputAttributes mInputAttributes;
+ public final InputAttributes mInputAttributes;
// Deduced settings
public final int mKeypressVibrationDuration;
- public final float mFxVolume;
+ public final float mKeypressSoundVolume;
public final int mKeyPreviewPopupDismissDelay;
private final boolean mAutoCorrectEnabled;
public final float mAutoCorrectionThreshold;
@@ -101,32 +76,24 @@ public final class SettingsValues {
private final boolean mVoiceKeyEnabled;
private final boolean mVoiceKeyOnMain;
- public SettingsValues(final SharedPreferences prefs, final InputAttributes inputAttributes,
- final Context context) {
- final Resources res = context.getResources();
-
+ public SettingsValues(final SharedPreferences prefs, final Resources res,
+ final InputAttributes inputAttributes) {
// Get the resources
mDelayUpdateOldSuggestions = res.getInteger(R.integer.config_delay_update_old_suggestions);
- mWeakSpaceStrippers = res.getString(R.string.weak_space_stripping_symbols);
- mWeakSpaceSwappers = res.getString(R.string.weak_space_swapping_symbols);
- mPhantomSpacePromotingSymbols = res.getString(R.string.phantom_space_promoting_symbols);
- if (LatinImeLogger.sDBG) {
- final int length = mWeakSpaceStrippers.length();
- for (int i = 0; i < length; i = mWeakSpaceStrippers.offsetByCodePoints(i, 1)) {
- if (isWeakSpaceSwapper(mWeakSpaceStrippers.codePointAt(i))) {
- throw new RuntimeException("Char code " + mWeakSpaceStrippers.codePointAt(i)
- + " is both a weak space swapper and stripper.");
- }
- }
- }
- final String[] suggestPuncsSpec = KeySpecParser.parseCsvString(
- res.getString(R.string.suggested_punctuations), null);
+ mSymbolsPrecededBySpace =
+ StringUtils.toCodePointArray(res.getString(R.string.symbols_preceded_by_space));
+ Arrays.sort(mSymbolsPrecededBySpace);
+ mSymbolsFollowedBySpace =
+ StringUtils.toCodePointArray(res.getString(R.string.symbols_followed_by_space));
+ Arrays.sort(mSymbolsFollowedBySpace);
+ mWordConnectors =
+ StringUtils.toCodePointArray(res.getString(R.string.symbols_word_connectors));
+ Arrays.sort(mWordConnectors);
+ final String[] suggestPuncsSpec = StringUtils.parseCsvString(res.getString(
+ R.string.suggested_punctuations));
mSuggestPuncList = createSuggestPuncList(suggestPuncsSpec);
- mSymbolsExcludedFromWordSeparators =
- res.getString(R.string.symbols_excluded_from_word_separators);
- mWordSeparators = createWordSeparators(mWeakSpaceStrippers, mWeakSpaceSwappers,
- mSymbolsExcludedFromWordSeparators, res);
- mHintToSaveText = context.getText(R.string.hint_add_to_dictionary);
+ mWordSeparators = res.getString(R.string.symbols_word_separators);
+ mHintToSaveText = res.getText(R.string.hint_add_to_dictionary);
// Store the input attributes
if (null == inputAttributes) {
@@ -137,97 +104,43 @@ public final class SettingsValues {
// Get the settings preferences
mAutoCap = prefs.getBoolean(Settings.PREF_AUTO_CAP, true);
- mVibrateOn = isVibrateOn(context, prefs, res);
- mSoundOn = prefs.getBoolean(Settings.PREF_SOUND_ON,
- res.getBoolean(R.bool.config_default_sound_enabled));
- mKeyPreviewPopupOn = isKeyPreviewPopupEnabled(prefs, res);
+ mVibrateOn = Settings.readVibrationEnabled(prefs, res);
+ mSoundOn = Settings.readKeypressSoundEnabled(prefs, res);
+ mKeyPreviewPopupOn = Settings.readKeyPreviewPopupEnabled(prefs, res);
+ mSlidingKeyInputPreviewEnabled = prefs.getBoolean(
+ Settings.PREF_SLIDING_KEY_INPUT_PREVIEW, true);
final String voiceModeMain = res.getString(R.string.voice_mode_main);
final String voiceModeOff = res.getString(R.string.voice_mode_off);
mVoiceMode = prefs.getString(Settings.PREF_VOICE_MODE, voiceModeMain);
- mAutoCorrectionThresholdRawValue = prefs.getString(Settings.PREF_AUTO_CORRECTION_THRESHOLD,
+ final String autoCorrectionThresholdRawValue = prefs.getString(
+ Settings.PREF_AUTO_CORRECTION_THRESHOLD,
res.getString(R.string.auto_correction_threshold_mode_index_modest));
- mShowSuggestionsSetting = prefs.getString(Settings.PREF_SHOW_SUGGESTIONS_SETTING,
- res.getString(R.string.prefs_suggestion_visibility_default_value));
- mUsabilityStudyMode = getUsabilityStudyMode(prefs);
mIncludesOtherImesInLanguageSwitchList = prefs.getBoolean(
Settings.PREF_INCLUDE_OTHER_IMES_IN_LANGUAGE_SWITCH_LIST, false);
- mShowsLanguageSwitchKey = showsLanguageSwitchKey(prefs);
- mKeyPreviewPopupDismissDelayRawValue = prefs.getString(
- Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY,
- Integer.toString(res.getInteger(R.integer.config_key_preview_linger_timeout)));
+ mShowsLanguageSwitchKey = Settings.readShowsLanguageSwitchKey(prefs);
mUseContactsDict = prefs.getBoolean(Settings.PREF_KEY_USE_CONTACTS_DICT, true);
- mAutoCorrectEnabled = isAutoCorrectEnabled(res, mAutoCorrectionThresholdRawValue);
- mBigramPredictionEnabled = isBigramPredictionEnabled(prefs, res);
- mVibrationDurationSettingsRawValue =
- prefs.getInt(Settings.PREF_VIBRATION_DURATION_SETTINGS, -1);
- mKeypressSoundVolumeRawValue = prefs.getFloat(Settings.PREF_KEYPRESS_SOUND_VOLUME, -1.0f);
+ mUseDoubleSpacePeriod = prefs.getBoolean(Settings.PREF_KEY_USE_DOUBLE_SPACE_PERIOD, true);
+ mAutoCorrectEnabled = Settings.readAutoCorrectEnabled(autoCorrectionThresholdRawValue, res);
+ mBigramPredictionEnabled = readBigramPredictionEnabled(prefs, res);
// Compute other readable settings
- mKeypressVibrationDuration = getCurrentVibrationDuration(prefs, res);
- mFxVolume = getCurrentKeypressSoundVolume(prefs, res);
- mKeyPreviewPopupDismissDelay = getKeyPreviewPopupDismissDelay(prefs, res);
- mAutoCorrectionThreshold = getAutoCorrectionThreshold(res,
- mAutoCorrectionThresholdRawValue);
+ mKeyLongpressTimeout = Settings.readKeyLongpressTimeout(prefs, res);
+ mKeypressVibrationDuration = Settings.readKeypressVibrationDuration(prefs, res);
+ mKeypressSoundVolume = Settings.readKeypressSoundVolume(prefs, res);
+ mKeyPreviewPopupDismissDelay = Settings.readKeyPreviewPopupDismissDelay(prefs, res);
+ mAutoCorrectionThreshold = readAutoCorrectionThreshold(res,
+ autoCorrectionThresholdRawValue);
mVoiceKeyEnabled = mVoiceMode != null && !mVoiceMode.equals(voiceModeOff);
mVoiceKeyOnMain = mVoiceMode != null && mVoiceMode.equals(voiceModeMain);
- mAdditionalSubtypes = AdditionalSubtype.createAdditionalSubtypesArray(
- getPrefAdditionalSubtypes(prefs, res));
- final boolean gestureInputEnabledByBuildConfig = res.getBoolean(
- R.bool.config_gesture_input_enabled_by_build_config);
- mGestureInputEnabled = gestureInputEnabledByBuildConfig
- && prefs.getBoolean(Settings.PREF_GESTURE_INPUT, true);
+ mGestureInputEnabled = Settings.readGestureInputEnabled(prefs, res);
mGesturePreviewTrailEnabled = prefs.getBoolean(Settings.PREF_GESTURE_PREVIEW_TRAIL, true);
mGestureFloatingPreviewTextEnabled = prefs.getBoolean(
Settings.PREF_GESTURE_FLOATING_PREVIEW_TEXT, true);
mCorrectionEnabled = mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect;
- mSuggestionVisibility = createSuggestionVisibility(res);
- }
-
- // Helper functions to create member values.
- private static SuggestedWords createSuggestPuncList(final String[] puncs) {
- final ArrayList<SuggestedWordInfo> puncList = CollectionUtils.newArrayList();
- if (puncs != null) {
- for (final String puncSpec : puncs) {
- puncList.add(new SuggestedWordInfo(KeySpecParser.getLabel(puncSpec),
- SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.KIND_HARDCODED,
- Dictionary.TYPE_HARDCODED));
- }
- }
- return new SuggestedWords(puncList,
- false /* typedWordValid */,
- false /* hasAutoCorrectionCandidate */,
- true /* isPunctuationSuggestions */,
- false /* isObsoleteSuggestions */,
- false /* isPrediction */);
- }
-
- private static String createWordSeparators(final String weakSpaceStrippers,
- final String weakSpaceSwappers, final String symbolsExcludedFromWordSeparators,
- final Resources res) {
- String wordSeparators = weakSpaceStrippers + weakSpaceSwappers
- + res.getString(R.string.phantom_space_promoting_symbols);
- for (int i = symbolsExcludedFromWordSeparators.length() - 1; i >= 0; --i) {
- wordSeparators = wordSeparators.replace(
- symbolsExcludedFromWordSeparators.substring(i, i + 1), "");
- }
- return wordSeparators;
- }
-
- private int createSuggestionVisibility(final Resources res) {
- final String suggestionVisiblityStr = mShowSuggestionsSetting;
- for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) {
- if (suggestionVisiblityStr.equals(res.getString(visibility))) {
- return visibility;
- }
- }
- throw new RuntimeException("Bug: visibility string is not configured correctly");
- }
-
- private static boolean isVibrateOn(final Context context, final SharedPreferences prefs,
- final Resources res) {
- final boolean hasVibrator = VibratorUtils.getInstance(context).hasVibrator();
- return hasVibrator && prefs.getBoolean(Settings.PREF_VIBRATE_ON,
- res.getBoolean(R.bool.config_default_vibration_enabled));
+ final String showSuggestionsSetting = prefs.getString(
+ Settings.PREF_SHOW_SUGGESTIONS_SETTING,
+ res.getString(R.string.prefs_suggestion_visibility_default_value));
+ mSuggestionVisibility = createSuggestionVisibility(res, showSuggestionsSetting);
}
public boolean isApplicationSpecifiedCompletionsOn() {
@@ -250,87 +163,22 @@ public final class SettingsValues {
return mWordSeparators.contains(String.valueOf((char)code));
}
- public boolean isSymbolExcludedFromWordSeparators(final int code) {
- return mSymbolsExcludedFromWordSeparators.contains(String.valueOf((char)code));
+ public boolean isWordConnector(final int code) {
+ return Arrays.binarySearch(mWordConnectors, code) >= 0;
}
- // TODO: use "Phantom" instead of "Weak" in this method name
- public boolean isWeakSpaceStripper(final int code) {
- // TODO: this does not work if the code does not fit in a char
- return mWeakSpaceStrippers.contains(String.valueOf((char)code));
+ public boolean isUsuallyPrecededBySpace(final int code) {
+ return Arrays.binarySearch(mSymbolsPrecededBySpace, code) >= 0;
}
- // TODO: use "Phantom" instead of "Weak" in this method name
- public boolean isWeakSpaceSwapper(final int code) {
- // TODO: this does not work if the code does not fit in a char
- return mWeakSpaceSwappers.contains(String.valueOf((char)code));
- }
-
- public boolean isPhantomSpacePromotingSymbol(final int code) {
- // TODO: this does not work if the code does not fit in a char
- return mPhantomSpacePromotingSymbols.contains(String.valueOf((char)code));
+ public boolean isUsuallyFollowedBySpace(final int code) {
+ return Arrays.binarySearch(mSymbolsFollowedBySpace, code) >= 0;
}
public boolean shouldInsertSpacesAutomatically() {
return mInputAttributes.mShouldInsertSpacesAutomatically;
}
- private static boolean isAutoCorrectEnabled(final Resources res,
- final String currentAutoCorrectionSetting) {
- final String autoCorrectionOff = res.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(final SharedPreferences prefs,
- final Resources res) {
- final boolean showPopupOption = res.getBoolean(
- R.bool.config_enable_show_popup_on_keypress_option);
- if (!showPopupOption) return res.getBoolean(R.bool.config_default_popup_preview);
- return prefs.getBoolean(Settings.PREF_POPUP_ON,
- res.getBoolean(R.bool.config_default_popup_preview));
- }
-
- // Likewise
- public static int getKeyPreviewPopupDismissDelay(final SharedPreferences prefs,
- final Resources res) {
- // TODO: use mKeyPreviewPopupDismissDelayRawValue instead of reading it again here.
- return Integer.parseInt(prefs.getString(Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY,
- Integer.toString(res.getInteger(
- R.integer.config_key_preview_linger_timeout))));
- }
-
- private static boolean isBigramPredictionEnabled(final SharedPreferences prefs,
- final Resources res) {
- return prefs.getBoolean(Settings.PREF_BIGRAM_PREDICTIONS, res.getBoolean(
- R.bool.config_default_next_word_prediction));
- }
-
- private static float getAutoCorrectionThreshold(final Resources res,
- final String currentAutoCorrectionSetting) {
- final String[] autoCorrectionThresholdValues = res.getStringArray(
- R.array.auto_correction_threshold_values);
- // When autoCorrectionThreshold is greater than 1.0, it's like auto correction is off.
- float autoCorrectionThreshold = Float.MAX_VALUE;
- try {
- final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting);
- if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) {
- autoCorrectionThreshold = Float.parseFloat(
- autoCorrectionThresholdValues[arrayIndex]);
- }
- } catch (NumberFormatException e) {
- // Whenever the threshold settings are correct, never come here.
- autoCorrectionThreshold = Float.MAX_VALUE;
- Log.w(TAG, "Cannot load auto correction threshold setting."
- + " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting
- + ", autoCorrectionThresholdValues: "
- + Arrays.toString(autoCorrectionThresholdValues));
- }
- return autoCorrectionThreshold;
- }
-
public boolean isVoiceKeyEnabled(final EditorInfo editorInfo) {
final boolean shortcutImeEnabled = SubtypeSwitcher.getInstance().isShortcutImeEnabled();
final int inputType = (editorInfo != null) ? editorInfo.inputType : 0;
@@ -342,108 +190,89 @@ public final class SettingsValues {
return mVoiceKeyOnMain;
}
- // This preference key is deprecated. Use {@link #PREF_SHOW_LANGUAGE_SWITCH_KEY} instead.
- // This is being used only for the backward compatibility.
- private static final String PREF_SUPPRESS_LANGUAGE_SWITCH_KEY =
- "pref_suppress_language_switch_key";
-
- public static boolean showsLanguageSwitchKey(final SharedPreferences prefs) {
- if (prefs.contains(PREF_SUPPRESS_LANGUAGE_SWITCH_KEY)) {
- final boolean suppressLanguageSwitchKey = prefs.getBoolean(
- PREF_SUPPRESS_LANGUAGE_SWITCH_KEY, false);
- final SharedPreferences.Editor editor = prefs.edit();
- editor.remove(PREF_SUPPRESS_LANGUAGE_SWITCH_KEY);
- editor.putBoolean(Settings.PREF_SHOW_LANGUAGE_SWITCH_KEY, !suppressLanguageSwitchKey);
- editor.apply();
- }
- return prefs.getBoolean(Settings.PREF_SHOW_LANGUAGE_SWITCH_KEY, true);
- }
-
- public boolean isLanguageSwitchKeyEnabled(final Context context) {
+ public boolean isLanguageSwitchKeyEnabled() {
if (!mShowsLanguageSwitchKey) {
return false;
}
+ final RichInputMethodManager imm = RichInputMethodManager.getInstance();
if (mIncludesOtherImesInLanguageSwitchList) {
- return ImfUtils.hasMultipleEnabledIMEsOrSubtypes(
- context, /* include aux subtypes */false);
+ return imm.hasMultipleEnabledIMEsOrSubtypes(false /* include aux subtypes */);
} else {
- return ImfUtils.hasMultipleEnabledSubtypesInThisIme(
- context, /* include aux subtypes */false);
+ return imm.hasMultipleEnabledSubtypesInThisIme(false /* include aux subtypes */);
}
}
- public static boolean isFullscreenModeAllowed(final Resources res) {
- return res.getBoolean(R.bool.config_use_fullscreen_mode);
+ public boolean isSameInputType(final EditorInfo editorInfo) {
+ return mInputAttributes.isSameInputType(editorInfo);
}
- public InputMethodSubtype[] getAdditionalSubtypes() {
- return mAdditionalSubtypes;
+ // Helper functions to create member values.
+ private static SuggestedWords createSuggestPuncList(final String[] puncs) {
+ final ArrayList<SuggestedWordInfo> puncList = CollectionUtils.newArrayList();
+ if (puncs != null) {
+ for (final String puncSpec : puncs) {
+ // TODO: Stop using KeySpceParser.getLabel().
+ puncList.add(new SuggestedWordInfo(KeySpecParser.getLabel(puncSpec),
+ SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.KIND_HARDCODED,
+ Dictionary.TYPE_HARDCODED));
+ }
+ }
+ return new SuggestedWords(puncList,
+ false /* typedWordValid */,
+ false /* hasAutoCorrectionCandidate */,
+ true /* isPunctuationSuggestions */,
+ false /* isObsoleteSuggestions */,
+ false /* isPrediction */);
}
- public static String getPrefAdditionalSubtypes(final SharedPreferences prefs,
- final Resources res) {
- final String predefinedPrefSubtypes = AdditionalSubtype.createPrefSubtypes(
- res.getStringArray(R.array.predefined_subtypes));
- return prefs.getString(Settings.PREF_CUSTOM_INPUT_STYLES, predefinedPrefSubtypes);
- }
+ private static final int SUGGESTION_VISIBILITY_SHOW_VALUE =
+ R.string.prefs_suggestion_visibility_show_value;
+ private static final int SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE =
+ R.string.prefs_suggestion_visibility_show_only_portrait_value;
+ private static final int SUGGESTION_VISIBILITY_HIDE_VALUE =
+ R.string.prefs_suggestion_visibility_hide_value;
+ private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] {
+ SUGGESTION_VISIBILITY_SHOW_VALUE,
+ SUGGESTION_VISIBILITY_SHOW_ONLY_PORTRAIT_VALUE,
+ SUGGESTION_VISIBILITY_HIDE_VALUE
+ };
- // Accessed from the settings interface, hence public
- public static float getCurrentKeypressSoundVolume(final SharedPreferences prefs,
- final Resources res) {
- // TODO: use mVibrationDurationSettingsRawValue instead of reading it again here
- final float volume = prefs.getFloat(Settings.PREF_KEYPRESS_SOUND_VOLUME, -1.0f);
- if (volume >= 0) {
- return volume;
+ private static int createSuggestionVisibility(final Resources res,
+ final String suggestionVisiblityStr) {
+ for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) {
+ if (suggestionVisiblityStr.equals(res.getString(visibility))) {
+ return visibility;
+ }
}
-
- return Float.parseFloat(ResourceUtils.getDeviceOverrideValue(
- res, R.array.keypress_volumes, "-1.0f"));
+ throw new RuntimeException("Bug: visibility string is not configured correctly");
}
- // Likewise
- public static int getCurrentVibrationDuration(final SharedPreferences prefs,
+ private static boolean readBigramPredictionEnabled(final SharedPreferences prefs,
final Resources res) {
- // TODO: use mKeypressVibrationDuration instead of reading it again here
- final int ms = prefs.getInt(Settings.PREF_VIBRATION_DURATION_SETTINGS, -1);
- if (ms >= 0) {
- return ms;
- }
-
- return Integer.parseInt(ResourceUtils.getDeviceOverrideValue(
- res, R.array.keypress_vibration_durations, "-1"));
- }
-
- // Likewise
- public static boolean getUsabilityStudyMode(final SharedPreferences prefs) {
- // TODO: use mUsabilityStudyMode instead of reading it again here
- return prefs.getBoolean(DebugSettings.PREF_USABILITY_STUDY_MODE, true);
+ return prefs.getBoolean(Settings.PREF_BIGRAM_PREDICTIONS, res.getBoolean(
+ R.bool.config_default_next_word_prediction));
}
- public static long getLastUserHistoryWriteTime(final SharedPreferences prefs,
- final String locale) {
- final String str = prefs.getString(Settings.PREF_LAST_USER_DICTIONARY_WRITE_TIME, "");
- final HashMap<String, Long> map = LocaleUtils.localeAndTimeStrToHashMap(str);
- if (map.containsKey(locale)) {
- return map.get(locale);
+ private static float readAutoCorrectionThreshold(final Resources res,
+ final String currentAutoCorrectionSetting) {
+ final String[] autoCorrectionThresholdValues = res.getStringArray(
+ R.array.auto_correction_threshold_values);
+ // When autoCorrectionThreshold is greater than 1.0, it's like auto correction is off.
+ float autoCorrectionThreshold = Float.MAX_VALUE;
+ try {
+ final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting);
+ if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) {
+ autoCorrectionThreshold = Float.parseFloat(
+ autoCorrectionThresholdValues[arrayIndex]);
+ }
+ } catch (NumberFormatException e) {
+ // Whenever the threshold settings are correct, never come here.
+ autoCorrectionThreshold = Float.MAX_VALUE;
+ Log.w(TAG, "Cannot load auto correction threshold setting."
+ + " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting
+ + ", autoCorrectionThresholdValues: "
+ + Arrays.toString(autoCorrectionThresholdValues));
}
- return 0;
- }
-
- public static void setLastUserHistoryWriteTime(final SharedPreferences prefs,
- final String locale) {
- final String oldStr = prefs.getString(Settings.PREF_LAST_USER_DICTIONARY_WRITE_TIME, "");
- final HashMap<String, Long> map = LocaleUtils.localeAndTimeStrToHashMap(oldStr);
- map.put(locale, System.currentTimeMillis());
- final String newStr = LocaleUtils.localeAndTimeHashMapToStr(map);
- prefs.edit().putString(Settings.PREF_LAST_USER_DICTIONARY_WRITE_TIME, newStr).apply();
- }
-
- public boolean isSameInputType(final EditorInfo editorInfo) {
- return mInputAttributes.isSameInputType(editorInfo);
- }
-
- // For debug.
- public String getInputAttributesDebugString() {
- return mInputAttributes.toString();
+ return autoCorrectionThreshold;
}
}
diff --git a/java/src/com/android/inputmethod/latin/StringUtils.java b/java/src/com/android/inputmethod/latin/StringUtils.java
index df7709892..90c3fcdd2 100644
--- a/java/src/com/android/inputmethod/latin/StringUtils.java
+++ b/java/src/com/android/inputmethod/latin/StringUtils.java
@@ -18,8 +18,6 @@ package com.android.inputmethod.latin;
import android.text.TextUtils;
-import com.android.inputmethod.keyboard.Keyboard; // For character constants
-
import java.util.ArrayList;
import java.util.Locale;
@@ -28,30 +26,30 @@ public final class StringUtils {
// This utility class is not publicly instantiable.
}
- public static int codePointCount(String text) {
+ public static int codePointCount(final String text) {
if (TextUtils.isEmpty(text)) return 0;
return text.codePointCount(0, text.length());
}
- public static boolean containsInArray(String key, String[] array) {
+ public static boolean containsInArray(final String key, final String[] array) {
for (final String element : array) {
if (key.equals(element)) return true;
}
return false;
}
- public static boolean containsInCsv(String key, String csv) {
+ public static boolean containsInCsv(final String key, final String csv) {
if (TextUtils.isEmpty(csv)) return false;
return containsInArray(key, csv.split(","));
}
- public static String appendToCsvIfNotExists(String key, String csv) {
+ public static String appendToCsvIfNotExists(final String key, final String csv) {
if (TextUtils.isEmpty(csv)) return key;
if (containsInCsv(key, csv)) return csv;
return csv + "," + key;
}
- public static String removeFromCsvIfExists(String key, String csv) {
+ public static String removeFromCsvIfExists(final String key, final String csv) {
if (TextUtils.isEmpty(csv)) return "";
final String[] elements = csv.split(",");
if (!containsInArray(key, elements)) return csv;
@@ -63,65 +61,20 @@ public final class StringUtils {
}
/**
- * 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}.
+ * Find a string that start with specified prefix from an array.
+ *
+ * @param prefix a prefix string to find.
+ * @param array an string array to be searched.
+ * @return the rest part of the string that starts with the prefix.
+ * Returns null if it couldn't be found.
*/
- 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;
+ public static String findPrefixedString(final String prefix, final String[] array) {
+ for (final String element : array) {
+ if (element.startsWith(prefix)) {
+ return element.substring(prefix.length());
+ }
}
- return true;
+ return null;
}
/**
@@ -130,15 +83,15 @@ public final class StringUtils {
* This method will always keep the first occurrence of all strings at their position
* in the array, removing the subsequent ones.
*/
- public static void removeDupes(final ArrayList<CharSequence> suggestions) {
+ public static void removeDupes(final ArrayList<String> suggestions) {
if (suggestions.size() < 2) return;
int i = 1;
// Don't cache suggestions.size(), since we may be removing items
while (i < suggestions.size()) {
- final CharSequence cur = suggestions.get(i);
+ final String cur = suggestions.get(i);
// Compare each suggestion with each previous suggestion
for (int j = 0; j < i; j++) {
- CharSequence previous = suggestions.get(j);
+ final String previous = suggestions.get(j);
if (TextUtils.equals(cur, previous)) {
suggestions.remove(i);
i--;
@@ -149,7 +102,7 @@ public final class StringUtils {
}
}
- public static String toTitleCase(String s, Locale locale) {
+ public static String toTitleCase(final String s, final Locale locale) {
if (s.length() <= 1) {
// TODO: is this really correct? Shouldn't this be s.toUpperCase()?
return s;
@@ -165,228 +118,57 @@ public final class StringUtils {
return s.toUpperCase(locale).charAt(0) + s.substring(1);
}
+ private static final int[] EMPTY_CODEPOINTS = {};
+
public static int[] toCodePointArray(final String string) {
- final char[] characters = string.toCharArray();
- final int length = characters.length;
- final int[] codePoints = new int[Character.codePointCount(characters, 0, length)];
+ final int length = string.length();
if (length <= 0) {
- return new int[0];
+ return EMPTY_CODEPOINTS;
}
- int codePoint = Character.codePointAt(characters, 0);
- int dsti = 0;
- for (int srci = Character.charCount(codePoint);
- srci < length; srci += Character.charCount(codePoint), ++dsti) {
- codePoints[dsti] = codePoint;
- codePoint = Character.codePointAt(characters, srci);
+ final int[] codePoints = new int[string.codePointCount(0, length)];
+ int destIndex = 0;
+ for (int index = 0; index < length; index = string.offsetByCodePoints(index, 1)) {
+ codePoints[destIndex] = string.codePointAt(index);
+ destIndex++;
}
- codePoints[dsti] = codePoint;
return codePoints;
}
- /**
- * Determine what caps mode should be in effect at the current offset in
- * the text. Only the mode bits set in <var>reqModes</var> will be
- * checked. Note that the caps mode flags here are explicitly defined
- * to match those in {@link InputType}.
- *
- * This code is a straight copy of TextUtils.getCapsMode (modulo namespace and formatting
- * issues). This will change in the future as we simplify the code for our use and fix bugs.
- *
- * @param cs The text that should be checked for caps modes.
- * @param reqModes The modes to be checked: may be any combination of
- * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
- * {@link TextUtils#CAP_MODE_SENTENCES}.
- * @param locale The locale to consider for capitalization rules
- * @param hasSpaceBefore Whether we should consider there is a space inserted at the end of cs
- *
- * @return Returns the actual capitalization modes that can be in effect
- * at the current position, which is any combination of
- * {@link TextUtils#CAP_MODE_CHARACTERS}, {@link TextUtils#CAP_MODE_WORDS}, and
- * {@link TextUtils#CAP_MODE_SENTENCES}.
- */
- public static int getCapsMode(final CharSequence cs, final int reqModes, final Locale locale,
- final boolean hasSpaceBefore) {
- // Quick description of what we want to do:
- // CAP_MODE_CHARACTERS is always on.
- // CAP_MODE_WORDS is on if there is some whitespace before the cursor.
- // CAP_MODE_SENTENCES is on if there is some whitespace before the cursor, and the end
- // of a sentence just before that.
- // We ignore opening parentheses and the like just before the cursor for purposes of
- // finding whitespace for WORDS and SENTENCES modes.
- // The end of a sentence ends with a period, question mark or exclamation mark. If it's
- // a period, it also needs not to be an abbreviation, which means it also needs to either
- // be immediately preceded by punctuation, or by a string of only letters with single
- // periods interleaved.
-
- // Step 1 : check for cap MODE_CHARACTERS. If it's looked for, it's always on.
- if ((reqModes & (TextUtils.CAP_MODE_WORDS | TextUtils.CAP_MODE_SENTENCES)) == 0) {
- // Here we are not looking for MODE_WORDS or MODE_SENTENCES, so since we already
- // evaluated MODE_CHARACTERS, we can return.
- return TextUtils.CAP_MODE_CHARACTERS & reqModes;
- }
-
- // Step 2 : Skip (ignore at the end of input) any opening punctuation. This includes
- // opening parentheses, brackets, opening quotes, everything that *opens* a span of
- // text in the linguistic sense. In RTL languages, this is still an opening sign, although
- // it may look like a right parenthesis for example. We also include double quote and
- // single quote since they aren't start punctuation in the unicode sense, but should still
- // be skipped for English. TODO: does this depend on the language?
- int i;
- if (hasSpaceBefore) {
- i = cs.length() + 1;
- } else {
- for (i = cs.length(); i > 0; i--) {
- final char c = cs.charAt(i - 1);
- if (c != Keyboard.CODE_DOUBLE_QUOTE && c != Keyboard.CODE_SINGLE_QUOTE
- && Character.getType(c) != Character.START_PUNCTUATION) {
- break;
- }
- }
- }
-
- // We are now on the character that precedes any starting punctuation, so in the most
- // frequent case this will be whitespace or a letter, although it may occasionally be a
- // start of line, or some symbol.
-
- // Step 3 : Search for the start of a paragraph. From the starting point computed in step 2,
- // we go back over any space or tab char sitting there. We find the start of a paragraph
- // if the first char that's not a space or tab is a start of line (as in \n, start of text,
- // or some other similar characters).
- int j = i;
- char prevChar = Keyboard.CODE_SPACE;
- if (hasSpaceBefore) --j;
- while (j > 0) {
- prevChar = cs.charAt(j - 1);
- if (!Character.isSpaceChar(prevChar) && prevChar != Keyboard.CODE_TAB) break;
- j--;
- }
- if (j <= 0 || Character.isWhitespace(prevChar)) {
- // There are only spacing chars between the start of the paragraph and the cursor,
- // defined as a isWhitespace() char that is neither a isSpaceChar() nor a tab. Both
- // MODE_WORDS and MODE_SENTENCES should be active.
- return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
- | TextUtils.CAP_MODE_SENTENCES) & reqModes;
- }
- if (i == j) {
- // If we don't have whitespace before index i, it means neither MODE_WORDS
- // nor mode sentences should be on so we can return right away.
- return TextUtils.CAP_MODE_CHARACTERS & reqModes;
- }
- if ((reqModes & TextUtils.CAP_MODE_SENTENCES) == 0) {
- // Here we know we have whitespace before the cursor (if not, we returned in the above
- // if i == j clause), so we need MODE_WORDS to be on. And we don't need to evaluate
- // MODE_SENTENCES so we can return right away.
- return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
- }
- // Please note that because of the reqModes & CAP_MODE_SENTENCES test a few lines above,
- // we know that MODE_SENTENCES is being requested.
-
- // Step 4 : Search for MODE_SENTENCES.
- // English is a special case in that "American typography" rules, which are the most common
- // in English, state that a sentence terminator immediately following a quotation mark
- // should be swapped with it and de-duplicated (included in the quotation mark),
- // e.g. <<Did he say, "let's go home?">>
- // No other language has such a rule as far as I know, instead putting inside the quotation
- // mark as the exact thing quoted and handling the surrounding punctuation independently,
- // e.g. <<Did he say, "let's go home"?>>
- // Hence, specifically for English, we treat this special case here.
- if (Locale.ENGLISH.getLanguage().equals(locale.getLanguage())) {
- for (; j > 0; j--) {
- // Here we look to go over any closing punctuation. This is because in dominant
- // variants of English, the final period is placed within double quotes and maybe
- // other closing punctuation signs. This is generally not true in other languages.
- final char c = cs.charAt(j - 1);
- if (c != Keyboard.CODE_DOUBLE_QUOTE && c != Keyboard.CODE_SINGLE_QUOTE
- && Character.getType(c) != Character.END_PUNCTUATION) {
- break;
+ public static String[] parseCsvString(final String text) {
+ final int size = text.length();
+ if (size == 0) {
+ return null;
+ }
+ if (codePointCount(text) == 1) {
+ return text.codePointAt(0) == Constants.CSV_SEPARATOR ? null : new String[] { text };
+ }
+
+ ArrayList<String> list = null;
+ int start = 0;
+ for (int pos = 0; pos < size; pos++) {
+ final char c = text.charAt(pos);
+ if (c == Constants.CSV_SEPARATOR) {
+ // Skip empty entry.
+ if (pos - start > 0) {
+ if (list == null) {
+ list = CollectionUtils.newArrayList();
+ }
+ list.add(text.substring(start, pos));
}
+ // Skip comma
+ start = pos + 1;
+ } else if (c == Constants.CSV_ESCAPE) {
+ // Skip escape character and escaped character.
+ pos++;
}
}
-
- if (j <= 0) return TextUtils.CAP_MODE_CHARACTERS & reqModes;
- char c = cs.charAt(--j);
-
- // We found the next interesting chunk of text ; next we need to determine if it's the
- // end of a sentence. If we have a question mark or an exclamation mark, it's the end of
- // a sentence. If it's neither, the only remaining case is the period so we get the opposite
- // case out of the way.
- if (c == Keyboard.CODE_QUESTION_MARK || c == Keyboard.CODE_EXCLAMATION_MARK) {
- return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_SENTENCES) & reqModes;
- }
- if (c != Keyboard.CODE_PERIOD || j <= 0) {
- return (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
+ final String remain = (size - start > 0) ? text.substring(start) : null;
+ if (list == null) {
+ return remain != null ? new String[] { remain } : null;
}
-
- // We found out that we have a period. We need to determine if this is a full stop or
- // otherwise sentence-ending period, or an abbreviation like "e.g.". An abbreviation
- // looks like (\w\.){2,}
- // To find out, we will have a simple state machine with the following states :
- // START, WORD, PERIOD, ABBREVIATION
- // On START : (just before the first period)
- // letter => WORD
- // whitespace => end with no caps (it was a stand-alone period)
- // otherwise => end with caps (several periods/symbols in a row)
- // On WORD : (within the word just before the first period)
- // letter => WORD
- // period => PERIOD
- // otherwise => end with caps (it was a word with a full stop at the end)
- // On PERIOD : (period within a potential abbreviation)
- // letter => LETTER
- // otherwise => end with caps (it was not an abbreviation)
- // On LETTER : (letter within a potential abbreviation)
- // letter => LETTER
- // period => PERIOD
- // otherwise => end with no caps (it was an abbreviation)
- // "Not an abbreviation" in the above chart essentially covers cases like "...yes.". This
- // should capitalize.
-
- final int START = 0;
- final int WORD = 1;
- final int PERIOD = 2;
- final int LETTER = 3;
- final int caps = (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS
- | TextUtils.CAP_MODE_SENTENCES) & reqModes;
- final int noCaps = (TextUtils.CAP_MODE_CHARACTERS | TextUtils.CAP_MODE_WORDS) & reqModes;
- int state = START;
- while (j > 0) {
- c = cs.charAt(--j);
- switch (state) {
- case START:
- if (Character.isLetter(c)) {
- state = WORD;
- } else if (Character.isWhitespace(c)) {
- return noCaps;
- } else {
- return caps;
- }
- break;
- case WORD:
- if (Character.isLetter(c)) {
- state = WORD;
- } else if (c == Keyboard.CODE_PERIOD) {
- state = PERIOD;
- } else {
- return caps;
- }
- break;
- case PERIOD:
- if (Character.isLetter(c)) {
- state = LETTER;
- } else {
- return caps;
- }
- break;
- case LETTER:
- if (Character.isLetter(c)) {
- state = LETTER;
- } else if (c == Keyboard.CODE_PERIOD) {
- state = PERIOD;
- } else {
- return noCaps;
- }
- }
+ if (remain != null) {
+ list.add(remain);
}
- // Here we arrived at the start of the line. This should behave exactly like whitespace.
- return (START == state || LETTER == state) ? noCaps : caps;
+ return list.toArray(new String[list.size()]);
}
}
diff --git a/java/src/com/android/inputmethod/latin/SubtypeLocale.java b/java/src/com/android/inputmethod/latin/SubtypeLocale.java
index 579f96bb4..9cbfe6698 100644
--- a/java/src/com/android/inputmethod/latin/SubtypeLocale.java
+++ b/java/src/com/android/inputmethod/latin/SubtypeLocale.java
@@ -42,6 +42,7 @@ public final class SubtypeLocale {
public static final int UNKNOWN_KEYBOARD_LAYOUT = R.string.subtype_generic;
private static boolean sInitialized = false;
+ private static Resources sResources;
private static String[] sPredefinedKeyboardLayoutSet;
// Keyboard layout to its display name map.
private static final HashMap<String, String> sKeyboardLayoutToDisplayNameMap =
@@ -50,20 +51,22 @@ public final class SubtypeLocale {
private static final HashMap<String, Integer> sKeyboardLayoutToNameIdsMap =
CollectionUtils.newHashMap();
// Exceptional locale to subtype name resource id map.
+ private static final HashMap<String, Integer> sExceptionalLocaleToNameIdsMap =
+ CollectionUtils.newHashMap();
+ // Exceptional locale to subtype name with layout resource id map.
private static final HashMap<String, Integer> sExceptionalLocaleToWithLayoutNameIdsMap =
CollectionUtils.newHashMap();
+ private static final String SUBTYPE_NAME_RESOURCE_PREFIX =
+ "string/subtype_";
private static final String SUBTYPE_NAME_RESOURCE_GENERIC_PREFIX =
"string/subtype_generic_";
private static final String SUBTYPE_NAME_RESOURCE_WITH_LAYOUT_PREFIX =
"string/subtype_with_layout_";
private static final String SUBTYPE_NAME_RESOURCE_NO_LANGUAGE_PREFIX =
"string/subtype_no_language_";
- // Exceptional locales to display name map.
- private static final HashMap<String, String> sExceptionalDisplayNamesMap =
- CollectionUtils.newHashMap();
// Keyboard layout set name for the subtypes that don't have a keyboardLayoutSet extra value.
// This is for compatibility to keep the same subtype ids as pre-JellyBean.
- private static final HashMap<String,String> sLocaleAndExtraValueToKeyboardLayoutSetMap =
+ private static final HashMap<String, String> sLocaleAndExtraValueToKeyboardLayoutSetMap =
CollectionUtils.newHashMap();
private SubtypeLocale() {
@@ -71,10 +74,11 @@ public final class SubtypeLocale {
}
// Note that this initialization method can be called multiple times.
- public static synchronized void init(Context context) {
+ public static synchronized void init(final Context context) {
if (sInitialized) return;
final Resources res = context.getResources();
+ sResources = res;
final String[] predefinedLayoutSet = res.getStringArray(R.array.predefined_layouts);
sPredefinedKeyboardLayoutSet = predefinedLayoutSet;
@@ -96,14 +100,16 @@ public final class SubtypeLocale {
final String[] exceptionalLocales = res.getStringArray(
R.array.subtype_locale_exception_keys);
- final String[] exceptionalDisplayNames = res.getStringArray(
- R.array.subtype_locale_exception_values);
for (int i = 0; i < exceptionalLocales.length; i++) {
final String localeString = exceptionalLocales[i];
- sExceptionalDisplayNamesMap.put(localeString, exceptionalDisplayNames[i]);
- final String resourceName = SUBTYPE_NAME_RESOURCE_WITH_LAYOUT_PREFIX + localeString;
+ final String resourceName = SUBTYPE_NAME_RESOURCE_PREFIX + localeString;
final int resId = res.getIdentifier(resourceName, null, RESOURCE_PACKAGE_NAME);
- sExceptionalLocaleToWithLayoutNameIdsMap.put(localeString, resId);
+ sExceptionalLocaleToNameIdsMap.put(localeString, resId);
+ final String resourceNameWithLayout =
+ SUBTYPE_NAME_RESOURCE_WITH_LAYOUT_PREFIX + localeString;
+ final int resIdWithLayout = res.getIdentifier(
+ resourceNameWithLayout, null, RESOURCE_PACKAGE_NAME);
+ sExceptionalLocaleToWithLayoutNameIdsMap.put(localeString, resIdWithLayout);
}
final String[] keyboardLayoutSetMap = res.getStringArray(
@@ -121,64 +127,115 @@ public final class SubtypeLocale {
return sPredefinedKeyboardLayoutSet;
}
- public static boolean isExceptionalLocale(String localeString) {
- return sExceptionalLocaleToWithLayoutNameIdsMap.containsKey(localeString);
+ public static boolean isExceptionalLocale(final String localeString) {
+ return sExceptionalLocaleToNameIdsMap.containsKey(localeString);
}
- private static final String getNoLanguageLayoutKey(String keyboardLayoutName) {
+ private static final String getNoLanguageLayoutKey(final String keyboardLayoutName) {
return NO_LANGUAGE + "_" + keyboardLayoutName;
}
- public static int getSubtypeNameId(String localeString, String keyboardLayoutName) {
- if (Build.VERSION.SDK_INT >= /* JELLY_BEAN */ 15 && isExceptionalLocale(localeString)) {
+ public static int getSubtypeNameId(final String localeString, final String keyboardLayoutName) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
+ && isExceptionalLocale(localeString)) {
return sExceptionalLocaleToWithLayoutNameIdsMap.get(localeString);
}
- final String key = localeString.equals(NO_LANGUAGE)
+ final String key = NO_LANGUAGE.equals(localeString)
? getNoLanguageLayoutKey(keyboardLayoutName)
: keyboardLayoutName;
final Integer nameId = sKeyboardLayoutToNameIdsMap.get(key);
return nameId == null ? UNKNOWN_KEYBOARD_LAYOUT : nameId;
}
- public static String getSubtypeLocaleDisplayName(String localeString) {
- final String exceptionalValue = sExceptionalDisplayNamesMap.get(localeString);
- if (exceptionalValue != null) {
- return exceptionalValue;
+ private static Locale getDisplayLocaleOfSubtypeLocale(final String localeString) {
+ if (NO_LANGUAGE.equals(localeString)) {
+ return sResources.getConfiguration().locale;
}
- final Locale locale = LocaleUtils.constructLocaleFromString(localeString);
- return StringUtils.toTitleCase(locale.getDisplayName(locale), locale);
+ return LocaleUtils.constructLocaleFromString(localeString);
+ }
+
+ public static String getSubtypeLocaleDisplayNameInSystemLocale(final String localeString) {
+ final Locale displayLocale = sResources.getConfiguration().locale;
+ return getSubtypeLocaleDisplayNameInternal(localeString, displayLocale);
+ }
+
+ public static String getSubtypeLocaleDisplayName(final String localeString) {
+ final Locale displayLocale = getDisplayLocaleOfSubtypeLocale(localeString);
+ return getSubtypeLocaleDisplayNameInternal(localeString, displayLocale);
+ }
+
+ private static String getSubtypeLocaleDisplayNameInternal(final String localeString,
+ final Locale displayLocale) {
+ final Integer exceptionalNameResId = sExceptionalLocaleToNameIdsMap.get(localeString);
+ final String displayName;
+ if (exceptionalNameResId != null) {
+ final RunInLocale<String> getExceptionalName = new RunInLocale<String>() {
+ @Override
+ protected String job(final Resources res) {
+ return res.getString(exceptionalNameResId);
+ }
+ };
+ displayName = getExceptionalName.runInLocale(sResources, displayLocale);
+ } else if (NO_LANGUAGE.equals(localeString)) {
+ // No language subtype should be displayed in system locale.
+ return sResources.getString(R.string.subtype_no_language);
+ } else {
+ final Locale locale = LocaleUtils.constructLocaleFromString(localeString);
+ displayName = locale.getDisplayName(displayLocale);
+ }
+ return StringUtils.toTitleCase(displayName, displayLocale);
}
// InputMethodSubtype's display name in its locale.
// isAdditionalSubtype (T=true, F=false)
- // locale layout | display name
- // ------ ------ - ----------------------
- // en_US qwerty F English (US) exception
- // en_GB qwerty F English (UK) exception
- // fr azerty F Français
- // fr_CA qwerty F Français (Canada)
- // de qwertz F Deutsch
- // zz qwerty F No language (QWERTY) in system locale
- // fr qwertz T Français (QWERTZ)
- // de qwerty T Deutsch (QWERTY)
- // en_US azerty T English (US) (AZERTY)
- // zz azerty T No language (AZERTY) in system locale
-
- public static String getSubtypeDisplayName(final InputMethodSubtype subtype, Resources res) {
- final String replacementString = (Build.VERSION.SDK_INT >= /* JELLY_BEAN */ 15
- && subtype.containsExtraValueKey(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME))
- ? subtype.getExtraValueOf(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME)
- : getSubtypeLocaleDisplayName(subtype.getLocale());
+ // locale layout | display name
+ // ------ ------- - ----------------------
+ // en_US qwerty F English (US) exception
+ // en_GB qwerty F English (UK) exception
+ // es_US spanish F Español (EE.UU.) exception
+ // fr azerty F Français
+ // fr_CA qwerty F Français (Canada)
+ // de qwertz F Deutsch
+ // zz qwerty F No language (QWERTY) in system locale
+ // fr qwertz T Français (QWERTZ)
+ // de qwerty T Deutsch (QWERTY)
+ // en_US azerty T English (US) (AZERTY) exception
+ // zz azerty T No language (AZERTY) in system locale
+
+ private static String getReplacementString(final InputMethodSubtype subtype,
+ final Locale displayLocale) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
+ && subtype.containsExtraValueKey(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME)) {
+ return subtype.getExtraValueOf(UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME);
+ } else {
+ return getSubtypeLocaleDisplayNameInternal(subtype.getLocale(), displayLocale);
+ }
+ }
+
+ public static String getSubtypeDisplayNameInSystemLocale(final InputMethodSubtype subtype) {
+ final Locale displayLocale = sResources.getConfiguration().locale;
+ return getSubtypeDisplayNameInternal(subtype, displayLocale);
+ }
+
+ public static String getSubtypeDisplayName(final InputMethodSubtype subtype) {
+ final Locale displayLocale = getDisplayLocaleOfSubtypeLocale(subtype.getLocale());
+ return getSubtypeDisplayNameInternal(subtype, displayLocale);
+ }
+
+ private static String getSubtypeDisplayNameInternal(final InputMethodSubtype subtype,
+ final Locale displayLocale) {
+ final String replacementString = getReplacementString(subtype, displayLocale);
final int nameResId = subtype.getNameResId();
final RunInLocale<String> getSubtypeName = new RunInLocale<String>() {
@Override
- protected String job(Resources res) {
+ protected String job(final Resources res) {
try {
return res.getString(nameResId, replacementString);
} catch (Resources.NotFoundException e) {
// TODO: Remove this catch when InputMethodManager.getCurrentInputMethodSubtype
// is fixed.
Log.w(TAG, "Unknown subtype: mode=" + subtype.getMode()
+ + " nameResId=" + subtype.getNameResId()
+ " locale=" + subtype.getLocale()
+ " extra=" + subtype.getExtraValue()
+ "\n" + Utils.getStackTrace());
@@ -186,31 +243,30 @@ public final class SubtypeLocale {
}
}
};
- final Locale locale = isNoLanguage(subtype)
- ? res.getConfiguration().locale : getSubtypeLocale(subtype);
- return getSubtypeName.runInLocale(res, locale);
+ return StringUtils.toTitleCase(
+ getSubtypeName.runInLocale(sResources, displayLocale), displayLocale);
}
- public static boolean isNoLanguage(InputMethodSubtype subtype) {
+ public static boolean isNoLanguage(final InputMethodSubtype subtype) {
final String localeString = subtype.getLocale();
- return localeString.equals(NO_LANGUAGE);
+ return NO_LANGUAGE.equals(localeString);
}
- public static Locale getSubtypeLocale(InputMethodSubtype subtype) {
+ public static Locale getSubtypeLocale(final InputMethodSubtype subtype) {
final String localeString = subtype.getLocale();
return LocaleUtils.constructLocaleFromString(localeString);
}
- public static String getKeyboardLayoutSetDisplayName(InputMethodSubtype subtype) {
+ public static String getKeyboardLayoutSetDisplayName(final InputMethodSubtype subtype) {
final String layoutName = getKeyboardLayoutSetName(subtype);
return getKeyboardLayoutSetDisplayName(layoutName);
}
- public static String getKeyboardLayoutSetDisplayName(String layoutName) {
+ public static String getKeyboardLayoutSetDisplayName(final String layoutName) {
return sKeyboardLayoutToDisplayNameMap.get(layoutName);
}
- public static String getKeyboardLayoutSetName(InputMethodSubtype subtype) {
+ public static String getKeyboardLayoutSetName(final InputMethodSubtype subtype) {
String keyboardLayoutSet = subtype.getExtraValueOf(KEYBOARD_LAYOUT_SET);
if (keyboardLayoutSet == null) {
// This subtype doesn't have a keyboardLayoutSet extra value, so lookup its keyboard
diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
index 8e51a372b..2f9e34ff1 100644
--- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
+++ b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java
@@ -20,7 +20,6 @@ import static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.REQ_NET
import android.content.Context;
import android.content.Intent;
-import android.content.res.Configuration;
import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.net.ConnectivityManager;
@@ -32,6 +31,7 @@ import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.InputMethodSubtype;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import java.util.List;
@@ -43,7 +43,7 @@ public final class SubtypeSwitcher {
private static final String TAG = SubtypeSwitcher.class.getSimpleName();
private static final SubtypeSwitcher sInstance = new SubtypeSwitcher();
- private /* final */ InputMethodManager mImm;
+ private /* final */ RichInputMethodManager mRichImm;
private /* final */ Resources mResources;
private /* final */ ConnectivityManager mConnectivityManager;
@@ -53,9 +53,6 @@ public final class SubtypeSwitcher {
private InputMethodInfo mShortcutInputMethodInfo;
private InputMethodSubtype mShortcutSubtype;
private InputMethodSubtype mNoLanguageSubtype;
- // Note: This variable is always non-null after {@link #initialize(LatinIME)}.
- private InputMethodSubtype mCurrentSubtype;
- private Locale mCurrentSystemLocale;
/*-----------------------------------------------------------*/
private boolean mIsNetworkConnected;
@@ -84,7 +81,6 @@ public final class SubtypeSwitcher {
public static void init(final Context context) {
SubtypeLocale.init(context);
sInstance.initialize(context);
- sInstance.updateAllParameters(context);
}
private SubtypeSwitcher() {
@@ -93,63 +89,31 @@ public final class SubtypeSwitcher {
private void initialize(final Context service) {
mResources = service.getResources();
- mImm = ImfUtils.getInputMethodManager(service);
+ mRichImm = RichInputMethodManager.getInstance();
mConnectivityManager = (ConnectivityManager) service.getSystemService(
Context.CONNECTIVITY_SERVICE);
- mCurrentSystemLocale = mResources.getConfiguration().locale;
- mNoLanguageSubtype = ImfUtils.findSubtypeByLocaleAndKeyboardLayoutSet(
- service, SubtypeLocale.NO_LANGUAGE, SubtypeLocale.QWERTY);
- mCurrentSubtype = ImfUtils.getCurrentInputMethodSubtype(service, mNoLanguageSubtype);
+ mNoLanguageSubtype = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet(
+ SubtypeLocale.NO_LANGUAGE, SubtypeLocale.QWERTY);
if (mNoLanguageSubtype == null) {
throw new RuntimeException("Can't find no lanugage with QWERTY subtype");
}
final NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
mIsNetworkConnected = (info != null && info.isConnected());
- }
- // Update all parameters stored in SubtypeSwitcher.
- // Only configuration changed event is allowed to call this because this is heavy.
- private void updateAllParameters(final Context context) {
- mCurrentSystemLocale = mResources.getConfiguration().locale;
- updateSubtype(ImfUtils.getCurrentInputMethodSubtype(context, mNoLanguageSubtype));
- updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
+ onSubtypeChanged(getCurrentSubtype());
+ updateParametersOnStartInputView();
}
/**
- * Update parameters which are changed outside LatinIME. This parameters affect UI so they
- * should be updated every time onStartInputView.
- *
- * @return true if the current subtype is enabled.
+ * Update parameters which are changed outside LatinIME. This parameters affect UI so that they
+ * should be updated every time onStartInputView is called.
*/
- public boolean updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled() {
- final boolean currentSubtypeEnabled =
- updateEnabledSubtypesAndReturnIfEnabled(mCurrentSubtype);
- updateShortcutIME();
- return currentSubtypeEnabled;
- }
-
- /**
- * Update enabled subtypes from the framework.
- *
- * @param subtype the subtype to be checked
- * @return true if the {@code subtype} is enabled.
- */
- private boolean updateEnabledSubtypesAndReturnIfEnabled(final InputMethodSubtype subtype) {
+ public void updateParametersOnStartInputView() {
final List<InputMethodSubtype> enabledSubtypesOfThisIme =
- mImm.getEnabledInputMethodSubtypeList(null, true);
+ mRichImm.getInputMethodManager().getEnabledInputMethodSubtypeList(null, true);
mNeedsToDisplayLanguage.updateEnabledSubtypeCount(enabledSubtypesOfThisIme.size());
-
- for (final InputMethodSubtype ims : enabledSubtypesOfThisIme) {
- if (ims.equals(subtype)) {
- return true;
- }
- }
- if (DBG) {
- Log.w(TAG, "Subtype: " + subtype.getLocale() + "/" + subtype.getExtraValue()
- + " was disabled");
- }
- return false;
+ updateShortcutIME();
}
private void updateShortcutIME() {
@@ -162,7 +126,7 @@ public final class SubtypeSwitcher {
}
// TODO: Update an icon for shortcut IME
final Map<InputMethodInfo, List<InputMethodSubtype>> shortcuts =
- mImm.getShortcutInputMethodsAndSubtypes();
+ mRichImm.getInputMethodManager().getShortcutInputMethodsAndSubtypes();
mShortcutInputMethodInfo = null;
mShortcutSubtype = null;
for (final InputMethodInfo imi : shortcuts.keySet()) {
@@ -185,20 +149,20 @@ public final class SubtypeSwitcher {
}
// Update the current subtype. LatinIME.onCurrentInputMethodSubtypeChanged calls this function.
- public void updateSubtype(InputMethodSubtype newSubtype) {
+ public void onSubtypeChanged(final InputMethodSubtype newSubtype) {
if (DBG) {
- Log.w(TAG, "onCurrentInputMethodSubtypeChanged: to: "
- + newSubtype.getLocale() + "/" + newSubtype.getExtraValue() + ", from: "
- + mCurrentSubtype.getLocale() + "/" + mCurrentSubtype.getExtraValue());
+ Log.w(TAG, "onSubtypeChanged: " + SubtypeLocale.getSubtypeDisplayName(newSubtype));
}
final Locale newLocale = SubtypeLocale.getSubtypeLocale(newSubtype);
+ final Locale systemLocale = mResources.getConfiguration().locale;
+ final boolean sameLocale = systemLocale.equals(newLocale);
+ final boolean sameLanguage = systemLocale.getLanguage().equals(newLocale.getLanguage());
+ final boolean implicitlyEnabled =
+ mRichImm.checkIfSubtypeBelongsToThisImeAndImplicitlyEnabled(newSubtype);
mNeedsToDisplayLanguage.updateIsSystemLanguageSameAsInputLanguage(
- mCurrentSystemLocale.equals(newLocale));
+ sameLocale || (sameLanguage && implicitlyEnabled));
- if (newSubtype.equals(mCurrentSubtype)) return;
-
- mCurrentSubtype = newSubtype;
updateShortcutIME();
}
@@ -221,7 +185,7 @@ public final class SubtypeSwitcher {
if (token == null) {
return;
}
- final InputMethodManager imm = mImm;
+ final InputMethodManager imm = mRichImm.getInputMethodManager();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
@@ -238,14 +202,8 @@ public final class SubtypeSwitcher {
if (mShortcutSubtype == null) {
return true;
}
- final boolean allowsImplicitlySelectedSubtypes = true;
- for (final InputMethodSubtype enabledSubtype : mImm.getEnabledInputMethodSubtypeList(
- mShortcutInputMethodInfo, allowsImplicitlySelectedSubtypes)) {
- if (enabledSubtype.equals(mShortcutSubtype)) {
- return true;
- }
- }
- return false;
+ return mRichImm.checkIfSubtypeBelongsToImeAndEnabled(
+ mShortcutInputMethodInfo, mShortcutSubtype);
}
public boolean isShortcutImeReady() {
@@ -281,22 +239,19 @@ public final class SubtypeSwitcher {
return mNeedsToDisplayLanguage.getValue();
}
- public Locale getCurrentSubtypeLocale() {
- return SubtypeLocale.getSubtypeLocale(mCurrentSubtype);
+ private static Locale sForcedLocaleForTesting = null;
+ @UsedForTesting
+ void forceLocale(final Locale locale) {
+ sForcedLocaleForTesting = locale;
}
- public boolean onConfigurationChanged(final Configuration conf, final Context context) {
- final Locale systemLocale = conf.locale;
- final boolean systemLocaleChanged = !systemLocale.equals(mCurrentSystemLocale);
- // If system configuration was changed, update all parameters.
- if (systemLocaleChanged) {
- updateAllParameters(context);
- }
- return systemLocaleChanged;
+ public Locale getCurrentSubtypeLocale() {
+ if (null != sForcedLocaleForTesting) return sForcedLocaleForTesting;
+ return SubtypeLocale.getSubtypeLocale(getCurrentSubtype());
}
public InputMethodSubtype getCurrentSubtype() {
- return mCurrentSubtype;
+ return mRichImm.getCurrentInputMethodSubtype(mNoLanguageSubtype);
}
public InputMethodSubtype getNoLanguageSubtype() {
diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java
index f0e3b4ebd..975664dca 100644
--- a/java/src/com/android/inputmethod/latin/Suggest.java
+++ b/java/src/com/android/inputmethod/latin/Suggest.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2008 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
+ * 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
+ * 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.
+ * 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;
@@ -19,7 +19,7 @@ package com.android.inputmethod.latin;
import android.content.Context;
import android.text.TextUtils;
-import com.android.inputmethod.keyboard.Keyboard;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
@@ -38,7 +38,7 @@ public final class Suggest {
public static final String TAG = Suggest.class.getSimpleName();
// Session id for
- // {@link #getSuggestedWords(WordComposer,CharSequence,ProximityInfo,boolean,int)}.
+ // {@link #getSuggestedWords(WordComposer,String,ProximityInfo,boolean,int)}.
public static final int SESSION_TYPING = 0;
public static final int SESSION_GESTURE = 1;
@@ -57,6 +57,8 @@ public final class Suggest {
private ContactsBinaryDictionary mContactsDict;
private final ConcurrentHashMap<String, Dictionary> mDictionaries =
CollectionUtils.newConcurrentHashMap();
+ @UsedForTesting
+ private boolean mIsCurrentlyWaitingForMainDictionary = false;
public static final int MAX_SUGGESTIONS = 18;
@@ -71,9 +73,9 @@ public final class Suggest {
mLocale = locale;
}
- /* package for test */ Suggest(final Context context, final File dictionary,
- final long startOffset, final long length, final Locale locale) {
- final Dictionary mainDict = DictionaryFactory.createDictionaryForTest(context, dictionary,
+ @UsedForTesting
+ Suggest(final File dictionary, final long startOffset, final long length, final Locale locale) {
+ final Dictionary mainDict = DictionaryFactory.createDictionaryForTest(dictionary,
startOffset, length /* useFullEditDistance */, false, locale);
mLocale = locale;
mMainDictionary = mainDict;
@@ -98,6 +100,7 @@ public final class Suggest {
public void resetMainDict(final Context context, final Locale locale,
final SuggestInitializationListener listener) {
+ mIsCurrentlyWaitingForMainDictionary = true;
mMainDictionary = null;
if (listener != null) {
listener.onUpdateMainDictionaryAvailability(hasMainDictionary());
@@ -112,6 +115,7 @@ public final class Suggest {
if (listener != null) {
listener.onUpdateMainDictionaryAvailability(hasMainDictionary());
}
+ mIsCurrentlyWaitingForMainDictionary = false;
}
}.start();
}
@@ -122,6 +126,11 @@ public final class Suggest {
return null != mMainDictionary && mMainDictionary.isInitialized();
}
+ @UsedForTesting
+ public boolean isCurrentlyWaitingForMainDictionary() {
+ return mIsCurrentlyWaitingForMainDictionary;
+ }
+
public Dictionary getMainDictionary() {
return mMainDictionary;
}
@@ -138,7 +147,7 @@ public final class Suggest {
* Sets an optional user dictionary resource to be loaded. The user dictionary is consulted
* before the main dictionary, if set. This refers to the system-managed user dictionary.
*/
- public void setUserDictionary(UserBinaryDictionary userDictionary) {
+ public void setUserDictionary(final UserBinaryDictionary userDictionary) {
addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_USER, userDictionary);
}
@@ -147,12 +156,12 @@ public final class Suggest {
* the contacts dictionary by passing null to this method. In this case no contacts dictionary
* won't be used.
*/
- public void setContactsDictionary(ContactsBinaryDictionary contactsDictionary) {
+ public void setContactsDictionary(final ContactsBinaryDictionary contactsDictionary) {
mContactsDict = contactsDictionary;
addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_CONTACTS, contactsDictionary);
}
- public void setUserHistoryDictionary(UserHistoryDictionary userHistoryDictionary) {
+ public void setUserHistoryDictionary(final UserHistoryDictionary userHistoryDictionary) {
addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_USER_HISTORY, userHistoryDictionary);
}
@@ -160,9 +169,9 @@ public final class Suggest {
mAutoCorrectionThreshold = threshold;
}
- public SuggestedWords getSuggestedWords(
- final WordComposer wordComposer, CharSequence prevWordForBigram,
- final ProximityInfo proximityInfo, final boolean isCorrectionEnabled, int sessionId) {
+ public SuggestedWords getSuggestedWords(final WordComposer wordComposer,
+ final String prevWordForBigram, final ProximityInfo proximityInfo,
+ final boolean isCorrectionEnabled, final int sessionId) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
if (wordComposer.isBatchMode()) {
return getSuggestedWordsForBatchInput(
@@ -174,9 +183,9 @@ public final class Suggest {
}
// Retrieves suggestions for the typing input.
- private SuggestedWords getSuggestedWordsForTypingInput(
- final WordComposer wordComposer, CharSequence prevWordForBigram,
- final ProximityInfo proximityInfo, final boolean isCorrectionEnabled) {
+ private SuggestedWords getSuggestedWordsForTypingInput(final WordComposer wordComposer,
+ final String prevWordForBigram, final ProximityInfo proximityInfo,
+ final boolean isCorrectionEnabled) {
final int trailingSingleQuotesCount = wordComposer.trailingSingleQuotesCount();
final BoundedTreeSet suggestionsSet = new BoundedTreeSet(sSuggestedWordInfoComparator,
MAX_SUGGESTIONS);
@@ -203,7 +212,7 @@ public final class Suggest {
wordComposerForLookup, prevWordForBigram, proximityInfo));
}
- final CharSequence whitelistedWord;
+ final String whitelistedWord;
if (suggestionsSet.isEmpty()) {
whitelistedWord = null;
} else if (SuggestedWordInfo.KIND_WHITELIST != suggestionsSet.first().mKind) {
@@ -287,9 +296,9 @@ public final class Suggest {
}
// Retrieves suggestions for the batch input.
- private SuggestedWords getSuggestedWordsForBatchInput(
- final WordComposer wordComposer, CharSequence prevWordForBigram,
- final ProximityInfo proximityInfo, int sessionId) {
+ private SuggestedWords getSuggestedWordsForBatchInput(final WordComposer wordComposer,
+ final String prevWordForBigram, final ProximityInfo proximityInfo,
+ final int sessionId) {
final BoundedTreeSet suggestionsSet = new BoundedTreeSet(sSuggestedWordInfoComparator,
MAX_SUGGESTIONS);
@@ -307,7 +316,7 @@ public final class Suggest {
}
for (SuggestedWordInfo wordInfo : suggestionsSet) {
- LatinImeLogger.onAddSuggestedWord(wordInfo.mWord.toString(), wordInfo.mSourceDict);
+ LatinImeLogger.onAddSuggestedWord(wordInfo.mWord, wordInfo.mSourceDict);
}
final ArrayList<SuggestedWordInfo> suggestionsContainer =
@@ -372,7 +381,7 @@ public final class Suggest {
if (o1.mScore < o2.mScore) return 1;
if (o1.mCodePointCount < o2.mCodePointCount) return -1;
if (o1.mCodePointCount > o2.mCodePointCount) return 1;
- return o1.mWord.toString().compareTo(o2.mWord.toString());
+ return o1.mWord.compareTo(o2.mWord);
}
}
private static final SuggestedWordInfoComparator sSuggestedWordInfoComparator =
@@ -383,16 +392,17 @@ public final class Suggest {
final boolean isFirstCharCapitalized, final int trailingSingleQuotesCount) {
final StringBuilder sb = new StringBuilder(wordInfo.mWord.length());
if (isAllUpperCase) {
- sb.append(wordInfo.mWord.toString().toUpperCase(locale));
+ sb.append(wordInfo.mWord.toUpperCase(locale));
} else if (isFirstCharCapitalized) {
- sb.append(StringUtils.toTitleCase(wordInfo.mWord.toString(), locale));
+ sb.append(StringUtils.toTitleCase(wordInfo.mWord, locale));
} else {
sb.append(wordInfo.mWord);
}
for (int i = trailingSingleQuotesCount - 1; i >= 0; --i) {
- sb.appendCodePoint(Keyboard.CODE_SINGLE_QUOTE);
+ sb.appendCodePoint(Constants.CODE_SINGLE_QUOTE);
}
- return new SuggestedWordInfo(sb, wordInfo.mScore, wordInfo.mKind, wordInfo.mSourceDict);
+ return new SuggestedWordInfo(sb.toString(), wordInfo.mScore, wordInfo.mKind,
+ wordInfo.mSourceDict);
}
public void close() {
diff --git a/java/src/com/android/inputmethod/latin/SuggestedWords.java b/java/src/com/android/inputmethod/latin/SuggestedWords.java
index 52e292a86..3d6fe2d22 100644
--- a/java/src/com/android/inputmethod/latin/SuggestedWords.java
+++ b/java/src/com/android/inputmethod/latin/SuggestedWords.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -53,6 +53,10 @@ public final class SuggestedWords {
mIsPrediction = isPrediction;
}
+ public boolean isEmpty() {
+ return mSuggestedWordInfoList.isEmpty();
+ }
+
public int size() {
return mSuggestedWordInfoList.size();
}
@@ -61,10 +65,6 @@ public final class SuggestedWords {
return mSuggestedWordInfoList.get(pos).mWord;
}
- public SuggestedWordInfo getWordInfo(int pos) {
- return mSuggestedWordInfoList.get(pos);
- }
-
public SuggestedWordInfo getInfo(int pos) {
return mSuggestedWordInfoList.get(pos);
}
@@ -86,11 +86,14 @@ public final class SuggestedWords {
public static ArrayList<SuggestedWordInfo> getFromApplicationSpecifiedCompletions(
final CompletionInfo[] infos) {
final ArrayList<SuggestedWordInfo> result = CollectionUtils.newArrayList();
- for (CompletionInfo info : infos) {
- if (null != info && info.getText() != null) {
- result.add(new SuggestedWordInfo(info.getText(), SuggestedWordInfo.MAX_SCORE,
- SuggestedWordInfo.KIND_APP_DEFINED, Dictionary.TYPE_APPLICATION_DEFINED));
- }
+ for (final CompletionInfo info : infos) {
+ if (info == null) continue;
+ final CharSequence text = info.getText();
+ if (null == text) continue;
+ final SuggestedWordInfo suggestedWordInfo = new SuggestedWordInfo(text.toString(),
+ SuggestedWordInfo.MAX_SCORE, SuggestedWordInfo.KIND_APP_DEFINED,
+ Dictionary.TYPE_APPLICATION_DEFINED);
+ result.add(suggestedWordInfo);
}
return result;
}
@@ -98,7 +101,7 @@ public final class SuggestedWords {
// Should get rid of the first one (what the user typed previously) from suggestions
// and replace it with what the user currently typed.
public static ArrayList<SuggestedWordInfo> getTypedWordAndPreviousSuggestions(
- final CharSequence typedWord, final SuggestedWords previousSuggestions) {
+ final String typedWord, final SuggestedWords previousSuggestions) {
final ArrayList<SuggestedWordInfo> suggestionsList = CollectionUtils.newArrayList();
final HashSet<String> alreadySeen = CollectionUtils.newHashSet();
suggestionsList.add(new SuggestedWordInfo(typedWord, SuggestedWordInfo.MAX_SCORE,
@@ -106,8 +109,8 @@ public final class SuggestedWords {
alreadySeen.add(typedWord.toString());
final int previousSize = previousSuggestions.size();
for (int pos = 1; pos < previousSize; pos++) {
- final SuggestedWordInfo prevWordInfo = previousSuggestions.getWordInfo(pos);
- final String prevWord = prevWordInfo.mWord.toString();
+ final SuggestedWordInfo prevWordInfo = previousSuggestions.getInfo(pos);
+ final String prevWord = prevWordInfo.mWord;
// Filter out duplicate suggestion.
if (!alreadySeen.contains(prevWord)) {
suggestionsList.add(prevWordInfo);
@@ -135,9 +138,9 @@ public final class SuggestedWords {
public final String mSourceDict;
private String mDebugString = "";
- public SuggestedWordInfo(final CharSequence word, final int score, final int kind,
+ public SuggestedWordInfo(final String word, final int score, final int kind,
final String sourceDict) {
- mWord = word.toString();
+ mWord = word;
mScore = score;
mKind = kind;
mSourceDict = sourceDict;
@@ -145,7 +148,7 @@ public final class SuggestedWords {
}
- public void setDebugString(String str) {
+ public void setDebugString(final String str) {
if (null == str) throw new NullPointerException("Debug info is null");
mDebugString = str;
}
@@ -167,7 +170,7 @@ public final class SuggestedWords {
if (TextUtils.isEmpty(mDebugString)) {
return mWord;
} else {
- return mWord + " (" + mDebugString.toString() + ")";
+ return mWord + " (" + mDebugString + ")";
}
}
diff --git a/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java b/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java
index d188fc5ef..ed6fc03f9 100644
--- a/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java
+++ b/java/src/com/android/inputmethod/latin/SuggestionSpanPickedNotificationReceiver.java
@@ -16,11 +16,10 @@
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.text.style.SuggestionSpan;
import android.util.Log;
public final class SuggestionSpanPickedNotificationReceiver extends BroadcastReceiver {
@@ -30,12 +29,12 @@ public final class SuggestionSpanPickedNotificationReceiver extends BroadcastRec
@Override
public void onReceive(Context context, Intent intent) {
- if (SuggestionSpanUtils.ACTION_SUGGESTION_PICKED.equals(intent.getAction())) {
+ if (SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(intent.getAction())) {
if (DBG) {
final String before = intent.getStringExtra(
- SuggestionSpanUtils.SUGGESTION_SPAN_PICKED_BEFORE);
+ SuggestionSpan.SUGGESTION_SPAN_PICKED_BEFORE);
final String after = intent.getStringExtra(
- SuggestionSpanUtils.SUGGESTION_SPAN_PICKED_AFTER);
+ SuggestionSpan.SUGGESTION_SPAN_PICKED_AFTER);
Log.d(TAG, "Received notification picked: " + before + "," + after);
}
}
diff --git a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java
index 8f21b7b4a..ec4dc1436 100644
--- a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java
@@ -33,13 +33,13 @@ public final class SynchronouslyLoadedContactsBinaryDictionary extends ContactsB
@Override
public synchronized ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer codes,
- final CharSequence prevWordForBigrams, final ProximityInfo proximityInfo) {
+ final String prevWordForBigrams, final ProximityInfo proximityInfo) {
syncReloadDictionaryIfRequired();
return super.getSuggestions(codes, prevWordForBigrams, proximityInfo);
}
@Override
- public synchronized boolean isValidWord(CharSequence word) {
+ public synchronized boolean isValidWord(final String word) {
syncReloadDictionaryIfRequired();
return isValidWordInner(word);
}
diff --git a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java
index 612f54d73..4bdaf2039 100644
--- a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java
@@ -36,13 +36,13 @@ public final class SynchronouslyLoadedUserBinaryDictionary extends UserBinaryDic
@Override
public synchronized ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer codes,
- final CharSequence prevWordForBigrams, final ProximityInfo proximityInfo) {
+ final String prevWordForBigrams, final ProximityInfo proximityInfo) {
syncReloadDictionaryIfRequired();
return super.getSuggestions(codes, prevWordForBigrams, proximityInfo);
}
@Override
- public synchronized boolean isValidWord(CharSequence word) {
+ public synchronized boolean isValidWord(final String word) {
syncReloadDictionaryIfRequired();
return isValidWordInner(word);
}
diff --git a/java/src/com/android/inputmethod/latin/TargetApplicationGetter.java b/java/src/com/android/inputmethod/latin/TargetApplicationGetter.java
index 743a8c60f..1ea4ac346 100644
--- a/java/src/com/android/inputmethod/latin/TargetApplicationGetter.java
+++ b/java/src/com/android/inputmethod/latin/TargetApplicationGetter.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java
index 8570746b1..0d5bde623 100644
--- a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java
@@ -24,27 +24,28 @@ import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
+import android.os.Build;
import android.provider.UserDictionary.Words;
import android.text.TextUtils;
import java.util.Arrays;
/**
- * An expandable dictionary that stores the words in the user unigram dictionary.
- *
- * Largely a copy of UserDictionary, will replace that class in the future.
+ * An expandable dictionary that stores the words in the user dictionary provider into a binary
+ * dictionary file to use it from native code.
*/
public class UserBinaryDictionary extends ExpandableBinaryDictionary {
// The user dictionary provider uses an empty string to mean "all languages".
private static final String USER_DICTIONARY_ALL_LANGUAGES = "";
+ private static final int HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY = 250;
+ private static final int LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY = 160;
// TODO: use Words.SHORTCUT when we target JellyBean or above
final static String SHORTCUT = "shortcut";
private static final String[] PROJECTION_QUERY;
static {
- // 16 is JellyBean, but we want this to compile against ICS.
- if (android.os.Build.VERSION.SDK_INT >= 16) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
PROJECTION_QUERY = new String[] {
Words.WORD,
SHORTCUT,
@@ -90,13 +91,14 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary {
mObserver = new ContentObserver(null) {
@Override
public void onChange(final boolean self) {
- // This hook is deprecated as of API level 16, but should still be supported for
- // cases where the IME is running on an older version of the platform.
+ // This hook is deprecated as of API level 16 (Build.VERSION_CODES.JELLY_BEAN),
+ // but should still be supported for cases where the IME is running on an older
+ // version of the platform.
onChange(self, null);
}
- // The following hook is only available as of API level 16, and as such it will only
- // work on JellyBean+ devices. On older versions of the platform, the hook
- // above will be called instead.
+ // The following hook is only available as of API level 16
+ // (Build.VERSION_CODES.JELLY_BEAN), and as such it will only work on JellyBean+
+ // devices. On older versions of the platform, the hook above will be called instead.
@Override
public void onChange(final boolean self, final Uri uri) {
setRequiresReload(true);
@@ -214,17 +216,13 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary {
*
* @param word the word to add. If the word is capitalized, then the dictionary will
* recognize it as a capitalized word when searched.
- * @param frequency the frequency of occurrence of the word. A frequency of 255 is considered
- * the highest.
- * @TODO use a higher or float range for frequency
*/
- public synchronized void addWordToUserDictionary(final String word, final int frequency) {
+ public synchronized void addWordToUserDictionary(final String word) {
// TODO: do something for the UI. With the following, any sufficiently long word will
// look like it will go to the user dictionary but it won't.
// Safeguard against adding long words. Can cause stack overflow.
if (word.length() >= MAX_WORD_LENGTH) return;
- // TODO: Add an argument to the intent to specify the frequency.
Intent intent = new Intent(ACTION_USER_DICTIONARY_INSERT);
intent.putExtra(Words.WORD, word);
intent.putExtra(Words.LOCALE, mLocale);
@@ -232,9 +230,21 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary {
mContext.startActivity(intent);
}
- private void addWords(Cursor cursor) {
- // 16 is JellyBean, but we want this to compile against ICS.
- final boolean hasShortcutColumn = android.os.Build.VERSION.SDK_INT >= 16;
+ private int scaleFrequencyFromDefaultToLatinIme(final int defaultFrequency) {
+ // The default frequency for the user dictionary is 250 for historical reasons.
+ // Latin IME considers a good value for the default user dictionary frequency
+ // is about 160 considering the scale we use. So we are scaling down the values.
+ if (defaultFrequency > Integer.MAX_VALUE / LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY) {
+ return (defaultFrequency / HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY)
+ * LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY;
+ } else {
+ return (defaultFrequency * LATINIME_DEFAULT_USER_DICTIONARY_FREQUENCY)
+ / HISTORICAL_DEFAULT_USER_DICTIONARY_FREQUENCY;
+ }
+ }
+
+ private void addWords(final Cursor cursor) {
+ final boolean hasShortcutColumn = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
clearFusionDictionary();
if (cursor == null) return;
if (cursor.moveToFirst()) {
@@ -245,12 +255,13 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary {
final String word = cursor.getString(indexWord);
final String shortcut = hasShortcutColumn ? cursor.getString(indexShortcut) : null;
final int frequency = cursor.getInt(indexFrequency);
+ final int adjustedFrequency = scaleFrequencyFromDefaultToLatinIme(frequency);
// Safeguard against adding really long words.
if (word.length() < MAX_WORD_LENGTH) {
- super.addWord(word, null, frequency);
+ super.addWord(word, null, adjustedFrequency);
}
if (null != shortcut && shortcut.length() < MAX_WORD_LENGTH) {
- super.addWord(shortcut, word, frequency);
+ super.addWord(shortcut, word, adjustedFrequency);
}
cursor.moveToNext();
}
diff --git a/java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java b/java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java
index e39011145..62f2a9750 100644
--- a/java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java
+++ b/java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java
@@ -1,23 +1,24 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.util.Log;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.latin.makedict.BinaryDictIOUtils;
import com.android.inputmethod.latin.makedict.BinaryDictInputOutput;
import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.FusionDictionaryBufferInterface;
@@ -47,6 +48,7 @@ public final class UserHistoryDictIOUtils {
public void setBigram(final String word1, final String word2, final int frequency);
}
+ @UsedForTesting
public interface BigramDictionaryInterface {
public int getFrequency(final String word1, final String word2);
}
@@ -62,7 +64,7 @@ public final class UserHistoryDictIOUtils {
@Override
public int readUnsignedByte() {
- return ((int)mBuffer[mPosition++]) & 0xFF;
+ return mBuffer[mPosition++] & 0xFF;
}
@Override
@@ -120,16 +122,17 @@ public final class UserHistoryDictIOUtils {
BinaryDictInputOutput.writeDictionaryBinary(destination, fusionDict, formatOptions);
Log.d(TAG, "end writing");
} catch (IOException e) {
- Log.e(TAG, "IO exception while writing file: " + e);
+ Log.e(TAG, "IO exception while writing file", e);
} catch (UnsupportedFormatException e) {
- Log.e(TAG, "Unsupported fomat: " + e);
+ Log.e(TAG, "Unsupported format", e);
}
}
/**
* Constructs a new FusionDictionary from BigramDictionaryInterface.
*/
- /* packages for test */ static FusionDictionary constructFusionDictionary(
+ @UsedForTesting
+ static FusionDictionary constructFusionDictionary(
final BigramDictionaryInterface dict, final UserHistoryDictionaryBigramList bigrams) {
final FusionDictionary fusionDict = new FusionDictionary(new Node(),
new FusionDictionary.DictionaryOptions(new HashMap<String, String>(), false,
@@ -181,11 +184,11 @@ public final class UserHistoryDictIOUtils {
BinaryDictIOUtils.readUnigramsAndBigramsBinary(buffer, unigrams, frequencies,
bigrams);
} catch (IOException e) {
- Log.e(TAG, "IO exception while reading file: " + e);
+ Log.e(TAG, "IO exception while reading file", e);
} catch (UnsupportedFormatException e) {
- Log.e(TAG, "Unsupported format: " + e);
+ Log.e(TAG, "Unsupported format", e);
} catch (ArrayIndexOutOfBoundsException e) {
- Log.e(TAG, "ArrayIndexOutOfBoundsException while reading file: " + e);
+ Log.e(TAG, "ArrayIndexOutOfBoundsException while reading file", e);
}
addWordsFromWordMap(unigrams, frequencies, bigrams, dict);
}
@@ -193,7 +196,8 @@ public final class UserHistoryDictIOUtils {
/**
* Adds all unigrams and bigrams in maps to OnAddWordListener.
*/
- /* package for test */ static void addWordsFromWordMap(final Map<Integer, String> unigrams,
+ @UsedForTesting
+ static void addWordsFromWordMap(final Map<Integer, String> unigrams,
final Map<Integer, Integer> frequencies,
final Map<Integer, ArrayList<PendingAttribute>> bigrams, final OnAddWordListener to) {
for (Map.Entry<Integer, String> entry : unigrams.entrySet()) {
@@ -211,4 +215,4 @@ public final class UserHistoryDictIOUtils {
}
}
-} \ No newline at end of file
+}
diff --git a/java/src/com/android/inputmethod/latin/UserHistoryDictionary.java b/java/src/com/android/inputmethod/latin/UserHistoryDictionary.java
index 3615fa1fb..528028328 100644
--- a/java/src/com/android/inputmethod/latin/UserHistoryDictionary.java
+++ b/java/src/com/android/inputmethod/latin/UserHistoryDictionary.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
@@ -21,6 +21,7 @@ import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.UserHistoryDictIOUtils.BigramDictionaryInterface;
@@ -75,7 +76,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
private final SharedPreferences mPrefs;
// Should always be false except when we use this class for test
- /* package for test */ boolean isTest = false;
+ @UsedForTesting boolean isTest = false;
private static final ConcurrentHashMap<String, SoftReference<UserHistoryDictionary>>
sLangDictCache = CollectionUtils.newConcurrentHashMap();
@@ -122,7 +123,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
@Override
protected ArrayList<SuggestedWordInfo> getWordsInner(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo) {
+ final String prevWord, final ProximityInfo proximityInfo) {
// Inhibit suggestions (not predictions) for user history for now. Removing this method
// is enough to use it through the standard ExpandableDictionary way.
return null;
@@ -132,7 +133,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
* Return whether the passed charsequence is in the dictionary.
*/
@Override
- public synchronized boolean isValidWord(final CharSequence word) {
+ public synchronized boolean isValidWord(final String word) {
// TODO: figure out what is the correct thing to do here.
return false;
}
@@ -145,9 +146,9 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
* context, as in beginning of a sentence for example.
* The second word may not be null (a NullPointerException would be thrown).
*/
- public int addToUserHistory(final String word1, String word2, boolean isValid) {
- if (word2.length() >= BinaryDictionary.MAX_WORD_LENGTH ||
- (word1 != null && word1.length() >= BinaryDictionary.MAX_WORD_LENGTH)) {
+ public int addToUserHistory(final String word1, final String word2, final boolean isValid) {
+ if (word2.length() >= Constants.Dictionary.MAX_WORD_LENGTH ||
+ (word1 != null && word1.length() >= Constants.Dictionary.MAX_WORD_LENGTH)) {
return -1;
}
if (mBigramListLock.tryLock()) {
@@ -175,7 +176,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
return -1;
}
- public boolean cancelAddingUserHistory(String word1, String word2) {
+ public boolean cancelAddingUserHistory(final String word1, final String word2) {
if (mBigramListLock.tryLock()) {
try {
if (mBigramList.removeBigram(word1, word2)) {
@@ -218,7 +219,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
} catch (InterruptedException e) {
}
}
- final long last = SettingsValues.getLastUserHistoryWriteTime(mPrefs, mLocale);
+ final long last = Settings.readLastUserHistoryWriteTime(mPrefs, mLocale);
final boolean initializing = last == 0;
final long now = System.currentTimeMillis();
profTotal = 0;
@@ -226,7 +227,8 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
final ExpandableDictionary dictionary = this;
final OnAddWordListener listener = new OnAddWordListener() {
@Override
- public void setUnigram(String word, String shortcutTarget, int frequency) {
+ public void setUnigram(final String word, final String shortcutTarget,
+ final int frequency) {
profTotal++;
if (DBG_SAVE_RESTORE) {
Log.d(TAG, "load unigram: " + word + "," + frequency);
@@ -236,9 +238,9 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
}
@Override
- public void setBigram(String word1, String word2, int frequency) {
- if (word1.length() < BinaryDictionary.MAX_WORD_LENGTH
- && word2.length() < BinaryDictionary.MAX_WORD_LENGTH) {
+ public void setBigram(final String word1, final String word2, final int frequency) {
+ if (word1.length() < Constants.Dictionary.MAX_WORD_LENGTH
+ && word2.length() < Constants.Dictionary.MAX_WORD_LENGTH) {
profTotal++;
if (DBG_SAVE_RESTORE) {
Log.d(TAG, "load bigram: " + word1 + "," + word2 + "," + frequency);
@@ -250,7 +252,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
mBigramList.addBigram(word1, word2, (byte)frequency);
}
};
-
+
// Load the dictionary from binary file
FileInputStream inStream = null;
try {
@@ -261,9 +263,10 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
UserHistoryDictIOUtils.readDictionaryBinary(
new UserHistoryDictIOUtils.ByteArrayWrapper(buffer), listener);
} catch (FileNotFoundException e) {
- Log.e(TAG, "when loading: file not found" + e);
+ // This is an expected condition: we don't have a user history dictionary for this
+ // language yet. It will be created sometime later.
} catch (IOException e) {
- Log.e(TAG, "IOException when open bytebuffer: " + e);
+ Log.e(TAG, "IOException on opening a bytebuffer", e);
} finally {
if (inStream != null) {
try {
@@ -292,8 +295,9 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
private final SharedPreferences mPrefs;
private final Context mContext;
- public UpdateBinaryTask(UserHistoryDictionaryBigramList pendingWrites, String locale,
- UserHistoryDictionary dict, SharedPreferences prefs, Context context) {
+ public UpdateBinaryTask(final UserHistoryDictionaryBigramList pendingWrites,
+ final String locale, final UserHistoryDictionary dict,
+ final SharedPreferences prefs, final Context context) {
mBigramList = pendingWrites;
mLocale = locale;
mUserHistoryDictionary = dict;
@@ -303,7 +307,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
}
@Override
- protected Void doInBackground(Void... v) {
+ protected Void doInBackground(final Void... v) {
if (mUserHistoryDictionary.isTest) {
// If isTest == true, wait until the lock is released.
mUserHistoryDictionary.mBigramListLock.lock();
@@ -325,7 +329,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
Thread.sleep(15000);
Log.w(TAG, "End stress in closing");
} catch (InterruptedException e) {
- Log.e(TAG, "In stress test: " + e);
+ Log.e(TAG, "In stress test", e);
}
}
@@ -340,7 +344,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
out.flush();
out.close();
} catch (IOException e) {
- Log.e(TAG, "IO Exception while writing file: " + e);
+ Log.e(TAG, "IO Exception while writing file", e);
} finally {
if (out != null) {
try {
@@ -352,7 +356,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
}
// Save the timestamp after we finish writing the binary dictionary.
- SettingsValues.setLastUserHistoryWriteTime(mPrefs, mLocale);
+ Settings.writeLastUserHistoryWriteTime(mPrefs, mLocale);
if (PROFILE_SAVE_RESTORE) {
final long diff = System.currentTimeMillis() - now;
Log.w(TAG, "PROF: Write User HistoryDictionary: " + mLocale + ", " + diff + "ms.");
@@ -360,7 +364,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
}
@Override
- public int getFrequency(String word1, String word2) {
+ public int getFrequency(final String word1, final String word2) {
final int freq;
if (word1 == null) { // unigram
freq = FREQUENCY_FOR_TYPED;
@@ -373,10 +377,10 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
final byte fc = fcp.getFc();
final boolean isValid = fcp.isValid();
if (prevFc > 0 && prevFc == fc) {
- freq = ((int)fc) & 0xFF;
+ freq = fc & 0xFF;
} else if (UserHistoryForgettingCurveUtils.
needsToSave(fc, isValid, mAddLevel0Bigrams)) {
- freq = ((int)fc) & 0xFF;
+ freq = fc & 0xFF;
} else {
// Delete this entry
freq = -1;
@@ -390,6 +394,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary {
}
}
+ @UsedForTesting
void forceAddWordForTest(final String word1, final String word2, final boolean isValid) {
mBigramListLock.lock();
try {
diff --git a/java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java b/java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java
index df44948f9..316f09603 100644
--- a/java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java
+++ b/java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java
@@ -18,6 +18,8 @@ package com.android.inputmethod.latin;
import android.util.Log;
+import com.android.inputmethod.annotations.UsedForTesting;
+
import java.util.HashMap;
import java.util.Set;
@@ -26,6 +28,7 @@ import java.util.Set;
* All bigrams including stale ones in SQL DB should be stored in this class to avoid adding stale
* bigrams when we write to the SQL DB.
*/
+@UsedForTesting
public final class UserHistoryDictionaryBigramList {
public static final byte FORGETTING_CURVE_INITIAL_VALUE = 0;
private static final String TAG = UserHistoryDictionaryBigramList.class.getSimpleName();
diff --git a/java/src/com/android/inputmethod/latin/Utils.java b/java/src/com/android/inputmethod/latin/Utils.java
index 876bc8e79..acfcd5354 100644
--- a/java/src/com/android/inputmethod/latin/Utils.java
+++ b/java/src/com/android/inputmethod/latin/Utils.java
@@ -41,6 +41,7 @@ import java.io.PrintWriter;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.Locale;
public final class Utils {
private Utils() {
@@ -60,7 +61,7 @@ public final class Utils {
}
}
- /* package */ static class RingCharBuffer {
+ /* package */ static final class RingCharBuffer {
private static RingCharBuffer sRingCharBuffer = new RingCharBuffer();
private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC';
private static final int INVALID_COORDINATE = -2;
@@ -193,7 +194,7 @@ public final class Utils {
private UsabilityStudyLogUtils() {
mDate = new Date();
- mDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss.SSSZ");
+ mDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss.SSSZ", Locale.US);
HandlerThread handlerThread = new HandlerThread("UsabilityStudyLogUtils logging task",
Process.THREAD_PRIORITY_BACKGROUND);
@@ -202,7 +203,7 @@ public final class Utils {
}
// Initialization-on-demand holder
- private static class OnDemandInitializationHolder {
+ private static final class OnDemandInitializationHolder {
public static final UsabilityStudyLogUtils sInstance = new UsabilityStudyLogUtils();
}
@@ -255,7 +256,7 @@ public final class Utils {
final long currentTime = System.currentTimeMillis();
mDate.setTime(currentTime);
- final String printString = String.format("%s\t%d\t%s\n",
+ final String printString = String.format(Locale.US, "%s\t%d\t%s\n",
mDateFormat.format(mDate), currentTime, log);
if (LatinImeLogger.sDBG) {
Log.d(USABILITY_TAG, "Write: " + log);
@@ -297,7 +298,7 @@ public final class Utils {
final Date date = new Date();
date.setTime(System.currentTimeMillis());
final String currentDateTimeString =
- new SimpleDateFormat("yyyyMMdd-HHmmssZ").format(date);
+ new SimpleDateFormat("yyyyMMdd-HHmmssZ", Locale.US).format(date);
if (mFile == null) {
Log.w(USABILITY_TAG, "No internal log file found.");
return;
@@ -313,11 +314,15 @@ public final class Utils {
+ "/research-" + currentDateTimeString + ".log";
final File destFile = new File(destPath);
try {
- final FileChannel src = (new FileInputStream(mFile)).getChannel();
- final FileChannel dest = (new FileOutputStream(destFile)).getChannel();
+ final FileInputStream srcStream = new FileInputStream(mFile);
+ final FileOutputStream destStream = new FileOutputStream(destFile);
+ final FileChannel src = srcStream.getChannel();
+ final FileChannel dest = destStream.getChannel();
src.transferTo(0, src.size(), dest);
src.close();
+ srcStream.close();
dest.close();
+ destStream.close();
} catch (FileNotFoundException e1) {
Log.w(USABILITY_TAG, e1);
return;
diff --git a/java/src/com/android/inputmethod/latin/VibratorUtils.java b/java/src/com/android/inputmethod/latin/VibratorUtils.java
deleted file mode 100644
index b6696cec0..000000000
--- a/java/src/com/android/inputmethod/latin/VibratorUtils.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 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.os.Vibrator;
-
-public final class VibratorUtils {
- private static final VibratorUtils sInstance = new VibratorUtils();
- private Vibrator mVibrator;
-
- private VibratorUtils() {
- // This utility class is not publicly instantiable.
- }
-
- public static VibratorUtils 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 mVibrator.hasVibrator();
- }
-
- public void vibrate(long milliseconds) {
- if (mVibrator == null) {
- return;
- }
- mVibrator.vibrate(milliseconds);
- }
-}
diff --git a/java/src/com/android/inputmethod/latin/WordComposer.java b/java/src/com/android/inputmethod/latin/WordComposer.java
index da0071adc..f7cb4346a 100644
--- a/java/src/com/android/inputmethod/latin/WordComposer.java
+++ b/java/src/com/android/inputmethod/latin/WordComposer.java
@@ -1,21 +1,22 @@
/*
* Copyright (C) 2008 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
+ * 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
+ * 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.
+ * 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.annotations.UsedForTesting;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
@@ -25,7 +26,7 @@ import java.util.Arrays;
* A place to store the currently composing word with information such as adjacent key codes as well
*/
public final class WordComposer {
- private static final int N = BinaryDictionary.MAX_WORD_LENGTH;
+ private static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH;
public static final int CAPS_MODE_OFF = 0;
// 1 is shift bit, 2 is caps bit, 4 is auto bit but this is just a convention as these bits
@@ -36,9 +37,9 @@ public final class WordComposer {
public static final int CAPS_MODE_AUTO_SHIFT_LOCKED = 0x7;
private int[] mPrimaryKeyCodes;
- private final InputPointers mInputPointers = new InputPointers(N);
+ private final InputPointers mInputPointers = new InputPointers(MAX_WORD_LENGTH);
private final StringBuilder mTypedWord;
- private CharSequence mAutoCorrection;
+ private String mAutoCorrection;
private boolean mIsResumed;
private boolean mIsBatchMode;
@@ -55,8 +56,8 @@ public final class WordComposer {
private boolean mIsFirstCharCapitalized;
public WordComposer() {
- mPrimaryKeyCodes = new int[N];
- mTypedWord = new StringBuilder(N);
+ mPrimaryKeyCodes = new int[MAX_WORD_LENGTH];
+ mTypedWord = new StringBuilder(MAX_WORD_LENGTH);
mAutoCorrection = null;
mTrailingSingleQuotesCount = 0;
mIsResumed = false;
@@ -64,7 +65,7 @@ public final class WordComposer {
refreshSize();
}
- public WordComposer(WordComposer source) {
+ public WordComposer(final WordComposer source) {
mPrimaryKeyCodes = Arrays.copyOf(source.mPrimaryKeyCodes, source.mPrimaryKeyCodes.length);
mTypedWord = new StringBuilder(source.mTypedWord);
mInputPointers.copy(source.mInputPointers);
@@ -111,7 +112,7 @@ public final class WordComposer {
// TODO: make sure that the index should not exceed MAX_WORD_LENGTH
public int getCodeAt(int index) {
- if (index >= BinaryDictionary.MAX_WORD_LENGTH) {
+ if (index >= MAX_WORD_LENGTH) {
return -1;
}
return mPrimaryKeyCodes[index];
@@ -121,7 +122,8 @@ public final class WordComposer {
return mInputPointers;
}
- private static boolean isFirstCharCapitalized(int index, int codePoint, boolean previous) {
+ private static boolean isFirstCharCapitalized(final int index, final int codePoint,
+ final boolean previous) {
if (index == 0) return Character.isUpperCase(codePoint);
return previous && !Character.isUpperCase(codePoint);
}
@@ -129,12 +131,12 @@ public final class WordComposer {
/**
* Add a new keystroke, with the pressed key's code point with the touch point coordinates.
*/
- public void add(int primaryCode, int keyX, int keyY) {
+ public void add(final int primaryCode, final int keyX, final int keyY) {
final int newIndex = size();
mTypedWord.appendCodePoint(primaryCode);
refreshSize();
- if (newIndex < BinaryDictionary.MAX_WORD_LENGTH) {
- mPrimaryKeyCodes[newIndex] = primaryCode >= Keyboard.CODE_SPACE
+ if (newIndex < MAX_WORD_LENGTH) {
+ mPrimaryKeyCodes[newIndex] = primaryCode >= Constants.CODE_SPACE
? Character.toLowerCase(primaryCode) : primaryCode;
// In the batch input mode, the {@code mInputPointers} holds batch input points and
// shouldn't be overridden by the "typed key" coordinates
@@ -148,7 +150,7 @@ public final class WordComposer {
newIndex, primaryCode, mIsFirstCharCapitalized);
if (Character.isUpperCase(primaryCode)) mCapsCount++;
if (Character.isDigit(primaryCode)) mDigitsCount++;
- if (Keyboard.CODE_SINGLE_QUOTE == primaryCode) {
+ if (Constants.CODE_SINGLE_QUOTE == primaryCode) {
++mTrailingSingleQuotesCount;
} else {
mTrailingSingleQuotesCount = 0;
@@ -156,12 +158,12 @@ public final class WordComposer {
mAutoCorrection = null;
}
- public void setBatchInputPointers(InputPointers batchPointers) {
+ public void setBatchInputPointers(final InputPointers batchPointers) {
mInputPointers.set(batchPointers);
mIsBatchMode = true;
}
- public void setBatchInputWord(CharSequence word) {
+ public void setBatchInputWord(final String word) {
reset();
mIsBatchMode = true;
final int length = word.length();
@@ -176,7 +178,8 @@ public final class WordComposer {
/**
* Internal method to retrieve reasonable proximity info for a character.
*/
- private void addKeyInfo(final int codePoint, final Keyboard keyboard) {
+ @UsedForTesting
+ public void addKeyInfo(final int codePoint, final Keyboard keyboard) {
final int x, y;
final Key key;
if (keyboard != null && (key = keyboard.getKey(codePoint)) != null) {
@@ -235,7 +238,7 @@ public final class WordComposer {
int i = mTypedWord.length();
while (i > 0) {
i = mTypedWord.offsetByCodePoints(i, -1);
- if (Keyboard.CODE_SINGLE_QUOTE != mTypedWord.codePointAt(i)) break;
+ if (Constants.CODE_SINGLE_QUOTE != mTypedWord.codePointAt(i)) break;
++mTrailingSingleQuotesCount;
}
}
@@ -321,14 +324,14 @@ public final class WordComposer {
/**
* Sets the auto-correction for this word.
*/
- public void setAutoCorrection(final CharSequence correction) {
+ public void setAutoCorrection(final String correction) {
mAutoCorrection = correction;
}
/**
* @return the auto-correction for this word, or null if none.
*/
- public CharSequence getAutoCorrectionOrNull() {
+ public String getAutoCorrectionOrNull() {
return mAutoCorrection;
}
@@ -341,15 +344,15 @@ public final class WordComposer {
// `type' should be one of the LastComposedWord.COMMIT_TYPE_* constants above.
public LastComposedWord commitWord(final int type, final String committedWord,
- final String separatorString, final CharSequence prevWord) {
+ final String separatorString, final String prevWord) {
// Note: currently, we come here whenever we commit a word. If it's a MANUAL_PICK
// or a DECIDED_WORD we may cancel the commit later; otherwise, we should deactivate
// the last composed word to ensure this does not happen.
final int[] primaryKeyCodes = mPrimaryKeyCodes;
- mPrimaryKeyCodes = new int[N];
+ mPrimaryKeyCodes = new int[MAX_WORD_LENGTH];
final LastComposedWord lastComposedWord = new LastComposedWord(primaryKeyCodes,
mInputPointers, mTypedWord.toString(), committedWord, separatorString,
- prevWord);
+ prevWord, mCapitalizedMode);
mInputPointers.reset();
if (type != LastComposedWord.COMMIT_TYPE_DECIDED_WORD
&& type != LastComposedWord.COMMIT_TYPE_MANUAL_PICK) {
@@ -359,8 +362,10 @@ public final class WordComposer {
mDigitsCount = 0;
mIsBatchMode = false;
mTypedWord.setLength(0);
+ mCodePointSize = 0;
mTrailingSingleQuotesCount = 0;
mIsFirstCharCapitalized = false;
+ mCapitalizedMode = CAPS_MODE_OFF;
refreshSize();
mAutoCorrection = null;
mIsResumed = false;
@@ -373,6 +378,7 @@ public final class WordComposer {
mTypedWord.setLength(0);
mTypedWord.append(lastComposedWord.mTypedWord);
refreshSize();
+ mCapitalizedMode = lastComposedWord.mCapitalizedMode;
mAutoCorrection = null; // This will be filled by the next call to updateSuggestion.
mIsResumed = true;
}
diff --git a/java/src/com/android/inputmethod/latin/WordListInfo.java b/java/src/com/android/inputmethod/latin/WordListInfo.java
index 095320e25..5ac806a0c 100644
--- a/java/src/com/android/inputmethod/latin/WordListInfo.java
+++ b/java/src/com/android/inputmethod/latin/WordListInfo.java
@@ -1,17 +1,17 @@
-/**
+/*
* 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/XmlParseUtils.java b/java/src/com/android/inputmethod/latin/XmlParseUtils.java
index 75dc68f1d..f01d4c5e6 100644
--- a/java/src/com/android/inputmethod/latin/XmlParseUtils.java
+++ b/java/src/com/android/inputmethod/latin/XmlParseUtils.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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;
diff --git a/java/src/com/android/inputmethod/latin/define/JniLibName.java b/java/src/com/android/inputmethod/latin/define/JniLibName.java
index e23e1a968..abfc36d39 100644
--- a/java/src/com/android/inputmethod/latin/define/JniLibName.java
+++ b/java/src/com/android/inputmethod/latin/define/JniLibName.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.define;
diff --git a/java/src/com/android/inputmethod/latin/define/ProductionFlag.java b/java/src/com/android/inputmethod/latin/define/ProductionFlag.java
index 52c066a44..fe9be16c6 100644
--- a/java/src/com/android/inputmethod/latin/define/ProductionFlag.java
+++ b/java/src/com/android/inputmethod/latin/define/ProductionFlag.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.define;
@@ -23,4 +23,11 @@ public final class ProductionFlag {
public static final boolean IS_EXPERIMENTAL = false;
public static final boolean IS_INTERNAL = false;
+
+ // When false, IS_EXPERIMENTAL_DEBUG suggests that all guarded class-private DEBUG flags should
+ // be false, and any privacy controls should be enforced. IS_EXPERIMENTAL_DEBUG should be false
+ // for any released build.
+ public static final boolean IS_EXPERIMENTAL_DEBUG = false;
+
+ public static final boolean IS_HARDWARE_KEYBOARD_SUPPORTED = true;
}
diff --git a/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java b/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java
index 7b0231a6b..c87a9254d 100644
--- a/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java
+++ b/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java
@@ -1,34 +1,51 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.makedict;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.latin.Constants;
+import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.CharEncoding;
import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.FusionDictionaryBufferInterface;
import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader;
import com.android.inputmethod.latin.makedict.FormatSpec.FormatOptions;
import com.android.inputmethod.latin.makedict.FusionDictionary.CharGroup;
+import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.channels.FileChannel;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
import java.util.Map;
import java.util.Stack;
public final class BinaryDictIOUtils {
private static final boolean DBG = false;
+ private static final int MSB24 = 0x800000;
+ private static final int SINT24_MAX = 0x7FFFFF;
+ private static final int MAX_JUMPS = 10000;
+
+ private BinaryDictIOUtils() {
+ // This utility class is not publicly instantiable.
+ }
private static final class Position {
public static final int NOT_READ_GROUPCOUNT = -1;
@@ -90,7 +107,9 @@ public final class BinaryDictIOUtils {
final boolean isMovedGroup = BinaryDictInputOutput.isMovedGroup(info.mFlags,
formatOptions);
- if (!isMovedGroup
+ final boolean isDeletedGroup = BinaryDictInputOutput.isDeletedGroup(info.mFlags,
+ formatOptions);
+ if (!isMovedGroup && !isDeletedGroup
&& info.mFrequency != FusionDictionary.CharGroup.NOT_A_TERMINAL) {// found word
words.put(info.mOriginalAddress, new String(pushedChars, 0, index));
frequencies.put(info.mOriginalAddress, info.mFrequency);
@@ -153,6 +172,7 @@ public final class BinaryDictIOUtils {
* @throws IOException
* @throws UnsupportedFormatException
*/
+ @UsedForTesting
public static int getTerminalPosition(final FusionDictionaryBufferInterface buffer,
final String word) throws IOException, UnsupportedFormatException {
if (word == null) return FormatSpec.NOT_VALID_WORD;
@@ -165,19 +185,19 @@ public final class BinaryDictIOUtils {
if (wordPos >= wordLen) return FormatSpec.NOT_VALID_WORD;
do {
- int groupOffset = buffer.position() - header.mHeaderSize;
final int charGroupCount = BinaryDictInputOutput.readCharGroupCount(buffer);
- groupOffset += BinaryDictInputOutput.getGroupCountSize(charGroupCount);
-
boolean foundNextCharGroup = false;
for (int i = 0; i < charGroupCount; ++i) {
final int charGroupPos = buffer.position();
final CharGroupInfo currentInfo = BinaryDictInputOutput.readCharGroup(buffer,
buffer.position(), header.mFormatOptions);
- if (BinaryDictInputOutput.isMovedGroup(currentInfo.mFlags,
- header.mFormatOptions)) {
- continue;
- }
+ final boolean isMovedGroup =
+ BinaryDictInputOutput.isMovedGroup(currentInfo.mFlags,
+ header.mFormatOptions);
+ final boolean isDeletedGroup =
+ BinaryDictInputOutput.isDeletedGroup(currentInfo.mFlags,
+ header.mFormatOptions);
+ if (isMovedGroup) continue;
boolean same = true;
for (int p = 0, j = word.offsetByCodePoints(0, wordPos);
p < currentInfo.mCharacters.length;
@@ -192,7 +212,8 @@ public final class BinaryDictIOUtils {
if (same) {
// found the group matches the word.
if (wordPos + currentInfo.mCharacters.length == wordLen) {
- if (currentInfo.mFrequency == CharGroup.NOT_A_TERMINAL) {
+ if (currentInfo.mFrequency == CharGroup.NOT_A_TERMINAL
+ || isDeletedGroup) {
return FormatSpec.NOT_VALID_WORD;
} else {
return charGroupPos;
@@ -206,7 +227,6 @@ public final class BinaryDictIOUtils {
buffer.position(currentInfo.mChildrenAddress);
break;
}
- groupOffset = currentInfo.mEndAddress;
}
// If we found the next char group, it is under the file pointer.
@@ -228,6 +248,10 @@ public final class BinaryDictIOUtils {
return FormatSpec.NOT_VALID_WORD;
}
+ private static int markAsDeleted(final int flags) {
+ return (flags & (~FormatSpec.MASK_GROUP_ADDRESS_TYPE)) | FormatSpec.FLAG_IS_DELETED;
+ }
+
/**
* Delete the word from the binary file.
*
@@ -236,6 +260,7 @@ public final class BinaryDictIOUtils {
* @throws IOException
* @throws UnsupportedFormatException
*/
+ @UsedForTesting
public static void deleteWord(final FusionDictionaryBufferInterface buffer,
final String word) throws IOException, UnsupportedFormatException {
buffer.position(0);
@@ -245,21 +270,58 @@ public final class BinaryDictIOUtils {
buffer.position(wordPosition);
final int flags = buffer.readUnsignedByte();
- final int newFlags = flags ^ FormatSpec.FLAG_IS_TERMINAL;
buffer.position(wordPosition);
- buffer.put((byte)newFlags);
+ buffer.put((byte)markAsDeleted(flags));
}
- private static void putSInt24(final FusionDictionaryBufferInterface buffer,
+ /**
+ * @return the size written, in bytes. Always 3 bytes.
+ */
+ private static int writeSInt24ToBuffer(final FusionDictionaryBufferInterface buffer,
final int value) {
final int absValue = Math.abs(value);
buffer.put((byte)(((value < 0 ? 0x80 : 0) | (absValue >> 16)) & 0xFF));
buffer.put((byte)((absValue >> 8) & 0xFF));
buffer.put((byte)(absValue & 0xFF));
+ return 3;
+ }
+
+ /**
+ * @return the size written, in bytes. Always 3 bytes.
+ */
+ private static int writeSInt24ToStream(final OutputStream destination, final int value)
+ throws IOException {
+ final int absValue = Math.abs(value);
+ destination.write((byte)(((value < 0 ? 0x80 : 0) | (absValue >> 16)) & 0xFF));
+ destination.write((byte)((absValue >> 8) & 0xFF));
+ destination.write((byte)(absValue & 0xFF));
+ return 3;
+ }
+
+ /**
+ * @return the size written, in bytes. 1, 2, or 3 bytes.
+ */
+ private static int writeVariableAddress(final OutputStream destination, final int value)
+ throws IOException {
+ switch (BinaryDictInputOutput.getByteSize(value)) {
+ case 1:
+ destination.write((byte)value);
+ break;
+ case 2:
+ destination.write((byte)(0xFF & (value >> 8)));
+ destination.write((byte)(0xFF & value));
+ break;
+ case 3:
+ destination.write((byte)(0xFF & (value >> 16)));
+ destination.write((byte)(0xFF & (value >> 8)));
+ destination.write((byte)(0xFF & value));
+ break;
+ }
+ return BinaryDictInputOutput.getByteSize(value);
}
/**
- * Update a parent address in a CharGroup that is addressed by groupOriginAddress.
+ * Update a parent address in a CharGroup that is referred to by groupOriginAddress.
*
* @param buffer the buffer to write.
* @param groupOriginAddress the address of the group.
@@ -275,8 +337,686 @@ public final class BinaryDictIOUtils {
throw new RuntimeException("this file format does not support parent addresses");
}
final int flags = buffer.readUnsignedByte();
+ if (BinaryDictInputOutput.isMovedGroup(flags, formatOptions)) {
+ // if the group is moved, the parent address is stored in the destination group.
+ // We are guaranteed to process the destination group later, so there is no need to
+ // update anything here.
+ buffer.position(originalPosition);
+ return;
+ }
+ if (DBG) {
+ MakedictLog.d("update parent address flags=" + flags + ", " + groupOriginAddress);
+ }
final int parentOffset = newParentAddress - groupOriginAddress;
- putSInt24(buffer, parentOffset);
+ writeSInt24ToBuffer(buffer, parentOffset);
buffer.position(originalPosition);
}
+
+ private static void skipCharGroup(final FusionDictionaryBufferInterface buffer,
+ final FormatOptions formatOptions) {
+ final int flags = buffer.readUnsignedByte();
+ BinaryDictInputOutput.readParentAddress(buffer, formatOptions);
+ skipString(buffer, (flags & FormatSpec.FLAG_HAS_MULTIPLE_CHARS) != 0);
+ BinaryDictInputOutput.readChildrenAddress(buffer, flags, formatOptions);
+ if ((flags & FormatSpec.FLAG_IS_TERMINAL) != 0) buffer.readUnsignedByte();
+ if ((flags & FormatSpec.FLAG_HAS_SHORTCUT_TARGETS) != 0) {
+ final int shortcutsSize = buffer.readUnsignedShort();
+ buffer.position(buffer.position() + shortcutsSize
+ - FormatSpec.GROUP_SHORTCUT_LIST_SIZE_SIZE);
+ }
+ if ((flags & FormatSpec.FLAG_HAS_BIGRAMS) != 0) {
+ int bigramCount = 0;
+ while (bigramCount++ < FormatSpec.MAX_BIGRAMS_IN_A_GROUP) {
+ final int bigramFlags = buffer.readUnsignedByte();
+ switch (bigramFlags & FormatSpec.MASK_ATTRIBUTE_ADDRESS_TYPE) {
+ case FormatSpec.FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE:
+ buffer.readUnsignedByte();
+ break;
+ case FormatSpec.FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES:
+ buffer.readUnsignedShort();
+ break;
+ case FormatSpec.FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES:
+ buffer.readUnsignedInt24();
+ break;
+ }
+ if ((bigramFlags & FormatSpec.FLAG_ATTRIBUTE_HAS_NEXT) == 0) break;
+ }
+ if (bigramCount >= FormatSpec.MAX_BIGRAMS_IN_A_GROUP) {
+ throw new RuntimeException("Too many bigrams in a group.");
+ }
+ }
+ }
+
+ /**
+ * Update parent addresses in a Node that is referred to by nodeOriginAddress.
+ *
+ * @param buffer the buffer to be modified.
+ * @param nodeOriginAddress the address of a modified Node.
+ * @param newParentAddress the address to be written.
+ * @param formatOptions file format options.
+ */
+ public static void updateParentAddresses(final FusionDictionaryBufferInterface buffer,
+ final int nodeOriginAddress, final int newParentAddress,
+ final FormatOptions formatOptions) {
+ final int originalPosition = buffer.position();
+ buffer.position(nodeOriginAddress);
+ do {
+ final int count = BinaryDictInputOutput.readCharGroupCount(buffer);
+ for (int i = 0; i < count; ++i) {
+ updateParentAddress(buffer, buffer.position(), newParentAddress, formatOptions);
+ skipCharGroup(buffer, formatOptions);
+ }
+ final int forwardLinkAddress = buffer.readUnsignedInt24();
+ buffer.position(forwardLinkAddress);
+ } while (formatOptions.mSupportsDynamicUpdate
+ && buffer.position() != FormatSpec.NO_FORWARD_LINK_ADDRESS);
+ buffer.position(originalPosition);
+ }
+
+ private static void skipString(final FusionDictionaryBufferInterface buffer,
+ final boolean hasMultipleChars) {
+ if (hasMultipleChars) {
+ int character = CharEncoding.readChar(buffer);
+ while (character != FormatSpec.INVALID_CHARACTER) {
+ character = CharEncoding.readChar(buffer);
+ }
+ } else {
+ CharEncoding.readChar(buffer);
+ }
+ }
+
+ /**
+ * Write a string to a stream.
+ *
+ * @param destination the stream to write.
+ * @param word the string to be written.
+ * @return the size written, in bytes.
+ * @throws IOException
+ */
+ private static int writeString(final OutputStream destination, final String word)
+ throws IOException {
+ int size = 0;
+ final int length = word.length();
+ for (int i = 0; i < length; i = word.offsetByCodePoints(i, 1)) {
+ final int codePoint = word.codePointAt(i);
+ if (CharEncoding.getCharSize(codePoint) == 1) {
+ destination.write((byte)codePoint);
+ size++;
+ } else {
+ destination.write((byte)(0xFF & (codePoint >> 16)));
+ destination.write((byte)(0xFF & (codePoint >> 8)));
+ destination.write((byte)(0xFF & codePoint));
+ size += 3;
+ }
+ }
+ destination.write((byte)FormatSpec.GROUP_CHARACTERS_TERMINATOR);
+ size += FormatSpec.GROUP_TERMINATOR_SIZE;
+ return size;
+ }
+
+ /**
+ * Update a children address in a CharGroup that is addressed by groupOriginAddress.
+ *
+ * @param buffer the buffer to write.
+ * @param groupOriginAddress the address of the group.
+ * @param newChildrenAddress the absolute address of the child.
+ * @param formatOptions file format options.
+ */
+ public static void updateChildrenAddress(final FusionDictionaryBufferInterface buffer,
+ final int groupOriginAddress, final int newChildrenAddress,
+ final FormatOptions formatOptions) {
+ final int originalPosition = buffer.position();
+ buffer.position(groupOriginAddress);
+ final int flags = buffer.readUnsignedByte();
+ final int parentAddress = BinaryDictInputOutput.readParentAddress(buffer, formatOptions);
+ skipString(buffer, (flags & FormatSpec.FLAG_HAS_MULTIPLE_CHARS) != 0);
+ if ((flags & FormatSpec.FLAG_IS_TERMINAL) != 0) buffer.readUnsignedByte();
+ final int childrenOffset = newChildrenAddress == FormatSpec.NO_CHILDREN_ADDRESS
+ ? FormatSpec.NO_CHILDREN_ADDRESS : newChildrenAddress - buffer.position();
+ writeSInt24ToBuffer(buffer, childrenOffset);
+ buffer.position(originalPosition);
+ }
+
+ /**
+ * Write a char group to an output stream.
+ * A char group is an in-memory representation of a node in trie.
+ * A char group info is an on-disk representation of a node.
+ *
+ * @param destination the stream to write.
+ * @param info the char group info to be written.
+ * @return the size written, in bytes.
+ */
+ public static int writeCharGroup(final OutputStream destination, final CharGroupInfo info)
+ throws IOException {
+ int size = FormatSpec.GROUP_FLAGS_SIZE;
+ destination.write((byte)info.mFlags);
+ final int parentOffset = info.mParentAddress == FormatSpec.NO_PARENT_ADDRESS ?
+ FormatSpec.NO_PARENT_ADDRESS : info.mParentAddress - info.mOriginalAddress;
+ size += writeSInt24ToStream(destination, parentOffset);
+
+ for (int i = 0; i < info.mCharacters.length; ++i) {
+ if (CharEncoding.getCharSize(info.mCharacters[i]) == 1) {
+ destination.write((byte)info.mCharacters[i]);
+ size++;
+ } else {
+ size += writeSInt24ToStream(destination, info.mCharacters[i]);
+ }
+ }
+ if (info.mCharacters.length > 1) {
+ destination.write((byte)FormatSpec.GROUP_CHARACTERS_TERMINATOR);
+ size++;
+ }
+
+ if ((info.mFlags & FormatSpec.FLAG_IS_TERMINAL) != 0) {
+ destination.write((byte)info.mFrequency);
+ size++;
+ }
+
+ if (DBG) {
+ MakedictLog.d("writeCharGroup origin=" + info.mOriginalAddress + ", size=" + size
+ + ", child=" + info.mChildrenAddress + ", characters ="
+ + new String(info.mCharacters, 0, info.mCharacters.length));
+ }
+ final int childrenOffset = info.mChildrenAddress == FormatSpec.NO_CHILDREN_ADDRESS ?
+ 0 : info.mChildrenAddress - (info.mOriginalAddress + size);
+ writeSInt24ToStream(destination, childrenOffset);
+ size += FormatSpec.SIGNED_CHILDREN_ADDRESS_SIZE;
+
+ if (info.mShortcutTargets != null && info.mShortcutTargets.size() > 0) {
+ final int shortcutListSize =
+ BinaryDictInputOutput.getShortcutListSize(info.mShortcutTargets);
+ destination.write((byte)(shortcutListSize >> 8));
+ destination.write((byte)(shortcutListSize & 0xFF));
+ size += 2;
+ final Iterator<WeightedString> shortcutIterator = info.mShortcutTargets.iterator();
+ while (shortcutIterator.hasNext()) {
+ final WeightedString target = shortcutIterator.next();
+ destination.write((byte)BinaryDictInputOutput.makeShortcutFlags(
+ shortcutIterator.hasNext(), target.mFrequency));
+ size++;
+ size += writeString(destination, target.mWord);
+ }
+ }
+
+ if (info.mBigrams != null) {
+ // TODO: Consolidate this code with the code that computes the size of the bigram list
+ // in BinaryDictionaryInputOutput#computeActualNodeSize
+ for (int i = 0; i < info.mBigrams.size(); ++i) {
+
+ final int bigramFrequency = info.mBigrams.get(i).mFrequency;
+ int bigramFlags = (i < info.mBigrams.size() - 1)
+ ? FormatSpec.FLAG_ATTRIBUTE_HAS_NEXT : 0;
+ size++;
+ final int bigramOffset = info.mBigrams.get(i).mAddress - (info.mOriginalAddress
+ + size);
+ bigramFlags |= (bigramOffset < 0) ? FormatSpec.FLAG_ATTRIBUTE_OFFSET_NEGATIVE : 0;
+ switch (BinaryDictInputOutput.getByteSize(bigramOffset)) {
+ case 1:
+ bigramFlags |= FormatSpec.FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE;
+ break;
+ case 2:
+ bigramFlags |= FormatSpec.FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES;
+ break;
+ case 3:
+ bigramFlags |= FormatSpec.FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES;
+ break;
+ }
+ bigramFlags |= bigramFrequency & FormatSpec.FLAG_ATTRIBUTE_FREQUENCY;
+ destination.write((byte)bigramFlags);
+ size += writeVariableAddress(destination, Math.abs(bigramOffset));
+ }
+ }
+ return size;
+ }
+
+ @SuppressWarnings("unused")
+ private static void updateForwardLink(final FusionDictionaryBufferInterface buffer,
+ final int nodeOriginAddress, final int newNodeAddress,
+ final FormatOptions formatOptions) {
+ buffer.position(nodeOriginAddress);
+ int jumpCount = 0;
+ while (jumpCount++ < MAX_JUMPS) {
+ final int count = BinaryDictInputOutput.readCharGroupCount(buffer);
+ for (int i = 0; i < count; ++i) skipCharGroup(buffer, formatOptions);
+ final int forwardLinkAddress = buffer.readUnsignedInt24();
+ if (forwardLinkAddress == FormatSpec.NO_FORWARD_LINK_ADDRESS) {
+ buffer.position(buffer.position() - FormatSpec.FORWARD_LINK_ADDRESS_SIZE);
+ writeSInt24ToBuffer(buffer, newNodeAddress);
+ return;
+ }
+ buffer.position(forwardLinkAddress);
+ }
+ if (DBG && jumpCount >= MAX_JUMPS) {
+ throw new RuntimeException("too many jumps, probably a bug.");
+ }
+ }
+
+ /**
+ * Helper method to move a char group to the tail of the file.
+ */
+ private static int moveCharGroup(final OutputStream destination,
+ final FusionDictionaryBufferInterface buffer, final CharGroupInfo info,
+ final int nodeOriginAddress, final int oldGroupAddress,
+ final FormatOptions formatOptions) throws IOException {
+ updateParentAddress(buffer, oldGroupAddress, buffer.limit() + 1, formatOptions);
+ buffer.position(oldGroupAddress);
+ final int currentFlags = buffer.readUnsignedByte();
+ buffer.position(oldGroupAddress);
+ buffer.put((byte)(FormatSpec.FLAG_IS_MOVED | (currentFlags
+ & (~FormatSpec.MASK_MOVE_AND_DELETE_FLAG))));
+ int size = FormatSpec.GROUP_FLAGS_SIZE;
+ updateForwardLink(buffer, nodeOriginAddress, buffer.limit(), formatOptions);
+ size += writeNode(destination, new CharGroupInfo[] { info });
+ return size;
+ }
+
+ /**
+ * Compute the size of the char group.
+ */
+ private static int computeGroupSize(final CharGroupInfo info,
+ final FormatOptions formatOptions) {
+ int size = FormatSpec.GROUP_FLAGS_SIZE + FormatSpec.PARENT_ADDRESS_SIZE
+ + BinaryDictInputOutput.getGroupCharactersSize(info.mCharacters)
+ + BinaryDictInputOutput.getChildrenAddressSize(info.mFlags, formatOptions);
+ if ((info.mFlags & FormatSpec.FLAG_IS_TERMINAL) != 0) {
+ size += FormatSpec.GROUP_FREQUENCY_SIZE;
+ }
+ if (info.mShortcutTargets != null && !info.mShortcutTargets.isEmpty()) {
+ size += BinaryDictInputOutput.getShortcutListSize(info.mShortcutTargets);
+ }
+ if (info.mBigrams != null) {
+ for (final PendingAttribute attr : info.mBigrams) {
+ size += FormatSpec.GROUP_FLAGS_SIZE;
+ size += BinaryDictInputOutput.getByteSize(attr.mAddress);
+ }
+ }
+ return size;
+ }
+
+ /**
+ * Write a node to the stream.
+ *
+ * @param destination the stream to write.
+ * @param infos groups to be written.
+ * @return the size written, in bytes.
+ * @throws IOException
+ */
+ private static int writeNode(final OutputStream destination, final CharGroupInfo[] infos)
+ throws IOException {
+ int size = BinaryDictInputOutput.getGroupCountSize(infos.length);
+ switch (BinaryDictInputOutput.getGroupCountSize(infos.length)) {
+ case 1:
+ destination.write((byte)infos.length);
+ break;
+ case 2:
+ destination.write((byte)(infos.length >> 8));
+ destination.write((byte)(infos.length & 0xFF));
+ break;
+ default:
+ throw new RuntimeException("Invalid group count size.");
+ }
+ for (final CharGroupInfo info : infos) size += writeCharGroup(destination, info);
+ writeSInt24ToStream(destination, FormatSpec.NO_FORWARD_LINK_ADDRESS);
+ return size + FormatSpec.FORWARD_LINK_ADDRESS_SIZE;
+ }
+
+ /**
+ * Move a group that is referred to by oldGroupOrigin to the tail of the file.
+ * And set the children address to the byte after the group.
+ *
+ * @param nodeOrigin the address of the tail of the file.
+ * @param characters
+ * @param length
+ * @param flags
+ * @param frequency
+ * @param parentAddress
+ * @param shortcutTargets
+ * @param bigrams
+ * @param destination the stream representing the tail of the file.
+ * @param buffer the buffer representing the (constant-size) body of the file.
+ * @param oldNodeOrigin
+ * @param oldGroupOrigin
+ * @param formatOptions
+ * @return the size written, in bytes.
+ * @throws IOException
+ */
+ private static int moveGroup(final int nodeOrigin, final int[] characters, final int length,
+ final int flags, final int frequency, final int parentAddress,
+ final ArrayList<WeightedString> shortcutTargets,
+ final ArrayList<PendingAttribute> bigrams, final OutputStream destination,
+ final FusionDictionaryBufferInterface buffer, final int oldNodeOrigin,
+ final int oldGroupOrigin, final FormatOptions formatOptions) throws IOException {
+ int size = 0;
+ final int newGroupOrigin = nodeOrigin + 1;
+ final int[] writtenCharacters = Arrays.copyOfRange(characters, 0, length);
+ final CharGroupInfo tmpInfo = new CharGroupInfo(newGroupOrigin, -1 /* endAddress */,
+ flags, writtenCharacters, frequency, parentAddress, FormatSpec.NO_CHILDREN_ADDRESS,
+ shortcutTargets, bigrams);
+ size = computeGroupSize(tmpInfo, formatOptions);
+ final CharGroupInfo newInfo = new CharGroupInfo(newGroupOrigin, newGroupOrigin + size,
+ flags, writtenCharacters, frequency, parentAddress,
+ nodeOrigin + 1 + size + FormatSpec.FORWARD_LINK_ADDRESS_SIZE, shortcutTargets,
+ bigrams);
+ moveCharGroup(destination, buffer, newInfo, oldNodeOrigin, oldGroupOrigin, formatOptions);
+ return 1 + size + FormatSpec.FORWARD_LINK_ADDRESS_SIZE;
+ }
+
+ /**
+ * Insert a word into a binary dictionary.
+ *
+ * @param buffer
+ * @param destination
+ * @param word
+ * @param frequency
+ * @param bigramStrings
+ * @param shortcuts
+ * @throws IOException
+ * @throws UnsupportedFormatException
+ */
+ // TODO: Support batch insertion.
+ // TODO: Remove @UsedForTesting once UserHistoryDictionary is implemented by BinaryDictionary.
+ @UsedForTesting
+ public static void insertWord(final FusionDictionaryBufferInterface buffer,
+ final OutputStream destination, final String word, final int frequency,
+ final ArrayList<WeightedString> bigramStrings,
+ final ArrayList<WeightedString> shortcuts, final boolean isNotAWord,
+ final boolean isBlackListEntry)
+ throws IOException, UnsupportedFormatException {
+ final ArrayList<PendingAttribute> bigrams = new ArrayList<PendingAttribute>();
+ if (bigramStrings != null) {
+ for (final WeightedString bigram : bigramStrings) {
+ int position = getTerminalPosition(buffer, bigram.mWord);
+ if (position == FormatSpec.NOT_VALID_WORD) {
+ // TODO: figure out what is the correct thing to do here.
+ } else {
+ bigrams.add(new PendingAttribute(bigram.mFrequency, position));
+ }
+ }
+ }
+
+ final boolean isTerminal = true;
+ final boolean hasBigrams = !bigrams.isEmpty();
+ final boolean hasShortcuts = shortcuts != null && !shortcuts.isEmpty();
+
+ // find the insert position of the word.
+ if (buffer.position() != 0) buffer.position(0);
+ final FileHeader header = BinaryDictInputOutput.readHeader(buffer);
+
+ int wordPos = 0, address = buffer.position(), nodeOriginAddress = buffer.position();
+ final int[] codePoints = FusionDictionary.getCodePoints(word);
+ final int wordLen = codePoints.length;
+
+ for (int depth = 0; depth < Constants.Dictionary.MAX_WORD_LENGTH; ++depth) {
+ if (wordPos >= wordLen) break;
+ nodeOriginAddress = buffer.position();
+ int nodeParentAddress = -1;
+ final int charGroupCount = BinaryDictInputOutput.readCharGroupCount(buffer);
+ boolean foundNextGroup = false;
+
+ for (int i = 0; i < charGroupCount; ++i) {
+ address = buffer.position();
+ final CharGroupInfo currentInfo = BinaryDictInputOutput.readCharGroup(buffer,
+ buffer.position(), header.mFormatOptions);
+ final boolean isMovedGroup = BinaryDictInputOutput.isMovedGroup(currentInfo.mFlags,
+ header.mFormatOptions);
+ if (isMovedGroup) continue;
+ nodeParentAddress = (currentInfo.mParentAddress == FormatSpec.NO_PARENT_ADDRESS)
+ ? FormatSpec.NO_PARENT_ADDRESS : currentInfo.mParentAddress + address;
+ boolean matched = true;
+ for (int p = 0; p < currentInfo.mCharacters.length; ++p) {
+ if (wordPos + p >= wordLen) {
+ /*
+ * splitting
+ * before
+ * abcd - ef
+ *
+ * insert "abc"
+ *
+ * after
+ * abc - d - ef
+ */
+ final int newNodeAddress = buffer.limit();
+ final int flags = BinaryDictInputOutput.makeCharGroupFlags(p > 1,
+ isTerminal, 0, hasShortcuts, hasBigrams, false /* isNotAWord */,
+ false /* isBlackListEntry */, header.mFormatOptions);
+ int written = moveGroup(newNodeAddress, currentInfo.mCharacters, p, flags,
+ frequency, nodeParentAddress, shortcuts, bigrams, destination,
+ buffer, nodeOriginAddress, address, header.mFormatOptions);
+
+ final int[] characters2 = Arrays.copyOfRange(currentInfo.mCharacters, p,
+ currentInfo.mCharacters.length);
+ if (currentInfo.mChildrenAddress != FormatSpec.NO_CHILDREN_ADDRESS) {
+ updateParentAddresses(buffer, currentInfo.mChildrenAddress,
+ newNodeAddress + written + 1, header.mFormatOptions);
+ }
+ final CharGroupInfo newInfo2 = new CharGroupInfo(
+ newNodeAddress + written + 1, -1 /* endAddress */,
+ currentInfo.mFlags, characters2, currentInfo.mFrequency,
+ newNodeAddress + 1, currentInfo.mChildrenAddress,
+ currentInfo.mShortcutTargets, currentInfo.mBigrams);
+ writeNode(destination, new CharGroupInfo[] { newInfo2 });
+ return;
+ } else if (codePoints[wordPos + p] != currentInfo.mCharacters[p]) {
+ if (p > 0) {
+ /*
+ * splitting
+ * before
+ * ab - cd
+ *
+ * insert "ac"
+ *
+ * after
+ * a - b - cd
+ * |
+ * - c
+ */
+
+ final int newNodeAddress = buffer.limit();
+ final int childrenAddress = currentInfo.mChildrenAddress;
+
+ // move prefix
+ final int prefixFlags = BinaryDictInputOutput.makeCharGroupFlags(p > 1,
+ false /* isTerminal */, 0 /* childrenAddressSize*/,
+ false /* hasShortcut */, false /* hasBigrams */,
+ false /* isNotAWord */, false /* isBlackListEntry */,
+ header.mFormatOptions);
+ int written = moveGroup(newNodeAddress, currentInfo.mCharacters, p,
+ prefixFlags, -1 /* frequency */, nodeParentAddress, null, null,
+ destination, buffer, nodeOriginAddress, address,
+ header.mFormatOptions);
+
+ final int[] suffixCharacters = Arrays.copyOfRange(
+ currentInfo.mCharacters, p, currentInfo.mCharacters.length);
+ if (currentInfo.mChildrenAddress != FormatSpec.NO_CHILDREN_ADDRESS) {
+ updateParentAddresses(buffer, currentInfo.mChildrenAddress,
+ newNodeAddress + written + 1, header.mFormatOptions);
+ }
+ final int suffixFlags = BinaryDictInputOutput.makeCharGroupFlags(
+ suffixCharacters.length > 1,
+ (currentInfo.mFlags & FormatSpec.FLAG_IS_TERMINAL) != 0,
+ 0 /* childrenAddressSize */,
+ (currentInfo.mFlags & FormatSpec.FLAG_HAS_SHORTCUT_TARGETS)
+ != 0,
+ (currentInfo.mFlags & FormatSpec.FLAG_HAS_BIGRAMS) != 0,
+ isNotAWord, isBlackListEntry, header.mFormatOptions);
+ final CharGroupInfo suffixInfo = new CharGroupInfo(
+ newNodeAddress + written + 1, -1 /* endAddress */, suffixFlags,
+ suffixCharacters, currentInfo.mFrequency, newNodeAddress + 1,
+ currentInfo.mChildrenAddress, currentInfo.mShortcutTargets,
+ currentInfo.mBigrams);
+ written += computeGroupSize(suffixInfo, header.mFormatOptions) + 1;
+
+ final int[] newCharacters = Arrays.copyOfRange(codePoints, wordPos + p,
+ codePoints.length);
+ final int flags = BinaryDictInputOutput.makeCharGroupFlags(
+ newCharacters.length > 1, isTerminal,
+ 0 /* childrenAddressSize */, hasShortcuts, hasBigrams,
+ isNotAWord, isBlackListEntry, header.mFormatOptions);
+ final CharGroupInfo newInfo = new CharGroupInfo(
+ newNodeAddress + written, -1 /* endAddress */, flags,
+ newCharacters, frequency, newNodeAddress + 1,
+ FormatSpec.NO_CHILDREN_ADDRESS, shortcuts, bigrams);
+ writeNode(destination, new CharGroupInfo[] { suffixInfo, newInfo });
+ return;
+ }
+ matched = false;
+ break;
+ }
+ }
+
+ if (matched) {
+ if (wordPos + currentInfo.mCharacters.length == wordLen) {
+ // the word exists in the dictionary.
+ // only update group.
+ final int newNodeAddress = buffer.limit();
+ final boolean hasMultipleChars = currentInfo.mCharacters.length > 1;
+ final int flags = BinaryDictInputOutput.makeCharGroupFlags(hasMultipleChars,
+ isTerminal, 0 /* childrenAddressSize */, hasShortcuts, hasBigrams,
+ isNotAWord, isBlackListEntry, header.mFormatOptions);
+ final CharGroupInfo newInfo = new CharGroupInfo(newNodeAddress + 1,
+ -1 /* endAddress */, flags, currentInfo.mCharacters, frequency,
+ nodeParentAddress, currentInfo.mChildrenAddress, shortcuts,
+ bigrams);
+ moveCharGroup(destination, buffer, newInfo, nodeOriginAddress, address,
+ header.mFormatOptions);
+ return;
+ }
+ wordPos += currentInfo.mCharacters.length;
+ if (currentInfo.mChildrenAddress == FormatSpec.NO_CHILDREN_ADDRESS) {
+ /*
+ * found the prefix of the word.
+ * make new node and link to the node from this group.
+ *
+ * before
+ * ab - cd
+ *
+ * insert "abcde"
+ *
+ * after
+ * ab - cd - e
+ */
+ final int newNodeAddress = buffer.limit();
+ updateChildrenAddress(buffer, address, newNodeAddress,
+ header.mFormatOptions);
+ final int newGroupAddress = newNodeAddress + 1;
+ final boolean hasMultipleChars = (wordLen - wordPos) > 1;
+ final int flags = BinaryDictInputOutput.makeCharGroupFlags(hasMultipleChars,
+ isTerminal, 0 /* childrenAddressSize */, hasShortcuts, hasBigrams,
+ isNotAWord, isBlackListEntry, header.mFormatOptions);
+ final int[] characters = Arrays.copyOfRange(codePoints, wordPos, wordLen);
+ final CharGroupInfo newInfo = new CharGroupInfo(newGroupAddress, -1, flags,
+ characters, frequency, address, FormatSpec.NO_CHILDREN_ADDRESS,
+ shortcuts, bigrams);
+ writeNode(destination, new CharGroupInfo[] { newInfo });
+ return;
+ }
+ buffer.position(currentInfo.mChildrenAddress);
+ foundNextGroup = true;
+ break;
+ }
+ }
+
+ if (foundNextGroup) continue;
+
+ // reached the end of the array.
+ final int linkAddressPosition = buffer.position();
+ int nextLink = buffer.readUnsignedInt24();
+ if ((nextLink & MSB24) != 0) {
+ nextLink = -(nextLink & SINT24_MAX);
+ }
+ if (nextLink == FormatSpec.NO_FORWARD_LINK_ADDRESS) {
+ /*
+ * expand this node.
+ *
+ * before
+ * ab - cd
+ *
+ * insert "abef"
+ *
+ * after
+ * ab - cd
+ * |
+ * - ef
+ */
+
+ // change the forward link address.
+ final int newNodeAddress = buffer.limit();
+ buffer.position(linkAddressPosition);
+ writeSInt24ToBuffer(buffer, newNodeAddress);
+
+ final int[] characters = Arrays.copyOfRange(codePoints, wordPos, wordLen);
+ final int flags = BinaryDictInputOutput.makeCharGroupFlags(characters.length > 1,
+ isTerminal, 0 /* childrenAddressSize */, hasShortcuts, hasBigrams,
+ isNotAWord, isBlackListEntry, header.mFormatOptions);
+ final CharGroupInfo newInfo = new CharGroupInfo(newNodeAddress + 1,
+ -1 /* endAddress */, flags, characters, frequency, nodeParentAddress,
+ FormatSpec.NO_CHILDREN_ADDRESS, shortcuts, bigrams);
+ writeNode(destination, new CharGroupInfo[]{ newInfo });
+ return;
+ } else {
+ depth--;
+ buffer.position(nextLink);
+ }
+ }
+ }
+
+ /**
+ * Find a word from the buffer.
+ *
+ * @param buffer the buffer representing the body of the dictionary file.
+ * @param word the word searched
+ * @return the found group
+ * @throws IOException
+ * @throws UnsupportedFormatException
+ */
+ @UsedForTesting
+ public static CharGroupInfo findWordFromBuffer(final FusionDictionaryBufferInterface buffer,
+ final String word) throws IOException, UnsupportedFormatException {
+ int position = getTerminalPosition(buffer, word);
+ if (position != FormatSpec.NOT_VALID_WORD) {
+ buffer.position(0);
+ final FileHeader header = BinaryDictInputOutput.readHeader(buffer);
+ buffer.position(position);
+ return BinaryDictInputOutput.readCharGroup(buffer, position, header.mFormatOptions);
+ }
+ return null;
+ }
+
+ /**
+ * Convenience method to read the header of a binary file.
+ *
+ * This is quite resource intensive - don't call when performance is critical.
+ *
+ * @param file The file to read.
+ * @param offset The offset in the file where to start reading the data.
+ * @param length The length of the data file.
+ */
+ private static final int HEADER_READING_BUFFER_SIZE = 16384;
+ public static FileHeader getDictionaryFileHeader(
+ final File file, final long offset, final long length)
+ throws FileNotFoundException, IOException, UnsupportedFormatException {
+ final byte[] buffer = new byte[HEADER_READING_BUFFER_SIZE];
+ final FileInputStream inStream = new FileInputStream(file);
+ try {
+ inStream.read(buffer);
+ final BinaryDictInputOutput.ByteBufferWrapper wrapper =
+ new BinaryDictInputOutput.ByteBufferWrapper(inStream.getChannel().map(
+ FileChannel.MapMode.READ_ONLY, offset, length));
+ return BinaryDictInputOutput.readHeader(wrapper);
+ } finally {
+ inStream.close();
+ }
+ }
+
+ public static FileHeader getDictionaryFileHeaderOrNull(final File file, final long offset,
+ final long length) {
+ try {
+ final FileHeader header = getDictionaryFileHeader(file, offset, length);
+ return header;
+ } catch (UnsupportedFormatException e) {
+ return null;
+ } catch (IOException e) {
+ return null;
+ }
+ }
}
diff --git a/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java b/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java
index b431a4da9..58ec1e83f 100644
--- a/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java
+++ b/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java
@@ -1,21 +1,22 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader;
import com.android.inputmethod.latin.makedict.FormatSpec.FormatOptions;
import com.android.inputmethod.latin.makedict.FusionDictionary.CharGroup;
@@ -55,6 +56,7 @@ public final class BinaryDictInputOutput {
private static final int MAX_PASSES = 24;
private static final int MAX_JUMPS = 12;
+ @UsedForTesting
public interface FusionDictionaryBufferInterface {
public int readUnsignedByte();
public int readUnsignedShort();
@@ -76,12 +78,12 @@ public final class BinaryDictInputOutput {
@Override
public int readUnsignedByte() {
- return ((int)mBuffer.get()) & 0xFF;
+ return mBuffer.get() & 0xFF;
}
@Override
public int readUnsignedShort() {
- return ((int)mBuffer.getShort()) & 0xFFFF;
+ return mBuffer.getShort() & 0xFFFF;
}
@Override
@@ -124,8 +126,7 @@ public final class BinaryDictInputOutput {
/**
* A class grouping utility function for our specific character encoding.
*/
- private static final class CharEncoding {
-
+ static final class CharEncoding {
private static final int MINIMAL_ONE_BYTE_CHARACTER_VALUE = 0x20;
private static final int MAXIMAL_ONE_BYTE_CHARACTER_VALUE = 0xFF;
@@ -154,7 +155,7 @@ public final class BinaryDictInputOutput {
* @param character the character code.
* @return the size in binary encoded-form, either 1 or 3 bytes.
*/
- private static int getCharSize(final int character) {
+ static int getCharSize(final int character) {
// See char encoding in FusionDictionary.java
if (fitsOnOneByte(character)) return 1;
if (FormatSpec.INVALID_CHARACTER == character) return 1;
@@ -263,7 +264,7 @@ public final class BinaryDictInputOutput {
* @param buffer the buffer, positioned over an encoded character.
* @return the character code.
*/
- private static int readChar(final FusionDictionaryBufferInterface buffer) {
+ static int readChar(final FusionDictionaryBufferInterface buffer) {
int character = buffer.readUnsignedByte();
if (!fitsOnOneByte(character)) {
if (FormatSpec.GROUP_CHARACTERS_TERMINATOR == character) {
@@ -277,6 +278,21 @@ public final class BinaryDictInputOutput {
}
/**
+ * Compute the binary size of the character array.
+ *
+ * If only one character, this is the size of this character. If many, it's the sum of their
+ * sizes + 1 byte for the terminator.
+ *
+ * @param characters the character array
+ * @return the size of the char array, including the terminator if any
+ */
+ static int getGroupCharactersSize(final int[] characters) {
+ int size = CharEncoding.getCharArraySize(characters);
+ if (characters.length > 1) size += FormatSpec.GROUP_TERMINATOR_SIZE;
+ return size;
+ }
+
+ /**
* Compute the binary size of the character array in a group
*
* If only one character, this is the size of this character. If many, it's the sum of their
@@ -286,9 +302,7 @@ public final class BinaryDictInputOutput {
* @return the size of the char array, including the terminator if any
*/
private static int getGroupCharactersSize(final CharGroup group) {
- int size = CharEncoding.getCharArraySize(group.mChars);
- if (group.hasSeveralChars()) size += FormatSpec.GROUP_TERMINATOR_SIZE;
- return size;
+ return getGroupCharactersSize(group.mChars);
}
/**
@@ -338,7 +352,7 @@ public final class BinaryDictInputOutput {
* This is known in advance and does not change according to position in the file
* like address lists do.
*/
- private static int getShortcutListSize(final ArrayList<WeightedString> shortcutList) {
+ static int getShortcutListSize(final ArrayList<WeightedString> shortcutList) {
if (null == shortcutList) return 0;
int size = FormatSpec.GROUP_SHORTCUT_LIST_SIZE_SIZE;
for (final WeightedString shortcut : shortcutList) {
@@ -399,7 +413,16 @@ public final class BinaryDictInputOutput {
* Helper method to check whether the group is moved.
*/
public static boolean isMovedGroup(final int flags, final FormatOptions options) {
- return options.mSupportsDynamicUpdate && ((flags & FormatSpec.FLAG_IS_MOVED) == 1);
+ return options.mSupportsDynamicUpdate
+ && ((flags & FormatSpec.MASK_GROUP_ADDRESS_TYPE) == FormatSpec.FLAG_IS_MOVED);
+ }
+
+ /**
+ * Helper method to check whether the group is deleted.
+ */
+ public static boolean isDeletedGroup(final int flags, final FormatOptions formatOptions) {
+ return formatOptions.mSupportsDynamicUpdate
+ && ((flags & FormatSpec.MASK_GROUP_ADDRESS_TYPE) == FormatSpec.FLAG_IS_DELETED);
}
/**
@@ -439,7 +462,7 @@ public final class BinaryDictInputOutput {
* @param address the address
* @return the byte size.
*/
- private static int getByteSize(final int address) {
+ static int getByteSize(final int address) {
assert(address <= UINT24_MAX);
if (!hasChildrenAddress(address)) {
return 0;
@@ -452,11 +475,8 @@ public final class BinaryDictInputOutput {
}
}
- private static final int SINT8_MAX = 0x7F;
- private static final int SINT16_MAX = 0x7FFF;
private static final int SINT24_MAX = 0x7FFFFF;
private static final int MSB8 = 0x80;
- private static final int MSB16 = 0x8000;
private static final int MSB24 = 0x800000;
// End utility methods.
@@ -721,53 +741,60 @@ public final class BinaryDictInputOutput {
return 3;
}
- private static byte makeCharGroupFlags(final CharGroup group, final int groupAddress,
- final int childrenOffset, final FormatOptions formatOptions) {
+ /**
+ * Makes the flag value for a char group.
+ *
+ * @param hasMultipleChars whether the group has multiple chars.
+ * @param isTerminal whether the group is terminal.
+ * @param childrenAddressSize the size of a children address.
+ * @param hasShortcuts whether the group has shortcuts.
+ * @param hasBigrams whether the group has bigrams.
+ * @param isNotAWord whether the group is not a word.
+ * @param isBlackListEntry whether the group is a blacklist entry.
+ * @param formatOptions file format options.
+ * @return the flags
+ */
+ static int makeCharGroupFlags(final boolean hasMultipleChars, final boolean isTerminal,
+ final int childrenAddressSize, final boolean hasShortcuts, final boolean hasBigrams,
+ final boolean isNotAWord, final boolean isBlackListEntry,
+ final FormatOptions formatOptions) {
byte flags = 0;
- if (group.mChars.length > 1) flags |= FormatSpec.FLAG_HAS_MULTIPLE_CHARS;
- if (group.mFrequency >= 0) {
- flags |= FormatSpec.FLAG_IS_TERMINAL;
- }
- if (null != group.mChildren) {
- final int byteSize = formatOptions.mSupportsDynamicUpdate
- ? FormatSpec.SIGNED_CHILDREN_ADDRESS_SIZE : getByteSize(childrenOffset);
- switch (byteSize) {
- case 1:
- flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_ONEBYTE;
- break;
- case 2:
- flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_TWOBYTES;
- break;
- case 3:
- flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_THREEBYTES;
- break;
- default:
- throw new RuntimeException("Node with a strange address");
- }
- } else if (formatOptions.mSupportsDynamicUpdate) {
- flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_THREEBYTES;
- }
- if (null != group.mShortcutTargets) {
- if (DBG && 0 == group.mShortcutTargets.size()) {
- throw new RuntimeException("0-sized shortcut list must be null");
- }
- flags |= FormatSpec.FLAG_HAS_SHORTCUT_TARGETS;
- }
- if (null != group.mBigrams) {
- if (DBG && 0 == group.mBigrams.size()) {
- throw new RuntimeException("0-sized bigram list must be null");
+ if (hasMultipleChars) flags |= FormatSpec.FLAG_HAS_MULTIPLE_CHARS;
+ if (isTerminal) flags |= FormatSpec.FLAG_IS_TERMINAL;
+ if (formatOptions.mSupportsDynamicUpdate) {
+ flags |= FormatSpec.FLAG_IS_NOT_MOVED;
+ } else if (true) {
+ switch (childrenAddressSize) {
+ case 1:
+ flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_ONEBYTE;
+ break;
+ case 2:
+ flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_TWOBYTES;
+ break;
+ case 3:
+ flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_THREEBYTES;
+ break;
+ case 0:
+ flags |= FormatSpec.FLAG_GROUP_ADDRESS_TYPE_NOADDRESS;
+ break;
+ default:
+ throw new RuntimeException("Node with a strange address");
}
- flags |= FormatSpec.FLAG_HAS_BIGRAMS;
- }
- if (group.mIsNotAWord) {
- flags |= FormatSpec.FLAG_IS_NOT_A_WORD;
- }
- if (group.mIsBlacklistEntry) {
- flags |= FormatSpec.FLAG_IS_BLACKLISTED;
}
+ if (hasShortcuts) flags |= FormatSpec.FLAG_HAS_SHORTCUT_TARGETS;
+ if (hasBigrams) flags |= FormatSpec.FLAG_HAS_BIGRAMS;
+ if (isNotAWord) flags |= FormatSpec.FLAG_IS_NOT_A_WORD;
+ if (isBlackListEntry) flags |= FormatSpec.FLAG_IS_BLACKLISTED;
return flags;
}
+ private static byte makeCharGroupFlags(final CharGroup group, final int groupAddress,
+ final int childrenOffset, final FormatOptions formatOptions) {
+ return (byte) makeCharGroupFlags(group.mChars.length > 1, group.mFrequency >= 0,
+ getByteSize(childrenOffset), group.mShortcutTargets != null, group.mBigrams != null,
+ group.mIsNotAWord, group.mIsBlacklistEntry, formatOptions);
+ }
+
/**
* Makes the flag value for a bigram.
*
@@ -859,7 +886,7 @@ public final class BinaryDictInputOutput {
* @param frequency the frequency of the attribute, 0..15
* @return the flags
*/
- private static final int makeShortcutFlags(final boolean more, final int frequency) {
+ static final int makeShortcutFlags(final boolean more, final int frequency) {
return (more ? FormatSpec.FLAG_ATTRIBUTE_HAS_NEXT : 0)
+ (frequency & FormatSpec.FLAG_ATTRIBUTE_FREQUENCY);
}
@@ -895,8 +922,10 @@ public final class BinaryDictInputOutput {
* @param formatOptions file format options.
* @return the address of the END of the node.
*/
+ @SuppressWarnings("unused")
private static int writePlacedNode(final FusionDictionary dict, byte[] buffer,
final Node node, final FormatOptions formatOptions) {
+ // TODO: Make the code in common with BinaryDictIOUtils#writeCharGroup
int index = node.mCachedAddress;
final int groupCount = node.mData.size();
@@ -1178,7 +1207,7 @@ public final class BinaryDictInputOutput {
// Input methods: Read a binary dictionary to memory.
// readDictionaryBinary is the public entry point for them.
- private static int getChildrenAddressSize(final int optionFlags,
+ static int getChildrenAddressSize(final int optionFlags,
final FormatOptions formatOptions) {
if (formatOptions.mSupportsDynamicUpdate) return FormatSpec.SIGNED_CHILDREN_ADDRESS_SIZE;
switch (optionFlags & FormatSpec.MASK_GROUP_ADDRESS_TYPE) {
@@ -1194,7 +1223,7 @@ public final class BinaryDictInputOutput {
}
}
- private static int readChildrenAddress(final FusionDictionaryBufferInterface buffer,
+ static int readChildrenAddress(final FusionDictionaryBufferInterface buffer,
final int optionFlags, final FormatOptions options) {
if (options.mSupportsDynamicUpdate) {
final int address = buffer.readUnsignedInt24();
@@ -1219,7 +1248,7 @@ public final class BinaryDictInputOutput {
}
}
- private static int readParentAddress(final FusionDictionaryBufferInterface buffer,
+ static int readParentAddress(final FusionDictionaryBufferInterface buffer,
final FormatOptions formatOptions) {
if (supportsDynamicUpdate(formatOptions)) {
final int parentAddress = buffer.readUnsignedInt24();
@@ -1290,7 +1319,8 @@ public final class BinaryDictInputOutput {
ArrayList<PendingAttribute> bigrams = null;
if (0 != (flags & FormatSpec.FLAG_HAS_BIGRAMS)) {
bigrams = new ArrayList<PendingAttribute>();
- while (true) {
+ int bigramCount = 0;
+ while (bigramCount++ < FormatSpec.MAX_BIGRAMS_IN_A_GROUP) {
final int bigramFlags = buffer.readUnsignedByte();
++addressPointer;
final int sign = 0 == (bigramFlags & FormatSpec.FLAG_ATTRIBUTE_OFFSET_NEGATIVE)
@@ -1318,6 +1348,9 @@ public final class BinaryDictInputOutput {
bigramAddress));
if (0 == (bigramFlags & FormatSpec.FLAG_ATTRIBUTE_HAS_NEXT)) break;
}
+ if (bigramCount >= FormatSpec.MAX_BIGRAMS_IN_A_GROUP) {
+ MakedictLog.d("too many bigrams in a group.");
+ }
}
return new CharGroupInfo(originalGroupAddress, addressPointer, flags, characters, frequency,
parentAddress, childrenAddress, shortcutTargets, bigrams);
@@ -1340,7 +1373,8 @@ public final class BinaryDictInputOutput {
// of this method. Since it performs direct, unbuffered random access to the file and
// may be called hundreds of thousands of times, the resulting performance is not
// reasonable without some kind of cache. Thus:
- private static TreeMap<Integer, String> wordCache = new TreeMap<Integer, String>();
+ private static TreeMap<Integer, WeightedString> wordCache =
+ new TreeMap<Integer, WeightedString>();
/**
* Finds, as a string, the word at the address passed as an argument.
*
@@ -1348,15 +1382,15 @@ public final class BinaryDictInputOutput {
* @param headerSize the size of the header.
* @param address the address to seek.
* @param formatOptions file format options.
- * @return the word, as a string.
+ * @return the word with its frequency, as a weighted string.
*/
- /* packages for tests */ static String getWordAtAddress(
+ /* package for tests */ static WeightedString getWordAtAddress(
final FusionDictionaryBufferInterface buffer, final int headerSize, final int address,
final FormatOptions formatOptions) {
- final String cachedString = wordCache.get(address);
+ final WeightedString cachedString = wordCache.get(address);
if (null != cachedString) return cachedString;
- final String result;
+ final WeightedString result;
final int originalPointer = buffer.position();
buffer.position(address);
@@ -1372,14 +1406,16 @@ public final class BinaryDictInputOutput {
return result;
}
+ // TODO: static!? This will behave erratically when used in multi-threaded code.
+ // We need to fix this
private static int[] sGetWordBuffer = new int[FormatSpec.MAX_WORD_LENGTH];
- private static String getWordAtAddressWithParentAddress(
+ @SuppressWarnings("unused")
+ private static WeightedString getWordAtAddressWithParentAddress(
final FusionDictionaryBufferInterface buffer, final int headerSize, final int address,
final FormatOptions options) {
- final StringBuilder builder = new StringBuilder();
-
int currentAddress = address;
int index = FormatSpec.MAX_WORD_LENGTH - 1;
+ int frequency = Integer.MIN_VALUE;
// the length of the path from the root to the leaf is limited by MAX_WORD_LENGTH
for (int count = 0; count < FormatSpec.MAX_WORD_LENGTH; ++count) {
CharGroupInfo currentInfo;
@@ -1394,6 +1430,7 @@ public final class BinaryDictInputOutput {
MakedictLog.d("Too many jumps - probably a bug");
}
} while (isMovedGroup(currentInfo.mFlags, options));
+ if (Integer.MIN_VALUE == frequency) frequency = currentInfo.mFrequency;
for (int i = 0; i < currentInfo.mCharacters.length; ++i) {
sGetWordBuffer[index--] =
currentInfo.mCharacters[currentInfo.mCharacters.length - i - 1];
@@ -1402,17 +1439,19 @@ public final class BinaryDictInputOutput {
currentAddress = currentInfo.mParentAddress + currentInfo.mOriginalAddress;
}
- return new String(sGetWordBuffer, index + 1, FormatSpec.MAX_WORD_LENGTH - index - 1);
+ return new WeightedString(
+ new String(sGetWordBuffer, index + 1, FormatSpec.MAX_WORD_LENGTH - index - 1),
+ frequency);
}
- private static String getWordAtAddressWithoutParentAddress(
+ private static WeightedString getWordAtAddressWithoutParentAddress(
final FusionDictionaryBufferInterface buffer, final int headerSize, final int address,
final FormatOptions options) {
buffer.position(headerSize);
final int count = readCharGroupCount(buffer);
int groupOffset = getGroupCountSize(count);
final StringBuilder builder = new StringBuilder();
- String result = null;
+ WeightedString result = null;
CharGroupInfo last = null;
for (int i = count - 1; i >= 0; --i) {
@@ -1420,7 +1459,7 @@ public final class BinaryDictInputOutput {
groupOffset = info.mEndAddress;
if (info.mOriginalAddress == address) {
builder.append(new String(info.mCharacters, 0, info.mCharacters.length));
- result = builder.toString();
+ result = new WeightedString(builder.toString(), info.mFrequency);
break; // and return
}
if (hasChildrenAddress(info.mChildrenAddress)) {
@@ -1481,9 +1520,11 @@ public final class BinaryDictInputOutput {
if (null != info.mBigrams) {
bigrams = new ArrayList<WeightedString>();
for (PendingAttribute bigram : info.mBigrams) {
- final String word = getWordAtAddress(
+ final WeightedString word = getWordAtAddress(
buffer, headerSize, bigram.mAddress, options);
- bigrams.add(new WeightedString(word, bigram.mFrequency));
+ final int reconstructedFrequency =
+ reconstructBigramFrequency(word.mFrequency, bigram.mFrequency);
+ bigrams.add(new WeightedString(word.mWord, reconstructedFrequency));
}
}
if (hasChildrenAddress(info.mChildrenAddress)) {
@@ -1618,6 +1659,7 @@ public final class BinaryDictInputOutput {
* @param dict an optional dictionary to add words to, or null.
* @return the created (or merged) dictionary.
*/
+ @UsedForTesting
public static FusionDictionary readDictionaryBinary(
final FusionDictionaryBufferInterface buffer, final FusionDictionary dict)
throws IOException, UnsupportedFormatException {
@@ -1655,17 +1697,24 @@ public final class BinaryDictInputOutput {
}
/**
+ * Helper method to pass a file name instead of a File object to isBinaryDictionary.
+ */
+ public static boolean isBinaryDictionary(final String filename) {
+ final File file = new File(filename);
+ return isBinaryDictionary(file);
+ }
+
+ /**
* Basic test to find out whether the file is a binary dictionary or not.
*
* Concretely this only tests the magic number.
*
- * @param filename The name of the file to test.
+ * @param file The file to test.
* @return true if it's a binary dictionary, false otherwise
*/
- public static boolean isBinaryDictionary(final String filename) {
+ public static boolean isBinaryDictionary(final File file) {
FileInputStream inStream = null;
try {
- final File file = new File(filename);
inStream = new FileInputStream(file);
final ByteBuffer buffer = inStream.getChannel().map(
FileChannel.MapMode.READ_ONLY, 0, file.length());
@@ -1700,8 +1749,7 @@ public final class BinaryDictInputOutput {
final int bigramFrequency) {
final float stepSize = (FormatSpec.MAX_TERMINAL_FREQUENCY - unigramFrequency)
/ (1.5f + FormatSpec.MAX_BIGRAM_FREQUENCY);
- final float resultFreqFloat = (float)unigramFrequency
- + stepSize * (bigramFrequency + 1.0f);
+ final float resultFreqFloat = unigramFrequency + stepSize * (bigramFrequency + 1.0f);
return (int)resultFreqFloat;
}
}
diff --git a/java/src/com/android/inputmethod/latin/makedict/CharGroupInfo.java b/java/src/com/android/inputmethod/latin/makedict/CharGroupInfo.java
index 8e64082e6..b3617443e 100644
--- a/java/src/com/android/inputmethod/latin/makedict/CharGroupInfo.java
+++ b/java/src/com/android/inputmethod/latin/makedict/CharGroupInfo.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
diff --git a/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java b/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java
index b3fbb9fb5..e1e5e5500 100644
--- a/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java
+++ b/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.makedict;
@@ -59,9 +59,11 @@ public final class FormatSpec {
* l | 10 = 2 bytes : FLAG_GROUP_ADDRESS_TYPE_TWOBYTES
* a | 11 = 3 bytes : FLAG_GROUP_ADDRESS_TYPE_THREEBYTES
* g | ELSE
- * s | is moved ? 2 bits, 11 = no
- * | 01 = yes
+ * s | is moved ? 2 bits, 11 = no : FLAG_IS_NOT_MOVED
+ * | This must be the same as FLAG_GROUP_ADDRESS_TYPE_THREEBYTES
+ * | 01 = yes : FLAG_IS_MOVED
* | the new address is stored in the same place as the parent address
+ * | is deleted? 10 = yes : FLAG_IS_DELETED
* | has several chars ? 1 bit, 1 = yes, 0 = no : FLAG_HAS_MULTIPLE_CHARS
* | has a terminal ? 1 bit, 1 = yes, 0 = no : FLAG_IS_TERMINAL
* | has shortcut targets ? 1 bit, 1 = yes, 0 = no : FLAG_HAS_SHORTCUT_TARGETS
@@ -170,6 +172,7 @@ public final class FormatSpec {
static final int PARENT_ADDRESS_SIZE = 3;
static final int FORWARD_LINK_ADDRESS_SIZE = 3;
+ // These flags are used only in the static dictionary.
static final int MASK_GROUP_ADDRESS_TYPE = 0xC0;
static final int FLAG_GROUP_ADDRESS_TYPE_NOADDRESS = 0x00;
static final int FLAG_GROUP_ADDRESS_TYPE_ONEBYTE = 0x40;
@@ -183,7 +186,13 @@ public final class FormatSpec {
static final int FLAG_HAS_BIGRAMS = 0x04;
static final int FLAG_IS_NOT_A_WORD = 0x02;
static final int FLAG_IS_BLACKLISTED = 0x01;
- static final int FLAG_IS_MOVED = 0x40;
+
+ // These flags are used only in the dynamic dictionary.
+ static final int MASK_MOVE_AND_DELETE_FLAG = 0xC0;
+ static final int FIXED_BIT_OF_DYNAMIC_UPDATE_MOVE = 0x40;
+ static final int FLAG_IS_MOVED = 0x00 | FIXED_BIT_OF_DYNAMIC_UPDATE_MOVE;
+ static final int FLAG_IS_NOT_MOVED = 0x80 | FIXED_BIT_OF_DYNAMIC_UPDATE_MOVE;
+ static final int FLAG_IS_DELETED = 0x80;
static final int FLAG_ATTRIBUTE_HAS_NEXT = 0x80;
static final int FLAG_ATTRIBUTE_OFFSET_NEGATIVE = 0x40;
@@ -210,10 +219,13 @@ public final class FormatSpec {
static final int MAX_CHARGROUPS_FOR_ONE_BYTE_CHARGROUP_COUNT = 0x7F; // 127
static final int MAX_CHARGROUPS_IN_A_NODE = 0x7FFF; // 32767
+ static final int MAX_BIGRAMS_IN_A_GROUP = 10000;
static final int MAX_TERMINAL_FREQUENCY = 255;
static final int MAX_BIGRAM_FREQUENCY = 15;
+ public static final int SHORTCUT_WHITELIST_FREQUENCY = 15;
+
// This option needs to be the same numeric value as the one in binary_format.h.
static final int NOT_VALID_WORD = -99;
static final int SIGNED_CHILDREN_ADDRESS_SIZE = 3;
@@ -240,16 +252,42 @@ public final class FormatSpec {
/**
* Class representing file header.
*/
- static final class FileHeader {
+ public static final class FileHeader {
public final int mHeaderSize;
public final DictionaryOptions mDictionaryOptions;
public final FormatOptions mFormatOptions;
+ private static final String DICTIONARY_VERSION_ATTRIBUTE = "version";
+ private static final String DICTIONARY_LOCALE_ATTRIBUTE = "locale";
+ private static final String DICTIONARY_ID_ATTRIBUTE = "dictionary";
+ private static final String DICTIONARY_DESCRIPTION_ATTRIBUTE = "description";
public FileHeader(final int headerSize, final DictionaryOptions dictionaryOptions,
final FormatOptions formatOptions) {
mHeaderSize = headerSize;
mDictionaryOptions = dictionaryOptions;
mFormatOptions = formatOptions;
}
+
+ // Helper method to get the locale as a String
+ public String getLocaleString() {
+ return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_LOCALE_ATTRIBUTE);
+ }
+
+ // Helper method to get the version String
+ public String getVersion() {
+ return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_VERSION_ATTRIBUTE);
+ }
+
+ // Helper method to get the dictionary ID as a String
+ public String getId() {
+ return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_ID_ATTRIBUTE);
+ }
+
+ // Helper method to get the description
+ public String getDescription() {
+ // TODO: Right now each dictionary file comes with a description in its own language.
+ // It will display as is no matter the device's locale. It should be internationalized.
+ return mDictionaryOptions.mAttributes.get(FileHeader.DICTIONARY_DESCRIPTION_ATTRIBUTE);
+ }
}
private FormatSpec() {
diff --git a/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java b/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java
index 3193ef457..5c805598a 100644
--- a/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java
+++ b/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java
@@ -1,26 +1,28 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.latin.Constants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
@@ -28,6 +30,7 @@ import java.util.LinkedList;
/**
* A dictionary that can fusion heads and tails of words for more compression.
*/
+@UsedForTesting
public final class FusionDictionary implements Iterable<Word> {
private static final boolean DBG = MakedictLog.DBG;
@@ -141,6 +144,33 @@ public final class FusionDictionary implements Iterable<Word> {
return NOT_A_TERMINAL != mFrequency;
}
+ public int getFrequency() {
+ return mFrequency;
+ }
+
+ public boolean getIsNotAWord() {
+ return mIsNotAWord;
+ }
+
+ public boolean getIsBlacklistEntry() {
+ return mIsBlacklistEntry;
+ }
+
+ public ArrayList<WeightedString> getShortcutTargets() {
+ // We don't want write permission to escape outside the package, so we return a copy
+ if (null == mShortcutTargets) return null;
+ final ArrayList<WeightedString> copyOfShortcutTargets =
+ new ArrayList<WeightedString>(mShortcutTargets);
+ return copyOfShortcutTargets;
+ }
+
+ public ArrayList<WeightedString> getBigrams() {
+ // We don't want write permission to escape outside the package, so we return a copy
+ if (null == mBigrams) return null;
+ final ArrayList<WeightedString> copyOfBigrams = new ArrayList<WeightedString>(mBigrams);
+ return copyOfBigrams;
+ }
+
public boolean hasSeveralChars() {
assert(mChars.length > 0);
return 1 < mChars.length;
@@ -249,8 +279,6 @@ public final class FusionDictionary implements Iterable<Word> {
/**
* Options global to the dictionary.
- *
- * There are no options at the moment, so this class is empty.
*/
public static final class DictionaryOptions {
public final boolean mGermanUmlautProcessing;
@@ -262,6 +290,43 @@ public final class FusionDictionary implements Iterable<Word> {
mGermanUmlautProcessing = germanUmlautProcessing;
mFrenchLigatureProcessing = frenchLigatureProcessing;
}
+ @Override
+ public String toString() { // Convenience method
+ return toString(0, false);
+ }
+ public String toString(final int indentCount, final boolean plumbing) {
+ final StringBuilder indent = new StringBuilder();
+ if (plumbing) {
+ indent.append("H:");
+ } else {
+ for (int i = 0; i < indentCount; ++i) {
+ indent.append(" ");
+ }
+ }
+ final StringBuilder s = new StringBuilder();
+ for (final String optionKey : mAttributes.keySet()) {
+ s.append(indent);
+ s.append(optionKey);
+ s.append(" = ");
+ if ("date".equals(optionKey) && !plumbing) {
+ // Date needs a number of milliseconds, but the dictionary contains seconds
+ s.append(new Date(
+ 1000 * Long.parseLong(mAttributes.get(optionKey))).toString());
+ } else {
+ s.append(mAttributes.get(optionKey));
+ }
+ s.append("\n");
+ }
+ if (mGermanUmlautProcessing) {
+ s.append(indent);
+ s.append("Needs German umlaut processing\n");
+ }
+ if (mFrenchLigatureProcessing) {
+ s.append(indent);
+ s.append("Needs French ligature processing\n");
+ }
+ return s.toString();
+ }
}
public final DictionaryOptions mOptions;
@@ -279,7 +344,7 @@ public final class FusionDictionary implements Iterable<Word> {
/**
* Helper method to convert a String to an int array.
*/
- static private int[] getCodePoints(final String word) {
+ static int[] getCodePoints(final String word) {
// TODO: this is a copy-paste of the contents of StringUtils.toCodePointArray,
// which is not visible from the makedict package. Factor this code.
final char[] characters = word.toCharArray();
@@ -358,6 +423,10 @@ public final class FusionDictionary implements Iterable<Word> {
if (charGroup2 == null) {
add(getCodePoints(word2), 0, null, false /* isNotAWord */,
false /* isBlacklistEntry */);
+ // The chargroup for the first word may have moved by the above insertion,
+ // if word1 and word2 share a common stem that happens not to have been
+ // a cutting point until now. In this case, we need to refresh charGroup.
+ charGroup = findWordInTree(mRoot, word1);
}
charGroup.addBigram(word2, frequency);
} else {
@@ -417,7 +486,7 @@ public final class FusionDictionary implements Iterable<Word> {
if (differentCharIndex == currentGroup.mChars.length) {
if (charIndex + differentCharIndex >= word.length) {
// The new word is a prefix of an existing word, but the node on which it
- // should end already exists as is. Since the old CharNode was not a terminal,
+ // should end already exists as is. Since the old CharNode was not a terminal,
// make it one by filling in its frequency and other attributes
currentGroup.update(frequency, shortcutTargets, null, isNotAWord,
isBlacklistEntry);
@@ -459,7 +528,7 @@ public final class FusionDictionary implements Iterable<Word> {
} else {
newParent = new CharGroup(
Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
- null /* shortcutTargets */, null /* bigrams */, -1,
+ null /* shortcutTargets */, null /* bigrams */, -1,
false /* isNotAWord */, false /* isBlacklistEntry */, newChildren);
final CharGroup newWord = new CharGroup(Arrays.copyOfRange(word,
charIndex + differentCharIndex, word.length),
@@ -550,6 +619,7 @@ public final class FusionDictionary implements Iterable<Word> {
/**
* Helper method to find a word in a given branch.
*/
+ @SuppressWarnings("unused")
public static CharGroup findWordInTree(Node node, final String s) {
int index = 0;
final StringBuilder checker = DBG ? new StringBuilder() : null;
diff --git a/java/src/com/android/inputmethod/latin/makedict/MakedictLog.java b/java/src/com/android/inputmethod/latin/makedict/MakedictLog.java
index 6c6b00b6a..cf07209d9 100644
--- a/java/src/com/android/inputmethod/latin/makedict/MakedictLog.java
+++ b/java/src/com/android/inputmethod/latin/makedict/MakedictLog.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
diff --git a/java/src/com/android/inputmethod/latin/makedict/PendingAttribute.java b/java/src/com/android/inputmethod/latin/makedict/PendingAttribute.java
index 5bb24da74..70e24cc98 100644
--- a/java/src/com/android/inputmethod/latin/makedict/PendingAttribute.java
+++ b/java/src/com/android/inputmethod/latin/makedict/PendingAttribute.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
diff --git a/java/src/com/android/inputmethod/latin/makedict/UnsupportedFormatException.java b/java/src/com/android/inputmethod/latin/makedict/UnsupportedFormatException.java
index dbb2ea870..4f3861526 100644
--- a/java/src/com/android/inputmethod/latin/makedict/UnsupportedFormatException.java
+++ b/java/src/com/android/inputmethod/latin/makedict/UnsupportedFormatException.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
diff --git a/java/src/com/android/inputmethod/latin/makedict/Word.java b/java/src/com/android/inputmethod/latin/makedict/Word.java
index 4c4f18f1a..0eabb7bf3 100644
--- a/java/src/com/android/inputmethod/latin/makedict/Word.java
+++ b/java/src/com/android/inputmethod/latin/makedict/Word.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.makedict;
diff --git a/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java b/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java
new file mode 100644
index 000000000..1b893a65d
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2013 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.setup;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
+import android.os.Process;
+import android.preference.PreferenceManager;
+import android.util.Log;
+
+import com.android.inputmethod.compat.IntentCompatUtils;
+import com.android.inputmethod.latin.RichInputMethodManager;
+import com.android.inputmethod.latin.Settings;
+
+/**
+ * This class detects the {@link Intent#ACTION_MY_PACKAGE_REPLACED} broadcast intent when this IME
+ * package has been replaced by a newer version of the same package. This class also detects
+ * {@link Intent#ACTION_BOOT_COMPLETED} and {@link Intent#ACTION_USER_INITIALIZE} broadcast intent.
+ *
+ * If this IME has already been installed in the system image and a new version of this IME has
+ * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received by this receiver and it
+ * will hide the setup wizard's icon.
+ *
+ * If this IME has already been installed in the data partition and a new version of this IME has
+ * been installed, {@link Intent#ACTION_MY_PACKAGE_REPLACED} is received by this receiver but it
+ * will not hide the setup wizard's icon, and the icon will appear on the launcher.
+ *
+ * If this IME hasn't been installed yet and has been newly installed, no
+ * {@link Intent#ACTION_MY_PACKAGE_REPLACED} will be sent and the setup wizard's icon will appear
+ * on the launcher.
+ *
+ * When the device has been booted, {@link Intent#ACTION_BOOT_COMPLETED} is received by this
+ * receiver and it checks whether the setup wizard's icon should be appeared or not on the launcher
+ * depending on which partition this IME is installed.
+ *
+ * When a multiuser account has been created, {@link Intent#ACTION_USER_INITIALIZE} is received
+ * by this receiver and it checks the whether the setup wizard's icon should be appeared or not on
+ * the launcher depending on which partition this IME is installed.
+ */
+public final class LauncherIconVisibilityManager extends BroadcastReceiver {
+ private static final String TAG = LauncherIconVisibilityManager.class.getSimpleName();
+
+ @Override
+ public void onReceive(final Context context, final Intent intent) {
+ if (shouldHandleThisIntent(intent, context)) {
+ updateSetupWizardIconVisibility(context);
+ }
+
+ // The process that hosts this broadcast receiver is invoked and remains alive even after
+ // 1) the package has been re-installed, 2) the device has been booted,
+ // 3) a multiuser has been created.
+ // There is no good reason to keep the process alive if this IME isn't a current IME.
+ RichInputMethodManager.init(context);
+ if (!SetupActivity.isThisImeCurrent(context)) {
+ final int myPid = Process.myPid();
+ Log.i(TAG, "Killing my process: pid=" + myPid);
+ Process.killProcess(myPid);
+ }
+ }
+
+ private static boolean shouldHandleThisIntent(final Intent intent, final Context context) {
+ final String action = intent.getAction();
+ if (Intent.ACTION_MY_PACKAGE_REPLACED.equals(action)) {
+ Log.i(TAG, "Package has been replaced: " + context.getPackageName());
+ return true;
+ } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
+ Log.i(TAG, "Boot has been completed");
+ return true;
+ } else if (IntentCompatUtils.has_ACTION_USER_INITIALIZE(intent)) {
+ Log.i(TAG, "User initialize");
+ return true;
+ }
+ return false;
+ }
+
+ public static void updateSetupWizardIconVisibility(final Context context) {
+ final ComponentName setupWizardActivity = new ComponentName(context, SetupActivity.class);
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ final boolean stateHasSet;
+ if (Settings.readShowSetupWizardIcon(prefs, context)) {
+ stateHasSet = setActivityState(context, setupWizardActivity,
+ PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
+ Log.i(TAG, (stateHasSet ? "Enable activity: " : "Activity has already been enabled: ")
+ + setupWizardActivity);
+ } else {
+ stateHasSet = setActivityState(context, setupWizardActivity,
+ PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
+ Log.i(TAG, (stateHasSet ? "Disable activity: " : "Activity has already been disabled: ")
+ + setupWizardActivity);
+ }
+ }
+
+ private static boolean setActivityState(final Context context,
+ final ComponentName activityComponent, final int activityState) {
+ final PackageManager pm = context.getPackageManager();
+ final int activityComponentState = pm.getComponentEnabledSetting(activityComponent);
+ if (activityComponentState == activityState) {
+ return false;
+ }
+ pm.setComponentEnabledSetting(
+ activityComponent, activityState, PackageManager.DONT_KILL_APP);
+ return true;
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java
new file mode 100644
index 000000000..e009fbc39
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java
@@ -0,0 +1,357 @@
+/*
+ * Copyright (C) 2013 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.setup;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.graphics.PorterDuff;
+import android.graphics.drawable.Drawable;
+import android.os.Bundle;
+import android.os.Message;
+import android.provider.Settings;
+import android.view.View;
+import android.view.inputmethod.InputMethodInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.TextView;
+
+import com.android.inputmethod.compat.TextViewCompatUtils;
+import com.android.inputmethod.compat.ViewCompatUtils;
+import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.RichInputMethodManager;
+import com.android.inputmethod.latin.SettingsActivity;
+import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
+
+import java.util.HashMap;
+
+public final class SetupActivity extends Activity {
+ private SetupStepIndicatorView mStepIndicatorView;
+ private final SetupStepGroup mSetupSteps = new SetupStepGroup();
+ private static final String STATE_STEP = "step";
+ private int mStepNumber;
+ private static final int STEP_1 = 1;
+ private static final int STEP_2 = 2;
+ private static final int STEP_3 = 3;
+
+ private final SettingsPoolingHandler mHandler = new SettingsPoolingHandler(this);
+
+ static final class SettingsPoolingHandler extends StaticInnerHandlerWrapper<SetupActivity> {
+ private static final int MSG_POLLING_IME_SETTINGS = 0;
+ private static final long IME_SETTINGS_POLLING_INTERVAL = 200;
+
+ public SettingsPoolingHandler(final SetupActivity outerInstance) {
+ super(outerInstance);
+ }
+
+ @Override
+ public void handleMessage(final Message msg) {
+ final SetupActivity setupActivity = getOuterInstance();
+ switch (msg.what) {
+ case MSG_POLLING_IME_SETTINGS:
+ if (SetupActivity.isThisImeEnabled(setupActivity)) {
+ setupActivity.invokeSetupWizardOfThisIme();
+ return;
+ }
+ startPollingImeSettings();
+ break;
+ }
+ }
+
+ public void startPollingImeSettings() {
+ sendMessageDelayed(obtainMessage(MSG_POLLING_IME_SETTINGS),
+ IME_SETTINGS_POLLING_INTERVAL);
+ }
+
+ public void cancelPollingImeSettings() {
+ removeMessages(MSG_POLLING_IME_SETTINGS);
+ }
+ }
+
+ @Override
+ protected void onCreate(final Bundle savedInstanceState) {
+ setTheme(android.R.style.Theme_DeviceDefault_Light_NoActionBar);
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.setup_wizard);
+
+ RichInputMethodManager.init(this);
+
+ if (savedInstanceState == null) {
+ mStepNumber = determineSetupStepNumber();
+ } else {
+ mStepNumber = savedInstanceState.getInt(STATE_STEP);
+ }
+
+ if (mStepNumber == STEP_3) {
+ // This IME already has been enabled and set as current IME.
+ // TODO: Implement tutorial.
+ invokeSettingsOfThisIme();
+ finish();
+ return;
+ }
+
+ // TODO: Use sans-serif-thin font family depending on the system locale white list and
+ // the SDK version.
+ final TextView titleView = (TextView)findViewById(R.id.setup_title);
+ titleView.setText(getString(R.string.setup_title, getString(R.string.english_ime_name)));
+
+ mStepIndicatorView = (SetupStepIndicatorView)findViewById(R.id.setup_step_indicator);
+
+ final SetupStep step1 = new SetupStep(findViewById(R.id.setup_step1),
+ R.string.setup_step1_title, R.string.setup_step1_instruction,
+ R.drawable.ic_settings_language, R.string.language_settings);
+ step1.setAction(new Runnable() {
+ @Override
+ public void run() {
+ invokeLanguageAndInputSettings();
+ mHandler.startPollingImeSettings();
+ }
+ });
+ mSetupSteps.addStep(STEP_1, step1);
+
+ final SetupStep step2 = new SetupStep(findViewById(R.id.setup_step2),
+ R.string.setup_step2_title, R.string.setup_step2_instruction,
+ 0 /* actionIcon */, R.string.select_input_method);
+ step2.setAction(new Runnable() {
+ @Override
+ public void run() {
+ // Invoke input method picker.
+ RichInputMethodManager.getInstance().getInputMethodManager()
+ .showInputMethodPicker();
+ }
+ });
+ mSetupSteps.addStep(STEP_2, step2);
+
+ final SetupStep step3 = new SetupStep(findViewById(R.id.setup_step3),
+ R.string.setup_step3_title, 0 /* instruction */,
+ R.drawable.sym_keyboard_language_switch, R.string.setup_step3_instruction);
+ step3.setAction(new Runnable() {
+ @Override
+ public void run() {
+ invokeSubtypeEnablerOfThisIme();
+ }
+ });
+ mSetupSteps.addStep(STEP_3, step3);
+ }
+
+ private void invokeSetupWizardOfThisIme() {
+ final Intent intent = new Intent();
+ intent.setClass(this, SetupActivity.class);
+ intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
+ | Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ startActivity(intent);
+ }
+
+ private void invokeSettingsOfThisIme() {
+ final Intent intent = new Intent();
+ intent.setClass(this, SettingsActivity.class);
+ intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
+ | Intent.FLAG_ACTIVITY_CLEAR_TOP);
+ startActivity(intent);
+ }
+
+ private void invokeLanguageAndInputSettings() {
+ final Intent intent = new Intent();
+ intent.setAction(Settings.ACTION_INPUT_METHOD_SETTINGS);
+ intent.addCategory(Intent.CATEGORY_DEFAULT);
+ startActivity(intent);
+ }
+
+ private void invokeSubtypeEnablerOfThisIme() {
+ final InputMethodInfo imi =
+ RichInputMethodManager.getInstance().getInputMethodInfoOfThisIme();
+ final Intent intent = new Intent();
+ intent.setAction(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS);
+ intent.addCategory(Intent.CATEGORY_DEFAULT);
+ intent.putExtra(Settings.EXTRA_INPUT_METHOD_ID, imi.getId());
+ startActivity(intent);
+ }
+
+ /**
+ * Check if the IME specified by the context is enabled.
+ * Note that {@link RichInputMethodManager} must have been initialized before calling this
+ * method.
+ *
+ * @param context package context of the IME to be checked.
+ * @return true if this IME is enabled.
+ */
+ public static boolean isThisImeEnabled(final Context context) {
+ final String packageName = context.getPackageName();
+ final InputMethodManager imm = RichInputMethodManager.getInstance().getInputMethodManager();
+ for (final InputMethodInfo imi : imm.getEnabledInputMethodList()) {
+ if (packageName.equals(imi.getPackageName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Check if the IME specified by the context is the current IME.
+ * Note that {@link RichInputMethodManager} must have been initialized before calling this
+ * method.
+ *
+ * @param context package context of the IME to be checked.
+ * @return true if this IME is the current IME.
+ */
+ public static boolean isThisImeCurrent(final Context context) {
+ final InputMethodInfo myImi =
+ RichInputMethodManager.getInstance().getInputMethodInfoOfThisIme();
+ final String currentImeId = Settings.Secure.getString(
+ context.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
+ return myImi.getId().equals(currentImeId);
+ }
+
+ private int determineSetupStepNumber() {
+ mHandler.cancelPollingImeSettings();
+ if (!isThisImeEnabled(this)) {
+ return STEP_1;
+ }
+ if (!isThisImeCurrent(this)) {
+ return STEP_2;
+ }
+ return STEP_3;
+ }
+
+ @Override
+ protected void onSaveInstanceState(final Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putInt(STATE_STEP, mStepNumber);
+ }
+
+ @Override
+ protected void onRestoreInstanceState(final Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+ mStepNumber = savedInstanceState.getInt(STATE_STEP);
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ mStepNumber = determineSetupStepNumber();
+ }
+
+ @Override
+ protected void onRestart() {
+ super.onRestart();
+ mStepNumber = determineSetupStepNumber();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ updateSetupStepView();
+ }
+
+ @Override
+ public void onWindowFocusChanged(final boolean hasFocus) {
+ super.onWindowFocusChanged(hasFocus);
+ if (!hasFocus) {
+ return;
+ }
+ mStepNumber = determineSetupStepNumber();
+ updateSetupStepView();
+ }
+
+ private void updateSetupStepView() {
+ final int layoutDirection = ViewCompatUtils.getLayoutDirection(mStepIndicatorView);
+ mStepIndicatorView.setIndicatorPosition(
+ getIndicatorPosition(mStepNumber, mSetupSteps.getTotalStep(), layoutDirection));
+ mSetupSteps.enableStep(mStepNumber);
+ }
+
+ private static float getIndicatorPosition(final int step, final int totalStep,
+ final int layoutDirection) {
+ final float pos = ((step - STEP_1) * 2 + 1) / (float)(totalStep * 2);
+ return (layoutDirection == ViewCompatUtils.LAYOUT_DIRECTION_RTL) ? 1.0f - pos : pos;
+ }
+
+ static final class SetupStep implements View.OnClickListener {
+ private final View mRootView;
+ private final TextView mActionLabel;
+ private Runnable mAction;
+
+ public SetupStep(final View rootView, final int title, final int instruction,
+ final int actionIcon, final int actionLabel) {
+ mRootView = rootView;
+ final Resources res = rootView.getResources();
+ final String applicationName = res.getString(R.string.english_ime_name);
+
+ final TextView titleView = (TextView)rootView.findViewById(R.id.setup_step_title);
+ titleView.setText(res.getString(title, applicationName));
+
+ final TextView instructionView = (TextView)rootView.findViewById(
+ R.id.setup_step_instruction);
+ if (instruction == 0) {
+ instructionView.setVisibility(View.GONE);
+ } else {
+ instructionView.setText(res.getString(instruction, applicationName));
+ }
+
+ mActionLabel = (TextView)rootView.findViewById(R.id.setup_step_action_label);
+ mActionLabel.setText(res.getString(actionLabel));
+ if (actionIcon == 0) {
+ final int paddingEnd = ViewCompatUtils.getPaddingEnd(mActionLabel);
+ ViewCompatUtils.setPaddingRelative(mActionLabel, paddingEnd, 0, paddingEnd, 0);
+ } else {
+ final int overrideColor = res.getColor(R.color.setup_text_action);
+ final Drawable icon = res.getDrawable(actionIcon);
+ icon.setColorFilter(overrideColor, PorterDuff.Mode.MULTIPLY);
+ icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
+ TextViewCompatUtils.setCompoundDrawablesRelative(
+ mActionLabel, icon, null, null, null);
+ }
+ }
+
+ public void setEnabled(final boolean enabled) {
+ mRootView.setVisibility(enabled ? View.VISIBLE : View.GONE);
+ }
+
+ public void setAction(final Runnable action) {
+ mActionLabel.setOnClickListener(this);
+ mAction = action;
+ }
+
+ @Override
+ public void onClick(final View v) {
+ if (mAction != null) {
+ mAction.run();
+ }
+ }
+ }
+
+ static final class SetupStepGroup {
+ private final HashMap<Integer, SetupStep> mGroup = CollectionUtils.newHashMap();
+
+ public void addStep(final int stepNo, final SetupStep step) {
+ mGroup.put(stepNo, step);
+ }
+
+ public void enableStep(final int enableStepNo) {
+ for (final Integer stepNo : mGroup.keySet()) {
+ final SetupStep step = mGroup.get(stepNo);
+ step.setEnabled(stepNo == enableStepNo);
+ }
+ }
+
+ public int getTotalStep() {
+ return mGroup.size();
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/setup/SetupStepIndicatorView.java b/java/src/com/android/inputmethod/latin/setup/SetupStepIndicatorView.java
new file mode 100644
index 000000000..077a21793
--- /dev/null
+++ b/java/src/com/android/inputmethod/latin/setup/SetupStepIndicatorView.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2013 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.setup;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.util.AttributeSet;
+import android.view.View;
+
+import com.android.inputmethod.latin.R;
+
+public final class SetupStepIndicatorView extends View {
+ private final Path mIndicatorPath = new Path();
+ private final Paint mIndicatorPaint = new Paint();
+ private float mXRatio;
+
+ public SetupStepIndicatorView(final Context context, final AttributeSet attrs) {
+ super(context, attrs);
+ mIndicatorPaint.setColor(getResources().getColor(R.color.setup_step_background));
+ mIndicatorPaint.setStyle(Paint.Style.FILL);
+ }
+
+ public void setIndicatorPosition(final float xRatio) {
+ mXRatio = xRatio;
+ invalidate();
+ }
+
+ @Override
+ protected void onDraw(final Canvas canvas) {
+ super.onDraw(canvas);
+ final int xPos = (int)(getWidth() * mXRatio);
+ final int height = getHeight();
+ mIndicatorPath.rewind();
+ mIndicatorPath.moveTo(xPos, 0);
+ mIndicatorPath.lineTo(xPos + height, height);
+ mIndicatorPath.lineTo(xPos - height, height);
+ mIndicatorPath.close();
+ canvas.drawPath(mIndicatorPath, mIndicatorPaint);
+ }
+}
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java
index 5a11ae534..38a26486d 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.spellcheck;
@@ -81,6 +81,7 @@ public final class AndroidSpellCheckerService extends SpellCheckerService
public static final int SCRIPT_LATIN = 0;
public static final int SCRIPT_CYRILLIC = 1;
+ public static final int SCRIPT_GREEK = 2;
public static final String SINGLE_QUOTE = "\u0027";
public static final String APOSTROPHE = "\u2019";
private static final TreeMap<String, Integer> mLanguageToScript;
@@ -94,18 +95,23 @@ public final class AndroidSpellCheckerService extends SpellCheckerService
// IMPORTANT: this only contains languages - do not write countries in there.
// Only the language is searched from the map.
mLanguageToScript = CollectionUtils.newTreeMap();
- mLanguageToScript.put("en", SCRIPT_LATIN);
- mLanguageToScript.put("fr", SCRIPT_LATIN);
- mLanguageToScript.put("de", SCRIPT_LATIN);
- mLanguageToScript.put("nl", SCRIPT_LATIN);
mLanguageToScript.put("cs", SCRIPT_LATIN);
+ mLanguageToScript.put("da", SCRIPT_LATIN);
+ mLanguageToScript.put("de", SCRIPT_LATIN);
+ mLanguageToScript.put("el", SCRIPT_GREEK);
+ mLanguageToScript.put("en", SCRIPT_LATIN);
mLanguageToScript.put("es", SCRIPT_LATIN);
- mLanguageToScript.put("it", SCRIPT_LATIN);
+ mLanguageToScript.put("fi", SCRIPT_LATIN);
+ mLanguageToScript.put("fr", SCRIPT_LATIN);
mLanguageToScript.put("hr", SCRIPT_LATIN);
+ mLanguageToScript.put("it", SCRIPT_LATIN);
+ mLanguageToScript.put("lt", SCRIPT_LATIN);
+ mLanguageToScript.put("lv", SCRIPT_LATIN);
+ mLanguageToScript.put("nb", SCRIPT_LATIN);
+ mLanguageToScript.put("nl", SCRIPT_LATIN);
mLanguageToScript.put("pt", SCRIPT_LATIN);
+ mLanguageToScript.put("sl", SCRIPT_LATIN);
mLanguageToScript.put("ru", SCRIPT_CYRILLIC);
- // TODO: Make a persian proximity, and activate the Farsi subtype.
- // mLanguageToScript.put("fa", SCRIPT_PERSIAN);
}
@Override public void onCreate() {
@@ -212,7 +218,7 @@ public final class AndroidSpellCheckerService extends SpellCheckerService
}
}
- private final ArrayList<CharSequence> mSuggestions;
+ private final ArrayList<String> mSuggestions;
private final int[] mScores;
private final String mOriginalText;
private final float mSuggestionThreshold;
@@ -294,6 +300,8 @@ public final class AndroidSpellCheckerService extends SpellCheckerService
final String[] gatheredSuggestions;
final boolean hasRecommendedSuggestions;
if (0 == mLength) {
+ // TODO: the comment below describes what is intended, but in the practice
+ // mBestSuggestion is only ever set to null so it doesn't work. Fix this.
// Either we found no suggestions, or we found some BUT the max length was 0.
// If we found some mBestSuggestion will not be null. If it is null, then
// we found none, regardless of the max length.
@@ -335,7 +343,7 @@ public final class AndroidSpellCheckerService extends SpellCheckerService
gatheredSuggestions = mSuggestions.toArray(EMPTY_STRING_ARRAY);
final int bestScore = mScores[mLength - 1];
- final CharSequence bestSuggestion = mSuggestions.get(0);
+ final String bestSuggestion = mSuggestions.get(0);
final float normalizedScore =
BinaryDictionary.calcNormalizedScore(
mOriginalText, bestSuggestion.toString(), bestScore);
@@ -438,15 +446,23 @@ public final class AndroidSpellCheckerService extends SpellCheckerService
if (!Character.isUpperCase(text.codePointAt(0))) return CAPITALIZE_NONE;
final int len = text.length();
int capsCount = 1;
+ int letterCount = 1;
for (int i = 1; i < len; i = text.offsetByCodePoints(i, 1)) {
- if (1 != capsCount && i != capsCount) break;
- if (Character.isUpperCase(text.codePointAt(i))) ++capsCount;
+ if (1 != capsCount && letterCount != capsCount) break;
+ final int codePoint = text.codePointAt(i);
+ if (Character.isUpperCase(codePoint)) {
+ ++capsCount;
+ ++letterCount;
+ } else if (Character.isLetter(codePoint)) {
+ // We need to discount non-letters since they may not be upper-case, but may
+ // still be part of a word (e.g. single quote or dash, as in "IT'S" or "FULL-TIME")
+ ++letterCount;
+ }
}
- // We know the first char is upper case. So we want to test if either everything
- // else is lower case, or if everything else is upper case. If the string is
- // exactly one char long, then we will arrive here with capsCount 1, and this is
- // correct, too.
+ // We know the first char is upper case. So we want to test if either every letter other
+ // than the first is lower case, or if they are all upper case. If the string is exactly
+ // one char long, then we will arrive here with letterCount 1, and this is correct, too.
if (1 == capsCount) return CAPITALIZE_FIRST;
- return (len == capsCount ? CAPITALIZE_ALL : CAPITALIZE_NONE);
+ return (letterCount == capsCount ? CAPITALIZE_ALL : CAPITALIZE_NONE);
}
}
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java
index 668e7a641..63f46b79e 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.spellcheck;
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSessionFactory.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSessionFactory.java
index 8eb1eb68e..e0418d404 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSessionFactory.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSessionFactory.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.spellcheck;
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java
index 53ed4d3c3..cd3f9e442 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.spellcheck;
@@ -28,9 +28,11 @@ import android.view.textservice.TextInfo;
import com.android.inputmethod.compat.SuggestionsInfoCompatUtils;
import com.android.inputmethod.latin.Constants;
+import com.android.inputmethod.latin.Dictionary;
import com.android.inputmethod.latin.LocaleUtils;
-import com.android.inputmethod.latin.WordComposer;
+import com.android.inputmethod.latin.StringUtils;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
+import com.android.inputmethod.latin.WordComposer;
import com.android.inputmethod.latin.spellcheck.AndroidSpellCheckerService.SuggestionsGatherer;
import java.util.ArrayList;
@@ -141,8 +143,17 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session {
case AndroidSpellCheckerService.SCRIPT_CYRILLIC:
// All Cyrillic characters are in the 400~52F block. There are some in the upper
// Unicode range, but they are archaic characters that are not used in modern
- // russian and are not used by our dictionary.
+ // Russian and are not used by our dictionary.
return codePoint >= 0x400 && codePoint <= 0x52F && Character.isLetter(codePoint);
+ case AndroidSpellCheckerService.SCRIPT_GREEK:
+ // Greek letters are either in the 370~3FF range (Greek & Coptic), or in the
+ // 1F00~1FFF range (Greek extended). Our dictionary contains both sort of characters.
+ // Our dictionary also contains a few words with 0xF2; it would be best to check
+ // if that's correct, but a Google search does return results for these words so
+ // they are probably okay.
+ return (codePoint >= 0x370 && codePoint <= 0x3FF)
+ || (codePoint >= 0x1F00 && codePoint <= 0x1FFF)
+ || codePoint == 0xF2;
default:
// Should never come here
throw new RuntimeException("Impossible value of script: " + script);
@@ -188,6 +199,35 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session {
return (letterCount * 4 < length * 3);
}
+ /**
+ * Helper method to test valid capitalizations of a word.
+ *
+ * If the "text" is lower-case, we test only the exact string.
+ * If the "Text" is capitalized, we test the exact string "Text" and the lower-cased
+ * version of it "text".
+ * If the "TEXT" is fully upper case, we test the exact string "TEXT", the lower-cased
+ * version of it "text" and the capitalized version of it "Text".
+ */
+ private boolean isInDictForAnyCapitalization(final Dictionary dict, final String text,
+ final int capitalizeType) {
+ // If the word is in there as is, then it's in the dictionary. If not, we'll test lower
+ // case versions, but only if the word is not already all-lower case or mixed case.
+ if (dict.isValidWord(text)) return true;
+ if (AndroidSpellCheckerService.CAPITALIZE_NONE == capitalizeType) return false;
+
+ // If we come here, we have a capitalized word (either First- or All-).
+ // Downcase the word and look it up again. If the word is only capitalized, we
+ // tested all possibilities, so if it's still negative we can return false.
+ final String lowerCaseText = text.toLowerCase(mLocale);
+ if (dict.isValidWord(lowerCaseText)) return true;
+ if (AndroidSpellCheckerService.CAPITALIZE_FIRST == capitalizeType) return false;
+
+ // If the lower case version is not in the dictionary, it's still possible
+ // that we have an all-caps version of a word that needs to be capitalized
+ // according to the dictionary. E.g. "GERMANS" only exists in the dictionary as "Germans".
+ return dict.isValidWord(StringUtils.toTitleCase(lowerCaseText, mLocale));
+ }
+
// Note : this must be reentrant
/**
* Gets a list of suggestions for a specific string. This returns a list of possible
@@ -268,17 +308,11 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session {
dictInfo.mDictionary.getSuggestions(composer, prevWord,
dictInfo.mProximityInfo);
for (final SuggestedWordInfo suggestion : suggestions) {
- final String suggestionStr = suggestion.mWord.toString();
+ final String suggestionStr = suggestion.mWord;
suggestionsGatherer.addWord(suggestionStr.toCharArray(), null, 0,
suggestionStr.length(), suggestion.mScore);
}
- isInDict = dictInfo.mDictionary.isValidWord(text);
- if (!isInDict && AndroidSpellCheckerService.CAPITALIZE_NONE != capitalizeType) {
- // We want to test the word again if it's all caps or first caps only.
- // If it's fully down, we already tested it, if it's mixed case, we don't
- // want to test a lowercase version of it.
- isInDict = dictInfo.mDictionary.isValidWord(text.toLowerCase(mLocale));
- }
+ isInDict = isInDictForAnyCapitalization(dictInfo.mDictionary, text, capitalizeType);
} finally {
if (null != dictInfo) {
if (!mDictionaryPool.offer(dictInfo)) {
@@ -318,7 +352,7 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session {
if (DBG) {
throw e;
} else {
- Log.e(TAG, "Exception while spellcheking: " + e);
+ Log.e(TAG, "Exception while spellcheking", e);
return AndroidSpellCheckerService.getNotInDictEmptySuggestions();
}
}
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/DictAndProximity.java b/java/src/com/android/inputmethod/latin/spellcheck/DictAndProximity.java
index 9d7c61a33..017a4f555 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/DictAndProximity.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/DictAndProximity.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.spellcheck;
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java b/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java
index 1fb2bbb6a..81dd92d9e 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.spellcheck;
@@ -51,11 +51,11 @@ public final class DictionaryPool extends LinkedBlockingQueue<DictAndProximity>
new Dictionary(Dictionary.TYPE_MAIN) {
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
- final CharSequence prevWord, final ProximityInfo proximityInfo) {
+ final String prevWord, final ProximityInfo proximityInfo) {
return noSuggestions;
}
@Override
- public boolean isValidWord(CharSequence word) {
+ public boolean isValidWord(final String word) {
// This is never called. However if for some strange reason it ever gets
// called, returning true is less destructive (it will not underline the
// word in red).
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerProximityInfo.java b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerProximityInfo.java
index 11bb97031..49dca21e6 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerProximityInfo.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerProximityInfo.java
@@ -1,21 +1,22 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.spellcheck;
+import com.android.inputmethod.annotations.UsedForTesting;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.Constants;
@@ -23,7 +24,7 @@ import com.android.inputmethod.latin.Constants;
import java.util.TreeMap;
public final class SpellCheckerProximityInfo {
- /* public for test */
+ @UsedForTesting
final public static int NUL = Constants.NOT_A_CODE;
// This must be the same as MAX_PROXIMITY_CHARS_SIZE else it will not work inside
@@ -72,6 +73,12 @@ public final class SpellCheckerProximityInfo {
// to spell check has been entered with one of the keyboards above. Also, specifically
// to English, many spelling errors consist of the last vowel of the word being wrong
// because in English vowels tend to merge with each other in pronunciation.
+ /*
+ The Qwerty layout this represents looks like the following:
+ q w e r t y u i o p
+ a s d f g h j k l
+ z x c v b n m
+ */
final static int[] PROXIMITY = {
// Proximity for row 1. This must have exactly ROW_SIZE entries for each letter,
// and exactly PROXIMITY_GRID_WIDTH letters for a row. Pad with NUL's.
@@ -126,10 +133,13 @@ public final class SpellCheckerProximityInfo {
final private static TreeMap<Integer, Integer> INDICES = CollectionUtils.newTreeMap();
// TODO: The following table is solely based on the keyboard layout. Consult with Russian
// speakers on commonly misspelled words/letters.
- final static int[] PROXIMITY = {
- // Proximity for row 1. This must have exactly ROW_SIZE entries for each letter,
- // and exactly PROXIMITY_GRID_WIDTH letters for a row. Pad with NUL's.
- // The number of rows must be exactly PROXIMITY_GRID_HEIGHT.
+ /*
+ The Russian layout this represents looks like the following:
+ й ц у к е н г ш щ з х
+ ф ы в а п р о л д ж э
+ я ч с м и т ь б ю
+
+ This gives us the following table:
'й', 'ц', 'ф', 'ы', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'ц', 'й', 'ф', 'ы', 'в', 'у', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'у', 'ц', 'ы', 'в', 'а', 'к', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
@@ -142,7 +152,6 @@ public final class SpellCheckerProximityInfo {
'з', 'щ', 'д', 'ж', 'э', 'х', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'х', 'з', 'ж', 'э', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
- // Proximity for row 2. See comment above about size.
'ф', 'й', 'ц', 'ы', 'я', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'ы', 'й', 'ц', 'у', 'ф', 'в', 'я', 'ч', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'в', 'ц', 'у', 'к', 'ы', 'а', 'я', 'ч', 'с', NUL, NUL, NUL, NUL, NUL, NUL, NUL,
@@ -155,7 +164,6 @@ public final class SpellCheckerProximityInfo {
'ж', 'щ', 'з', 'х', 'д', 'э', 'б', 'ю', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'э', 'з', 'х', 'ю', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
- // Proximity for row 3. See comment above about size.
'я', 'ф', 'ы', 'в', 'ч', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'ч', 'ы', 'в', 'а', 'я', 'с', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'с', 'в', 'а', 'п', 'ч', 'м', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
@@ -165,6 +173,249 @@ public final class SpellCheckerProximityInfo {
'ь', 'о', 'л', 'д', 'т', 'б', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'б', 'л', 'д', 'ж', 'ь', 'ю', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
'ю', 'д', 'ж', 'э', 'б', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ Using the following characters:
+ */
+ private static final int CY_SHORT_I = '\u0439'; // й
+ private static final int CY_TSE = '\u0446'; // ц
+ private static final int CY_U = '\u0443'; // у
+ private static final int CY_KA = '\u043A'; // к
+ private static final int CY_IE = '\u0435'; // е
+ private static final int CY_EN = '\u043D'; // н
+ private static final int CY_GHE = '\u0433'; // г
+ private static final int CY_SHA = '\u0448'; // ш
+ private static final int CY_SHCHA = '\u0449'; // щ
+ private static final int CY_ZE = '\u0437'; // з
+ private static final int CY_HA = '\u0445'; // х
+ private static final int CY_EF = '\u0444'; // ф
+ private static final int CY_YERU = '\u044B'; // ы
+ private static final int CY_VE = '\u0432'; // в
+ private static final int CY_A = '\u0430'; // а
+ private static final int CY_PE = '\u043F'; // п
+ private static final int CY_ER = '\u0440'; // р
+ private static final int CY_O = '\u043E'; // о
+ private static final int CY_EL = '\u043B'; // л
+ private static final int CY_DE = '\u0434'; // д
+ private static final int CY_ZHE = '\u0436'; // ж
+ private static final int CY_E = '\u044D'; // э
+ private static final int CY_YA = '\u044F'; // я
+ private static final int CY_CHE = '\u0447'; // ч
+ private static final int CY_ES = '\u0441'; // с
+ private static final int CY_EM = '\u043C'; // м
+ private static final int CY_I = '\u0438'; // и
+ private static final int CY_TE = '\u0442'; // т
+ private static final int CY_SOFT_SIGN = '\u044C'; // ь
+ private static final int CY_BE = '\u0431'; // б
+ private static final int CY_YU = '\u044E'; // ю
+ final static int[] PROXIMITY = {
+ // Proximity for row 1. This must have exactly ROW_SIZE entries for each letter,
+ // and exactly PROXIMITY_GRID_WIDTH letters for a row. Pad with NUL's.
+ // The number of rows must be exactly PROXIMITY_GRID_HEIGHT.
+ CY_SHORT_I, CY_TSE, CY_EF, CY_YERU, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_TSE, CY_SHORT_I, CY_EF, CY_YERU, CY_VE, CY_U, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_U, CY_TSE, CY_YERU, CY_VE, CY_A, CY_KA, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_KA, CY_U, CY_VE, CY_A, CY_PE, CY_IE, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_IE, CY_KA, CY_A, CY_PE, CY_ER, CY_EN, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_EN, CY_IE, CY_PE, CY_ER, CY_O, CY_GHE, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_GHE, CY_EN, CY_ER, CY_O, CY_EL, CY_SHA, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_SHA, CY_GHE, CY_O, CY_EL, CY_DE, CY_SHCHA, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_SHCHA, CY_SHA, CY_EL, CY_DE, CY_ZHE, CY_ZE, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_ZE, CY_SHCHA, CY_DE, CY_ZHE, CY_E, CY_HA, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_HA, CY_ZE, CY_ZHE, CY_E, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ // Proximity for row 2. See comment above about size.
+ CY_EF, CY_SHORT_I, CY_TSE, CY_YERU, CY_YA, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_YERU, CY_SHORT_I, CY_TSE, CY_U, CY_EF, CY_VE, CY_YA, CY_CHE,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_VE, CY_TSE, CY_U, CY_KA, CY_YERU, CY_A, CY_YA, CY_CHE,
+ CY_ES, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_A, CY_U, CY_KA, CY_IE, CY_VE, CY_PE, CY_CHE, CY_ES,
+ CY_EM, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_PE, CY_KA, CY_IE, CY_EN, CY_A, CY_ER, CY_ES, CY_EM,
+ CY_I, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_ER, CY_IE, CY_EN, CY_GHE, CY_PE, CY_O, CY_EM, CY_I,
+ CY_TE, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_O, CY_EN, CY_GHE, CY_SHA, CY_ER, CY_EL, CY_I, CY_TE,
+ CY_SOFT_SIGN, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_EL, CY_GHE, CY_SHA, CY_SHCHA, CY_O, CY_DE, CY_TE, CY_SOFT_SIGN,
+ CY_BE, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_DE, CY_SHA, CY_SHCHA, CY_ZE, CY_EL, CY_ZHE, CY_SOFT_SIGN, CY_BE,
+ CY_YU, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_ZHE, CY_SHCHA, CY_ZE, CY_HA, CY_DE, CY_E, CY_BE, CY_YU,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_E, CY_ZE, CY_HA, CY_YU, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ // Proximity for row 3. See comment above about size.
+ CY_YA, CY_EF, CY_YERU, CY_VE, CY_CHE, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_CHE, CY_YERU, CY_VE, CY_A, CY_YA, CY_ES, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_ES, CY_VE, CY_A, CY_PE, CY_CHE, CY_EM, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_EM, CY_A, CY_PE, CY_ER, CY_ES, CY_I, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_I, CY_PE, CY_ER, CY_O, CY_EM, CY_TE, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_TE, CY_ER, CY_O, CY_EL, CY_I, CY_SOFT_SIGN, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_SOFT_SIGN, CY_O, CY_EL, CY_DE, CY_TE, CY_BE, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_BE, CY_EL, CY_DE, CY_ZHE, CY_SOFT_SIGN, CY_YU, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ CY_YU, CY_DE, CY_ZHE, CY_E, CY_BE, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ };
+ static {
+ buildProximityIndices(PROXIMITY, INDICES);
+ }
+ static int getIndexOf(int characterCode) {
+ return computeIndex(characterCode, INDICES);
+ }
+ }
+
+ private static final class Greek {
+ final private static TreeMap<Integer, Integer> INDICES = CollectionUtils.newTreeMap();
+ // TODO: The following table is solely based on the keyboard layout. Consult with Greek
+ // speakers on commonly misspelled words/letters.
+ /*
+ The Greek layout this represents looks like the following:
+ ; ς ε ρ τ υ θ ι ο π
+ α σ δ φ γ η ξ κ λ
+ ζ χ ψ ω β ν μ
+
+ This gives us the following table:
+ 'ς', 'ε', 'α', 'σ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ε', 'ς', 'ρ', 'σ', 'δ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ρ', 'ε', 'τ', 'δ', 'φ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'τ', 'ρ', 'υ', 'φ', 'γ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'υ', 'τ', 'θ', 'γ', 'η', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'θ', 'υ', 'ι', 'η', 'ξ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ι', 'θ', 'ο', 'ξ', 'κ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ο', 'ι', 'π', 'κ', 'λ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'π', 'ο', 'λ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ 'α', 'ς', 'σ', 'ζ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'σ', 'ς', 'ε', 'α', 'δ', 'ζ', 'χ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'δ', 'ε', 'ρ', 'σ', 'φ', 'ζ', 'χ', 'ψ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'φ', 'ρ', 'τ', 'δ', 'γ', 'χ', 'ψ', 'ω', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'γ', 'τ', 'υ', 'φ', 'η', 'ψ', 'ω', 'β', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'η', 'υ', 'θ', 'γ', 'ξ', 'ω', 'β', 'ν', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ξ', 'θ', 'ι', 'η', 'κ', 'β', 'ν', 'μ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'κ', 'ι', 'ο', 'ξ', 'λ', 'ν', 'μ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'λ', 'ο', 'π', 'κ', 'μ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ 'ζ', 'α', 'σ', 'δ', 'χ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'χ', 'σ', 'δ', 'φ', 'ζ', 'ψ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ψ', 'δ', 'φ', 'γ', 'χ', 'ω', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ω', 'φ', 'γ', 'η', 'ψ', 'β', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'β', 'γ', 'η', 'ξ', 'ω', 'ν', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'ν', 'η', 'ξ', 'κ', 'β', 'μ', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ 'μ', 'ξ', 'κ', 'λ', 'ν', NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ Using the following characters:
+ */
+ private static final int GR_FINAL_SIGMA = '\u03C2'; // ς
+ private static final int GR_EPSILON = '\u03B5'; // ε
+ private static final int GR_RHO = '\u03C1'; // ρ
+ private static final int GR_TAU = '\u03C4'; // τ
+ private static final int GR_UPSILON = '\u03C5'; // υ
+ private static final int GR_THETA = '\u03B8'; // θ
+ private static final int GR_IOTA = '\u03B9'; // ι
+ private static final int GR_OMICRON = '\u03BF'; // ο
+ private static final int GR_PI = '\u03C0'; // π
+ private static final int GR_ALPHA = '\u03B1'; // α
+ private static final int GR_SIGMA = '\u03C3'; // σ
+ private static final int GR_DELTA = '\u03B4'; // δ
+ private static final int GR_PHI = '\u03C6'; // φ
+ private static final int GR_GAMMA = '\u03B3'; // γ
+ private static final int GR_ETA = '\u03B7'; // η
+ private static final int GR_XI = '\u03BE'; // ξ
+ private static final int GR_KAPPA = '\u03BA'; // κ
+ private static final int GR_LAMDA = '\u03BB'; // λ
+ private static final int GR_ZETA = '\u03B6'; // ζ
+ private static final int GR_CHI = '\u03C7'; // χ
+ private static final int GR_PSI = '\u03C8'; // ψ
+ private static final int GR_OMEGA = '\u03C9'; // ω
+ private static final int GR_BETA = '\u03B2'; // β
+ private static final int GR_NU = '\u03BD'; // ν
+ private static final int GR_MU = '\u03BC'; // μ
+ final static int[] PROXIMITY = {
+ // Proximity for row 1. This must have exactly ROW_SIZE entries for each letter,
+ // and exactly PROXIMITY_GRID_WIDTH letters for a row. Pad with NUL's.
+ // The number of rows must be exactly PROXIMITY_GRID_HEIGHT.
+ GR_FINAL_SIGMA, GR_EPSILON, GR_ALPHA, GR_SIGMA, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_EPSILON, GR_FINAL_SIGMA, GR_RHO, GR_SIGMA, GR_DELTA, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_RHO, GR_EPSILON, GR_TAU, GR_DELTA, GR_PHI, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_TAU, GR_RHO, GR_UPSILON, GR_PHI, GR_GAMMA, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_UPSILON, GR_TAU, GR_THETA, GR_GAMMA, GR_ETA, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_THETA, GR_UPSILON, GR_IOTA, GR_ETA, GR_XI, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_IOTA, GR_THETA, GR_OMICRON, GR_XI, GR_KAPPA, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_OMICRON, GR_IOTA, GR_PI, GR_KAPPA, GR_LAMDA, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_PI, GR_OMICRON, GR_LAMDA, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ GR_ALPHA, GR_FINAL_SIGMA, GR_SIGMA, GR_ZETA, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_SIGMA, GR_FINAL_SIGMA, GR_EPSILON, GR_ALPHA, GR_DELTA, GR_ZETA, GR_CHI, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_DELTA, GR_EPSILON, GR_RHO, GR_SIGMA, GR_PHI, GR_ZETA, GR_CHI, GR_PSI,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_PHI, GR_RHO, GR_TAU, GR_DELTA, GR_GAMMA, GR_CHI, GR_PSI, GR_OMEGA,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_GAMMA, GR_TAU, GR_UPSILON, GR_PHI, GR_ETA, GR_PSI, GR_OMEGA, GR_BETA,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_ETA, GR_UPSILON, GR_THETA, GR_GAMMA, GR_XI, GR_OMEGA, GR_BETA, GR_NU,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_XI, GR_THETA, GR_IOTA, GR_ETA, GR_KAPPA, GR_BETA, GR_NU, GR_MU,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_KAPPA, GR_IOTA, GR_OMICRON, GR_XI, GR_LAMDA, GR_NU, GR_MU, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_LAMDA, GR_OMICRON, GR_PI, GR_KAPPA, GR_MU, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+
+ GR_ZETA, GR_ALPHA, GR_SIGMA, GR_DELTA, GR_CHI, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_CHI, GR_SIGMA, GR_DELTA, GR_PHI, GR_ZETA, GR_PSI, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_PSI, GR_DELTA, GR_PHI, GR_GAMMA, GR_CHI, GR_OMEGA, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_OMEGA, GR_PHI, GR_GAMMA, GR_ETA, GR_PSI, GR_BETA, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_BETA, GR_GAMMA, GR_ETA, GR_XI, GR_OMEGA, GR_NU, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_NU, GR_ETA, GR_XI, GR_KAPPA, GR_BETA, GR_MU, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ GR_MU, GR_XI, GR_KAPPA, GR_LAMDA, GR_NU, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
+ NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL, NUL,
};
@@ -182,6 +433,8 @@ public final class SpellCheckerProximityInfo {
return Latin.PROXIMITY;
case AndroidSpellCheckerService.SCRIPT_CYRILLIC:
return Cyrillic.PROXIMITY;
+ case AndroidSpellCheckerService.SCRIPT_GREEK:
+ return Greek.PROXIMITY;
default:
throw new RuntimeException("Wrong script supplied: " + script);
}
@@ -193,6 +446,8 @@ public final class SpellCheckerProximityInfo {
return Latin.getIndexOf(codePoint);
case AndroidSpellCheckerService.SCRIPT_CYRILLIC:
return Cyrillic.getIndexOf(codePoint);
+ case AndroidSpellCheckerService.SCRIPT_GREEK:
+ return Greek.getIndexOf(codePoint);
default:
throw new RuntimeException("Wrong script supplied: " + script);
}
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsActivity.java b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsActivity.java
index e63dff312..119ca4755 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsActivity.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsActivity.java
@@ -1,17 +1,17 @@
-/**
+/*
* 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
+ * 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
+ * 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.
+ * 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.spellcheck;
diff --git a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java
index ef5123d68..9606b0352 100644
--- a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java
+++ b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java
@@ -1,17 +1,17 @@
-/**
+/*
* 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
+ * 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
+ * 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.
+ * 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.spellcheck;
diff --git a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java
index 4e9fd1968..ed408bb3c 100644
--- a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java
+++ b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.suggestions;
@@ -22,7 +22,6 @@ import android.graphics.drawable.Drawable;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
-import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.internal.KeyboardBuilder;
import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.keyboard.internal.KeyboardParams;
@@ -66,7 +65,7 @@ public final class MoreSuggestions extends Keyboard {
int pos = fromPos, rowStartPos = fromPos;
final int size = Math.min(suggestions.size(), SuggestionStripView.MAX_SUGGESTIONS);
while (pos < size) {
- final String word = suggestions.getWord(pos).toString();
+ final String word = suggestions.getWord(pos);
// TODO: Should take care of text x-scaling.
mWidths[pos] = (int)view.getLabelWidth(word, paint) + padding;
final int numColumn = pos - rowStartPos + 1;
@@ -176,11 +175,11 @@ public final class MoreSuggestions extends Keyboard {
}
public Builder layout(final SuggestedWords suggestions, final int fromPos,
- final int maxWidth, final int minWidth, final int maxRow) {
- final Keyboard keyboard = KeyboardSwitcher.getInstance().getKeyboard();
+ final int maxWidth, final int minWidth, final int maxRow,
+ final Keyboard parentKeyboard) {
final int xmlId = R.xml.kbd_suggestions_pane_template;
- load(xmlId, keyboard.mId);
- mParams.mVerticalGap = mParams.mTopPadding = keyboard.mVerticalGap / 2;
+ load(xmlId, parentKeyboard.mId);
+ mParams.mVerticalGap = mParams.mTopPadding = parentKeyboard.mVerticalGap / 2;
mPaneView.updateKeyboardGeometry(mParams.mDefaultRowHeight);
final int count = mParams.layout(suggestions, fromPos, maxWidth, minWidth, maxRow,
diff --git a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java
index 03a2e73d1..438820d17 100644
--- a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java
+++ b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java
@@ -17,92 +17,29 @@
package com.android.inputmethod.latin.suggestions;
import android.content.Context;
-import android.content.res.Resources;
import android.util.AttributeSet;
-import android.view.Gravity;
-import android.view.MotionEvent;
-import android.view.View;
-import android.widget.PopupWindow;
-import com.android.inputmethod.keyboard.KeyDetector;
-import com.android.inputmethod.keyboard.Keyboard;
-import com.android.inputmethod.keyboard.KeyboardActionListener;
-import com.android.inputmethod.keyboard.KeyboardView;
-import com.android.inputmethod.keyboard.MoreKeysDetector;
-import com.android.inputmethod.keyboard.MoreKeysPanel;
-import com.android.inputmethod.keyboard.PointerTracker;
-import com.android.inputmethod.keyboard.PointerTracker.DrawingProxy;
-import com.android.inputmethod.keyboard.PointerTracker.KeyEventHandler;
-import com.android.inputmethod.keyboard.PointerTracker.TimerProxy;
+import com.android.inputmethod.keyboard.MoreKeysKeyboardView;
import com.android.inputmethod.latin.R;
/**
* A view that renders a virtual {@link MoreSuggestions}. It handles rendering of keys and detecting
* key presses and touch movements.
*/
-public final class MoreSuggestionsView extends KeyboardView implements MoreKeysPanel {
- private final int[] mCoordinates = new int[2];
-
- final KeyDetector mModalPanelKeyDetector;
- private final KeyDetector mSlidingPanelKeyDetector;
-
- private Controller mController;
- KeyboardActionListener mListener;
- private int mOriginX;
- private int mOriginY;
-
- static final TimerProxy EMPTY_TIMER_PROXY = new TimerProxy.Adapter();
-
- final KeyboardActionListener mSuggestionsPaneListener =
- new KeyboardActionListener.Adapter() {
- @Override
- public void onPressKey(int primaryCode) {
- mListener.onPressKey(primaryCode);
- }
-
- @Override
- public void onReleaseKey(int primaryCode, boolean withSliding) {
- mListener.onReleaseKey(primaryCode, withSliding);
- }
-
- @Override
- public void onCodeInput(int primaryCode, int x, int y) {
- final int index = primaryCode - MoreSuggestions.SUGGESTION_CODE_BASE;
- if (index >= 0 && index < SuggestionStripView.MAX_SUGGESTIONS) {
- mListener.onCustomRequest(index);
- }
- }
-
- @Override
- public void onCancelInput() {
- mListener.onCancelInput();
- }
- };
-
- public MoreSuggestionsView(Context context, AttributeSet attrs) {
+public final class MoreSuggestionsView extends MoreKeysKeyboardView {
+ public MoreSuggestionsView(final Context context, final AttributeSet attrs) {
this(context, attrs, R.attr.moreSuggestionsViewStyle);
}
- public MoreSuggestionsView(Context context, AttributeSet attrs, int defStyle) {
+ public MoreSuggestionsView(final Context context, final AttributeSet attrs,
+ final int defStyle) {
super(context, attrs, defStyle);
-
- final Resources res = context.getResources();
- mModalPanelKeyDetector = new KeyDetector(/* keyHysteresisDistance */ 0);
- mSlidingPanelKeyDetector = new MoreKeysDetector(
- res.getDimension(R.dimen.more_suggestions_slide_allowance));
- setKeyPreviewPopupEnabled(false, 0);
}
@Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- final Keyboard keyboard = getKeyboard();
- if (keyboard != null) {
- final int width = keyboard.mOccupiedWidth + getPaddingLeft() + getPaddingRight();
- final int height = keyboard.mOccupiedHeight + getPaddingTop() + getPaddingBottom();
- setMeasuredDimension(width, height);
- } else {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- }
+ protected int getDefaultCoordX() {
+ final MoreSuggestions pane = (MoreSuggestions)getKeyboard();
+ return pane.mOccupiedWidth / 2;
}
public void updateKeyboardGeometry(final int keyHeight) {
@@ -110,116 +47,10 @@ public final class MoreSuggestionsView extends KeyboardView implements MoreKeysP
}
@Override
- public void setKeyboard(Keyboard keyboard) {
- super.setKeyboard(keyboard);
- mModalPanelKeyDetector.setKeyboard(keyboard, -getPaddingLeft(), -getPaddingTop());
- mSlidingPanelKeyDetector.setKeyboard(keyboard, -getPaddingLeft(),
- -getPaddingTop() + mVerticalCorrection);
- }
-
- @Override
- public KeyDetector getKeyDetector() {
- return mSlidingPanelKeyDetector;
- }
-
- @Override
- public KeyboardActionListener getKeyboardActionListener() {
- return mSuggestionsPaneListener;
- }
-
- @Override
- public DrawingProxy getDrawingProxy() {
- return this;
- }
-
- @Override
- public TimerProxy getTimerProxy() {
- return EMPTY_TIMER_PROXY;
- }
-
- @Override
- public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) {
- // Suggestions pane 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 showMoreKeysPanel(View parentView, Controller controller, int pointX, int pointY,
- PopupWindow window, KeyboardActionListener listener) {
- mController = controller;
- mListener = listener;
- final View container = (View)getParent();
- final MoreSuggestions pane = (MoreSuggestions)getKeyboard();
- final int defaultCoordX = pane.mOccupiedWidth / 2;
- // The coordinates of panel's left-top corner in parentView's coordinate system.
- final int x = pointX - defaultCoordX - container.getPaddingLeft();
- final int y = pointY - container.getMeasuredHeight() + container.getPaddingBottom();
-
- window.setContentView(container);
- window.setWidth(container.getMeasuredWidth());
- window.setHeight(container.getMeasuredHeight());
- parentView.getLocationInWindow(mCoordinates);
- window.showAtLocation(parentView, Gravity.NO_GRAVITY,
- x + mCoordinates[0], y + mCoordinates[1]);
-
- mOriginX = x + container.getPaddingLeft();
- mOriginY = y + container.getPaddingTop();
- }
-
- private boolean mIsDismissing;
-
- @Override
- public boolean dismissMoreKeysPanel() {
- if (mIsDismissing || mController == null) return false;
- mIsDismissing = true;
- final boolean dismissed = mController.dismissMoreKeysPanel();
- mIsDismissing = false;
- return dismissed;
- }
-
- @Override
- public int translateX(int x) {
- return x - mOriginX;
- }
-
- @Override
- public int translateY(int y) {
- return y - mOriginY;
- }
-
- private final KeyEventHandler mModalPanelKeyEventHandler = new KeyEventHandler() {
- @Override
- public KeyDetector getKeyDetector() {
- return mModalPanelKeyDetector;
- }
-
- @Override
- public KeyboardActionListener getKeyboardActionListener() {
- return mSuggestionsPaneListener;
- }
-
- @Override
- public DrawingProxy getDrawingProxy() {
- return MoreSuggestionsView.this;
+ public void onCodeInput(final int code, final int x, final int y) {
+ final int index = code - MoreSuggestions.SUGGESTION_CODE_BASE;
+ if (index >= 0 && index < SuggestionStripView.MAX_SUGGESTIONS) {
+ mListener.onCustomRequest(index);
}
-
- @Override
- public TimerProxy getTimerProxy() {
- return EMPTY_TIMER_PROXY;
- }
- };
-
- @Override
- public boolean onTouchEvent(MotionEvent me) {
- final int action = me.getAction();
- final long eventTime = me.getEventTime();
- final int index = me.getActionIndex();
- final int id = me.getPointerId(index);
- final PointerTracker tracker = PointerTracker.getPointerTracker(id, this);
- final int x = (int)me.getX(index);
- final int y = (int)me.getY(index);
- tracker.processMotionEvent(action, x, y, eventTime, mModalPanelKeyEventHandler);
- return true;
}
}
diff --git a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java
index a1c95ad8a..5a29eee4e 100644
--- a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java
+++ b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java
@@ -1,17 +1,17 @@
/*
* 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
+ * 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
+ * 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.
+ * 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.suggestions;
@@ -27,9 +27,7 @@ import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
-import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
@@ -48,21 +46,21 @@ import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
-import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
+import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
-import com.android.inputmethod.keyboard.KeyboardView;
+import com.android.inputmethod.keyboard.KeyboardSwitcher;
+import com.android.inputmethod.keyboard.MainKeyboardView;
import com.android.inputmethod.keyboard.MoreKeysPanel;
-import com.android.inputmethod.keyboard.PointerTracker;
import com.android.inputmethod.keyboard.ViewLayoutUtils;
import com.android.inputmethod.latin.AutoCorrection;
import com.android.inputmethod.latin.CollectionUtils;
+import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.ResourceUtils;
-import com.android.inputmethod.latin.StaticInnerHandlerWrapper;
import com.android.inputmethod.latin.SuggestedWords;
import com.android.inputmethod.latin.Utils;
import com.android.inputmethod.latin.define.ProductionFlag;
@@ -74,7 +72,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
OnLongClickListener {
public interface Listener {
public void addWordToUserDictionary(String word);
- public void pickSuggestionManually(int index, CharSequence word);
+ public void pickSuggestionManually(int index, String word);
}
// The maximum number of suggestions available. See {@link Suggest#mPrefMaxSuggestions}.
@@ -83,54 +81,22 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
static final boolean DBG = LatinImeLogger.sDBG;
private final ViewGroup mSuggestionsStrip;
- private KeyboardView mKeyboardView;
+ MainKeyboardView mMainKeyboardView;
private final View mMoreSuggestionsContainer;
private final MoreSuggestionsView mMoreSuggestionsView;
private final MoreSuggestions.Builder mMoreSuggestionsBuilder;
- private final PopupWindow mMoreSuggestionsWindow;
private final ArrayList<TextView> mWords = CollectionUtils.newArrayList();
private final ArrayList<TextView> mInfos = CollectionUtils.newArrayList();
private final ArrayList<View> mDividers = CollectionUtils.newArrayList();
- private final PopupWindow mPreviewPopup;
- private final TextView mPreviewText;
-
- private Listener mListener;
- private SuggestedWords mSuggestedWords = SuggestedWords.EMPTY;
+ Listener mListener;
+ SuggestedWords mSuggestedWords = SuggestedWords.EMPTY;
private final SuggestionStripViewParams mParams;
private static final float MIN_TEXT_XSCALE = 0.70f;
- private final UiHandler mHandler = new UiHandler(this);
-
- private static final class UiHandler extends StaticInnerHandlerWrapper<SuggestionStripView> {
- private static final int MSG_HIDE_PREVIEW = 0;
-
- public UiHandler(SuggestionStripView outerInstance) {
- super(outerInstance);
- }
-
- @Override
- public void dispatchMessage(Message msg) {
- final SuggestionStripView suggestionStripView = getOuterInstance();
- switch (msg.what) {
- case MSG_HIDE_PREVIEW:
- suggestionStripView.hidePreview();
- break;
- }
- }
-
- public void cancelHidePreview() {
- removeMessages(MSG_HIDE_PREVIEW);
- }
-
- public void cancelAllMessages() {
- cancelHidePreview();
- }
- }
-
private static final class SuggestionStripViewParams {
private static final int DEFAULT_SUGGESTIONS_COUNT_IN_STRIP = 3;
private static final float DEFAULT_CENTER_SUGGESTION_PERCENTILE = 0.40f;
@@ -177,8 +143,9 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
private final TextView mLeftwardsArrowView;
private final TextView mHintToSaveView;
- public SuggestionStripViewParams(Context context, AttributeSet attrs, int defStyle,
- ArrayList<TextView> words, ArrayList<View> dividers, ArrayList<TextView> infos) {
+ public SuggestionStripViewParams(final Context context, final AttributeSet attrs,
+ final int defStyle, final ArrayList<TextView> words, final ArrayList<View> dividers,
+ final ArrayList<TextView> infos) {
mWords = words;
mDividers = dividers;
mInfos = infos;
@@ -250,7 +217,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return mMaxMoreSuggestionsRow * mMoreSuggestionsRowHeight + mMoreSuggestionsBottomGap;
}
- public int setMoreSuggestionsHeight(int remainingHeight) {
+ public int setMoreSuggestionsHeight(final int remainingHeight) {
final int currentHeight = getMoreSuggestionsHeight();
if (currentHeight <= remainingHeight) {
return currentHeight;
@@ -262,7 +229,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return newHeight;
}
- private static Drawable getMoreSuggestionsHint(Resources res, float textSize, int color) {
+ private static Drawable getMoreSuggestionsHint(final Resources res, final float textSize,
+ final int color) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setTextAlign(Align.CENTER);
@@ -279,8 +247,9 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return new BitmapDrawable(res, buffer);
}
- private CharSequence getStyledSuggestionWord(SuggestedWords suggestedWords, int pos) {
- final CharSequence word = suggestedWords.getWord(pos);
+ private CharSequence getStyledSuggestionWord(final SuggestedWords suggestedWords,
+ final int pos) {
+ final String word = suggestedWords.getWord(pos);
final boolean isAutoCorrect = pos == 1 && suggestedWords.willAutoCorrect();
final boolean isTypedWordValid = pos == 0 && suggestedWords.mTypedWordValid;
if (!isAutoCorrect && !isTypedWordValid)
@@ -299,7 +268,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return spannedWord;
}
- private int getWordPosition(int index, SuggestedWords suggestedWords) {
+ private int getWordPosition(final int index, final SuggestedWords suggestedWords) {
// TODO: This works for 3 suggestions. Revisit this algorithm when there are 5 or more
// suggestions.
final int centerPos = suggestedWords.willAutoCorrect() ? 1 : 0;
@@ -312,7 +281,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
}
- private int getSuggestionTextColor(int index, SuggestedWords suggestedWords, int pos) {
+ private int getSuggestionTextColor(final int index, final SuggestedWords suggestedWords,
+ final int pos) {
// TODO: Need to revisit this logic with bigram suggestions
final boolean isSuggested = (pos != 0);
@@ -331,7 +301,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
// is in slot 1.
if (index == mCenterSuggestionIndex
&& AutoCorrection.shouldBlockAutoCorrectionBySafetyNet(
- suggestedWords.getWord(1).toString(), suggestedWords.getWord(0))) {
+ suggestedWords.getWord(1), suggestedWords.getWord(0))) {
return 0xFFFF0000;
}
}
@@ -355,8 +325,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
params.gravity = Gravity.CENTER;
}
- public void layout(SuggestedWords suggestedWords, ViewGroup stripView, ViewGroup placer,
- int stripWidth) {
+ public void layout(final SuggestedWords suggestedWords, final ViewGroup stripView,
+ final ViewGroup placer, final int stripWidth) {
if (suggestedWords.mIsPunctuationSuggestions) {
layoutPunctuationSuggestions(suggestedWords, stripView);
return;
@@ -402,7 +372,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
x += word.getMeasuredWidth();
if (DBG && pos < suggestedWords.size()) {
- final CharSequence debugInfo = Utils.getDebugInfo(suggestedWords, pos);
+ final String debugInfo = Utils.getDebugInfo(suggestedWords, pos);
if (debugInfo != null) {
final TextView info = mInfos.get(pos);
info.setText(debugInfo);
@@ -418,14 +388,14 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
}
- private int getSuggestionWidth(int index, int maxWidth) {
+ private int getSuggestionWidth(final int index, final int maxWidth) {
final int paddings = mPadding * mSuggestionsCountInStrip;
final int dividers = mDividerWidth * (mSuggestionsCountInStrip - 1);
final int availableWidth = maxWidth - paddings - dividers;
return (int)(availableWidth * getSuggestionWeight(index));
}
- private float getSuggestionWeight(int index) {
+ private float getSuggestionWeight(final int index) {
if (index == mCenterSuggestionIndex) {
return mCenterSuggestionWeight;
} else {
@@ -434,7 +404,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
}
- private void setupTexts(SuggestedWords suggestedWords, int countInStrip) {
+ private void setupTexts(final SuggestedWords suggestedWords, final int countInStrip) {
mTexts.clear();
final int count = Math.min(suggestedWords.size(), countInStrip);
for (int pos = 0; pos < count; pos++) {
@@ -447,8 +417,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
}
- private void layoutPunctuationSuggestions(SuggestedWords suggestedWords,
- ViewGroup stripView) {
+ private void layoutPunctuationSuggestions(final SuggestedWords suggestedWords,
+ final ViewGroup stripView) {
final int countInStrip = Math.min(suggestedWords.size(), PUNCTUATIONS_IN_STRIP);
for (int index = 0; index < countInStrip; index++) {
if (index != 0) {
@@ -459,7 +429,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
final TextView word = mWords.get(index);
word.setEnabled(true);
word.setTextColor(mColorAutoCorrect);
- final CharSequence text = suggestedWords.getWord(index);
+ final String text = suggestedWords.getWord(index);
word.setText(text);
word.setTextScaleX(1.0f);
word.setCompoundDrawables(null, null, null, null);
@@ -469,8 +439,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
mMoreSuggestionsAvailable = false;
}
- public void layoutAddToDictionaryHint(CharSequence word, ViewGroup stripView,
- int stripWidth, CharSequence hintText, OnClickListener listener) {
+ public void layoutAddToDictionaryHint(final String word, final ViewGroup stripView,
+ final int stripWidth, final CharSequence hintText, final OnClickListener listener) {
final int width = stripWidth - mDividerWidth - mPadding * 2;
final TextView wordView = mWordToSaveView;
@@ -511,11 +481,11 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return (CharSequence)mWordToSaveView.getTag();
}
- public boolean isAddToDictionaryShowing(View v) {
+ public boolean isAddToDictionaryShowing(final View v) {
return v == mWordToSaveView || v == mHintToSaveView || v == mLeftwardsArrowView;
}
- private static void setLayoutWeight(View v, float weight, int height) {
+ private static void setLayoutWeight(final View v, final float weight, final int height) {
final ViewGroup.LayoutParams lp = v.getLayoutParams();
if (lp instanceof LinearLayout.LayoutParams) {
final LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams)lp;
@@ -525,7 +495,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
}
- private static float getTextScaleX(CharSequence text, int maxWidth, TextPaint paint) {
+ private static float getTextScaleX(final CharSequence text, final int maxWidth,
+ final TextPaint paint) {
paint.setTextScaleX(1.0f);
final int width = getTextWidth(text, paint);
if (width <= maxWidth) {
@@ -534,8 +505,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return maxWidth / (float)width;
}
- private static CharSequence getEllipsizedText(CharSequence text, int maxWidth,
- TextPaint paint) {
+ private static CharSequence getEllipsizedText(final CharSequence text, final int maxWidth,
+ final TextPaint paint) {
if (text == null) return null;
paint.setTextScaleX(1.0f);
final int width = getTextWidth(text, paint);
@@ -556,7 +527,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return ellipsized;
}
- private static int getTextWidth(CharSequence text, TextPaint paint) {
+ private static int getTextWidth(final CharSequence text, final TextPaint paint) {
if (TextUtils.isEmpty(text)) return 0;
final Typeface savedTypeface = paint.getTypeface();
paint.setTypeface(getTextTypeface(text));
@@ -571,7 +542,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return width;
}
- private static Typeface getTextTypeface(CharSequence text) {
+ private static Typeface getTextTypeface(final CharSequence text) {
if (!(text instanceof SpannableString))
return Typeface.DEFAULT;
@@ -593,23 +564,17 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
* @param context
* @param attrs
*/
- public SuggestionStripView(Context context, AttributeSet attrs) {
+ public SuggestionStripView(final Context context, final AttributeSet attrs) {
this(context, attrs, R.attr.suggestionStripViewStyle);
}
- public SuggestionStripView(Context context, AttributeSet attrs, int defStyle) {
+ public SuggestionStripView(final Context context, final AttributeSet attrs,
+ final int defStyle) {
super(context, attrs, defStyle);
final LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.suggestions_strip, this);
- mPreviewPopup = new PopupWindow(context);
- mPreviewText = (TextView) inflater.inflate(R.layout.suggestion_preview, null);
- mPreviewPopup.setWindowLayoutMode(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- mPreviewPopup.setContentView(mPreviewText);
- mPreviewPopup.setBackgroundDrawable(null);
-
mSuggestionsStrip = (ViewGroup)findViewById(R.id.suggestions_strip);
for (int pos = 0; pos < MAX_SUGGESTIONS; pos++) {
final TextView word = (TextView)inflater.inflate(R.layout.suggestion_word, null);
@@ -632,21 +597,6 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
.findViewById(R.id.more_suggestions_view);
mMoreSuggestionsBuilder = new MoreSuggestions.Builder(mMoreSuggestionsView);
- final PopupWindow moreWindow = new PopupWindow(context);
- moreWindow.setWindowLayoutMode(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- moreWindow.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));
- moreWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
- moreWindow.setFocusable(true);
- moreWindow.setOutsideTouchable(true);
- moreWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
- @Override
- public void onDismiss() {
- mKeyboardView.dimEntireKeyboard(false);
- }
- });
- mMoreSuggestionsWindow = moreWindow;
-
final Resources res = context.getResources();
mMoreSuggestionsModalTolerance = res.getDimensionPixelOffset(
R.dimen.more_suggestions_modal_tolerance);
@@ -658,15 +608,12 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
* A connection back to the input method.
* @param listener
*/
- public void setListener(Listener listener, View inputView) {
+ public void setListener(final Listener listener, final View inputView) {
mListener = listener;
- mKeyboardView = (KeyboardView)inputView.findViewById(R.id.keyboard_view);
+ mMainKeyboardView = (MainKeyboardView)inputView.findViewById(R.id.keyboard_view);
}
- public void setSuggestions(SuggestedWords suggestedWords) {
- if (suggestedWords == null)
- return;
-
+ public void setSuggestions(final SuggestedWords suggestedWords) {
clear();
mSuggestedWords = suggestedWords;
mParams.layout(mSuggestedWords, mSuggestionsStrip, this, getWidth());
@@ -675,7 +622,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
}
- public int setMoreSuggestionsHeight(int remainingHeight) {
+ public int setMoreSuggestionsHeight(final int remainingHeight) {
return mParams.setMoreSuggestionsHeight(remainingHeight);
}
@@ -684,7 +631,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
&& mParams.isAddToDictionaryShowing(mSuggestionsStrip.getChildAt(0));
}
- public void showAddToDictionaryHint(CharSequence word, CharSequence hintText) {
+ public void showAddToDictionaryHint(final String word, final CharSequence hintText) {
clear();
mParams.layoutAddToDictionaryHint(word, mSuggestionsStrip, getWidth(), hintText, this);
}
@@ -697,10 +644,6 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
return false;
}
- public SuggestedWords getSuggestions() {
- return mSuggestedWords;
- }
-
public void clear() {
mSuggestionsStrip.removeAllViews();
removeAllViews();
@@ -708,16 +651,12 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
dismissMoreSuggestions();
}
- private void hidePreview() {
- mPreviewPopup.dismiss();
- }
-
private final KeyboardActionListener mMoreSuggestionsListener =
new KeyboardActionListener.Adapter() {
@Override
- public boolean onCustomRequest(int requestCode) {
+ public boolean onCustomRequest(final int requestCode) {
final int index = requestCode;
- final CharSequence word = mSuggestedWords.getWord(index);
+ final String word = mSuggestedWords.getWord(index);
mListener.pickSuggestionManually(index, word);
dismissMoreSuggestions();
return true;
@@ -732,55 +671,62 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
private final MoreKeysPanel.Controller mMoreSuggestionsController =
new MoreKeysPanel.Controller() {
@Override
- public boolean dismissMoreKeysPanel() {
- return dismissMoreSuggestions();
+ public boolean onDismissMoreKeysPanel() {
+ return mMainKeyboardView.onDismissMoreKeysPanel();
}
- };
- private boolean dismissMoreSuggestions() {
- if (mMoreSuggestionsWindow.isShowing()) {
- mMoreSuggestionsWindow.dismiss();
- return true;
+ @Override
+ public void onShowMoreKeysPanel(final MoreKeysPanel panel) {
+ mMainKeyboardView.onShowMoreKeysPanel(panel);
}
- return false;
+
+ @Override
+ public void onCancelMoreKeysPanel() {
+ dismissMoreSuggestions();
+ }
+ };
+
+ boolean dismissMoreSuggestions() {
+ return mMoreSuggestionsView.dismissMoreKeysPanel();
}
@Override
- public boolean onLongClick(View view) {
+ public boolean onLongClick(final View view) {
+ KeyboardSwitcher.getInstance().hapticAndAudioFeedback(Constants.NOT_A_CODE);
return showMoreSuggestions();
}
- private boolean showMoreSuggestions() {
+ boolean showMoreSuggestions() {
+ final Keyboard parentKeyboard = KeyboardSwitcher.getInstance().getKeyboard();
+ if (parentKeyboard == null) {
+ return false;
+ }
final SuggestionStripViewParams params = mParams;
- if (params.mMoreSuggestionsAvailable) {
- final int stripWidth = getWidth();
- final View container = mMoreSuggestionsContainer;
- final int maxWidth = stripWidth - container.getPaddingLeft()
- - container.getPaddingRight();
- final MoreSuggestions.Builder builder = mMoreSuggestionsBuilder;
- builder.layout(mSuggestedWords, params.mSuggestionsCountInStrip, maxWidth,
- (int)(maxWidth * params.mMinMoreSuggestionsWidth),
- params.getMaxMoreSuggestionsRow());
- mMoreSuggestionsView.setKeyboard(builder.build());
- container.measure(
- ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
-
- final MoreKeysPanel moreKeysPanel = mMoreSuggestionsView;
- final int pointX = stripWidth / 2;
- final int pointY = -params.mMoreSuggestionsBottomGap;
- moreKeysPanel.showMoreKeysPanel(
- this, mMoreSuggestionsController, pointX, pointY,
- mMoreSuggestionsWindow, mMoreSuggestionsListener);
- mMoreSuggestionsMode = MORE_SUGGESTIONS_CHECKING_MODAL_OR_SLIDING;
- mOriginX = mLastX;
- mOriginY = mLastY;
- mKeyboardView.dimEntireKeyboard(true);
- for (int i = 0; i < params.mSuggestionsCountInStrip; i++) {
- mWords.get(i).setPressed(false);
- }
- return true;
+ if (!params.mMoreSuggestionsAvailable) {
+ return false;
}
- return false;
+ final int stripWidth = getWidth();
+ final View container = mMoreSuggestionsContainer;
+ final int maxWidth = stripWidth - container.getPaddingLeft() - container.getPaddingRight();
+ final MoreSuggestions.Builder builder = mMoreSuggestionsBuilder;
+ builder.layout(mSuggestedWords, params.mSuggestionsCountInStrip, maxWidth,
+ (int)(maxWidth * params.mMinMoreSuggestionsWidth),
+ params.getMaxMoreSuggestionsRow(), parentKeyboard);
+ mMoreSuggestionsView.setKeyboard(builder.build());
+ container.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+
+ final MoreKeysPanel moreKeysPanel = mMoreSuggestionsView;
+ final int pointX = stripWidth / 2;
+ final int pointY = -params.mMoreSuggestionsBottomGap;
+ moreKeysPanel.showMoreKeysPanel(this, mMoreSuggestionsController, pointX, pointY,
+ mMoreSuggestionsListener);
+ mMoreSuggestionsMode = MORE_SUGGESTIONS_CHECKING_MODAL_OR_SLIDING;
+ mOriginX = mLastX;
+ mOriginY = mLastY;
+ for (int i = 0; i < params.mSuggestionsCountInStrip; i++) {
+ mWords.get(i).setPressed(false);
+ }
+ return true;
}
// Working variables for onLongClick and dispatchTouchEvent.
@@ -807,8 +753,8 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
};
@Override
- public boolean dispatchTouchEvent(MotionEvent me) {
- if (!mMoreSuggestionsWindow.isShowing()
+ public boolean dispatchTouchEvent(final MotionEvent me) {
+ if (!mMoreSuggestionsView.isShowingInParent()
|| mMoreSuggestionsMode == MORE_SUGGESTIONS_IN_MODAL_MODE) {
mLastX = (int)me.getX();
mLastY = (int)me.getY();
@@ -823,7 +769,6 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
final long eventTime = me.getEventTime();
final int index = me.getActionIndex();
final int id = me.getPointerId(index);
- final PointerTracker tracker = PointerTracker.getPointerTracker(id, moreKeysPanel);
final int x = (int)me.getX(index);
final int y = (int)me.getY(index);
final int translatedX = moreKeysPanel.translateX(x);
@@ -835,7 +780,6 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
// Decided to be in the sliding input mode only when the touch point has been moved
// upward.
mMoreSuggestionsMode = MORE_SUGGESTIONS_IN_SLIDING_MODE;
- tracker.onShowMoreKeysPanel(translatedX, translatedY, moreKeysPanel);
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
// Decided to be in the modal input mode
mMoreSuggestionsMode = MORE_SUGGESTIONS_IN_MODAL_MODE;
@@ -844,12 +788,12 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
}
// MORE_SUGGESTIONS_IN_SLIDING_MODE
- tracker.processMotionEvent(action, translatedX, translatedY, eventTime, moreKeysPanel);
+ mMoreSuggestionsView.processMotionEvent(action, translatedX, translatedY, id, eventTime);
return true;
}
@Override
- public void onClick(View view) {
+ public void onClick(final View view) {
if (mParams.isAddToDictionaryShowing(view)) {
mListener.addWordToUserDictionary(mParams.getAddToDictionaryWord().toString());
clear();
@@ -863,15 +807,13 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick
if (index >= mSuggestedWords.size())
return;
- final CharSequence word = mSuggestedWords.getWord(index);
+ final String word = mSuggestedWords.getWord(index);
mListener.pickSuggestionManually(index, word);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
- mHandler.cancelAllMessages();
- hidePreview();
dismissMoreSuggestions();
}
}
diff --git a/java/src/com/android/inputmethod/research/BootBroadcastReceiver.java b/java/src/com/android/inputmethod/research/BootBroadcastReceiver.java
index 5124a35a6..c5f095919 100644
--- a/java/src/com/android/inputmethod/research/BootBroadcastReceiver.java
+++ b/java/src/com/android/inputmethod/research/BootBroadcastReceiver.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
diff --git a/java/src/com/android/inputmethod/research/FeedbackActivity.java b/java/src/com/android/inputmethod/research/FeedbackActivity.java
index 11eae8813..b985fda21 100644
--- a/java/src/com/android/inputmethod/research/FeedbackActivity.java
+++ b/java/src/com/android/inputmethod/research/FeedbackActivity.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
@@ -28,25 +28,10 @@ public class FeedbackActivity extends Activity {
super.onCreate(savedInstanceState);
setContentView(R.layout.research_feedback_activity);
final FeedbackLayout layout = (FeedbackLayout) findViewById(R.id.research_feedback_layout);
- final CheckBox checkbox = (CheckBox) findViewById(R.id.research_feedback_include_history);
- final CharSequence cs = checkbox.getText();
- final String actualString = String.format(cs.toString(),
- ResearchLogger.FEEDBACK_WORD_BUFFER_SIZE);
- checkbox.setText(actualString);
layout.setActivity(this);
}
@Override
- protected void onResume() {
- super.onResume();
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- }
-
- @Override
public void onBackPressed() {
ResearchLogger.getInstance().onLeavingSendFeedbackDialog();
super.onBackPressed();
diff --git a/java/src/com/android/inputmethod/research/FeedbackFragment.java b/java/src/com/android/inputmethod/research/FeedbackFragment.java
index a2e08e2b7..39f9c87a0 100644
--- a/java/src/com/android/inputmethod/research/FeedbackFragment.java
+++ b/java/src/com/android/inputmethod/research/FeedbackFragment.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
@@ -20,6 +20,8 @@ import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.text.Editable;
+import android.text.TextUtils;
+import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
@@ -27,12 +29,22 @@ import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
+import android.widget.Toast;
import com.android.inputmethod.latin.R;
-public class FeedbackFragment extends Fragment {
+public class FeedbackFragment extends Fragment implements OnClickListener {
+ private static final String TAG = FeedbackFragment.class.getSimpleName();
+
+ public static final String KEY_FEEDBACK_STRING = "FeedbackString";
+ public static final String KEY_INCLUDE_ACCOUNT_NAME = "IncludeAccountName";
+ public static final String KEY_HAS_USER_RECORDING = "HasRecording";
+
private EditText mEditText;
- private CheckBox mCheckBox;
+ private CheckBox mIncludingAccountNameCheckBox;
+ private CheckBox mIncludingUserRecordingCheckBox;
+ private Button mSendButton;
+ private Button mCancelButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
@@ -40,34 +52,102 @@ public class FeedbackFragment extends Fragment {
final View view = inflater.inflate(R.layout.research_feedback_fragment_layout, container,
false);
mEditText = (EditText) view.findViewById(R.id.research_feedback_contents);
- mCheckBox = (CheckBox) view.findViewById(R.id.research_feedback_include_history);
-
- final Button sendButton = (Button) view.findViewById(
- R.id.research_feedback_send_button);
- sendButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- final Editable editable = mEditText.getText();
- final String feedbackContents = editable.toString();
- final boolean includeHistory = mCheckBox.isChecked();
- ResearchLogger.getInstance().sendFeedback(feedbackContents, includeHistory);
- final Activity activity = FeedbackFragment.this.getActivity();
- activity.finish();
- ResearchLogger.getInstance().onLeavingSendFeedbackDialog();
+ mEditText.requestFocus();
+ mIncludingAccountNameCheckBox = (CheckBox) view.findViewById(
+ R.id.research_feedback_include_account_name);
+ mIncludingUserRecordingCheckBox = (CheckBox) view.findViewById(
+ R.id.research_feedback_include_recording_checkbox);
+ mIncludingUserRecordingCheckBox.setOnClickListener(this);
+
+ mSendButton = (Button) view.findViewById(R.id.research_feedback_send_button);
+ mSendButton.setOnClickListener(this);
+ mCancelButton = (Button) view.findViewById(R.id.research_feedback_cancel_button);
+ mCancelButton.setOnClickListener(this);
+
+ if (savedInstanceState != null) {
+ Log.d(TAG, "restoring from savedInstanceState");
+ restoreState(savedInstanceState);
+ } else {
+ final Bundle bundle = getActivity().getIntent().getExtras();
+ if (bundle != null) {
+ Log.d(TAG, "restoring from getArguments()");
+ restoreState(bundle);
}
- });
-
- final Button cancelButton = (Button) view.findViewById(
- R.id.research_feedback_cancel_button);
- cancelButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- final Activity activity = FeedbackFragment.this.getActivity();
- activity.finish();
- ResearchLogger.getInstance().onLeavingSendFeedbackDialog();
+ }
+ return view;
+ }
+
+ @Override
+ public void onClick(final View view) {
+ final ResearchLogger researchLogger = ResearchLogger.getInstance();
+ if (view == mIncludingUserRecordingCheckBox) {
+ if (hasUserRecording()) {
+ // Remove the recording
+ setHasUserRecording(false);
+ } else {
+ final Bundle bundle = new Bundle();
+ onSaveInstanceState(bundle);
+
+ // Let the user make a recording
+ getActivity().finish();
+
+ researchLogger.setFeedbackDialogBundle(bundle);
+ researchLogger.onLeavingSendFeedbackDialog();
+ researchLogger.startRecording();
}
- });
+ } else if (view == mSendButton) {
+ final Editable editable = mEditText.getText();
+ final String feedbackContents = editable.toString();
+ if (TextUtils.isEmpty(feedbackContents)) {
+ Toast.makeText(getActivity(),
+ R.string.research_feedback_empty_feedback_error_message,
+ Toast.LENGTH_LONG).show();
+ } else {
+ final boolean isIncludingAccountName = isIncludingAccountName();
+ researchLogger.sendFeedback(feedbackContents,
+ false /* isIncludingHistory */, isIncludingAccountName, hasUserRecording());
+ getActivity().finish();
+ researchLogger.setFeedbackDialogBundle(null);
+ researchLogger.onLeavingSendFeedbackDialog();
+ }
+ } else if (view == mCancelButton) {
+ Log.d(TAG, "Finishing");
+ getActivity().finish();
+ researchLogger.setFeedbackDialogBundle(null);
+ researchLogger.onLeavingSendFeedbackDialog();
+ } else {
+ Log.e(TAG, "Unknown view passed to FeedbackFragment.onClick()");
+ }
+ }
- return view;
+ @Override
+ public void onSaveInstanceState(final Bundle bundle) {
+ final String savedFeedbackString = mEditText.getText().toString();
+
+ bundle.putString(KEY_FEEDBACK_STRING, savedFeedbackString);
+ bundle.putBoolean(KEY_INCLUDE_ACCOUNT_NAME, isIncludingAccountName());
+ bundle.putBoolean(KEY_HAS_USER_RECORDING, hasUserRecording());
+ }
+
+ public void restoreState(final Bundle bundle) {
+ mEditText.setText(bundle.getString(KEY_FEEDBACK_STRING));
+ setIsIncludingAccountName(bundle.getBoolean(KEY_INCLUDE_ACCOUNT_NAME));
+ setHasUserRecording(bundle.getBoolean(KEY_HAS_USER_RECORDING));
+ }
+
+ private boolean hasUserRecording() {
+ return mIncludingUserRecordingCheckBox.isChecked();
+ }
+
+ private void setHasUserRecording(final boolean hasRecording) {
+ mIncludingUserRecordingCheckBox.setChecked(hasRecording);
+ }
+
+ private boolean isIncludingAccountName() {
+ return mIncludingAccountNameCheckBox.isChecked();
+ }
+
+ private void setIsIncludingAccountName(final boolean isIncludingAccountName) {
+ mIncludingAccountNameCheckBox.setChecked(isIncludingAccountName);
}
}
diff --git a/java/src/com/android/inputmethod/research/FeedbackLayout.java b/java/src/com/android/inputmethod/research/FeedbackLayout.java
index f2cbfe308..d283d14b2 100644
--- a/java/src/com/android/inputmethod/research/FeedbackLayout.java
+++ b/java/src/com/android/inputmethod/research/FeedbackLayout.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
diff --git a/java/src/com/android/inputmethod/research/FixedLogBuffer.java b/java/src/com/android/inputmethod/research/FixedLogBuffer.java
new file mode 100644
index 000000000..78dc59562
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/FixedLogBuffer.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2012 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.research;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+
+/**
+ * A buffer that holds a fixed number of LogUnits.
+ *
+ * LogUnits are added in and shifted out in temporal order. Only a subset of the LogUnits are
+ * actual words; the other LogUnits do not count toward the word limit. Once the buffer reaches
+ * capacity, adding another LogUnit that is a word evicts the oldest LogUnits out one at a time to
+ * stay under the capacity limit.
+ *
+ * This variant of a LogBuffer has a limited memory footprint because of its limited size. This
+ * makes it useful, for example, for recording a window of the user's most recent actions in case
+ * they want to report an observed error that they do not know how to reproduce.
+ */
+public class FixedLogBuffer extends LogBuffer {
+ /* package for test */ int mWordCapacity;
+ // The number of members of mLogUnits that are actual words.
+ private int mNumActualWords;
+
+ /**
+ * Create a new LogBuffer that can hold a fixed number of LogUnits that are words (and
+ * unlimited number of non-word LogUnits), and that outputs its result to a researchLog.
+ *
+ * @param wordCapacity maximum number of words
+ */
+ public FixedLogBuffer(final int wordCapacity) {
+ super();
+ if (wordCapacity <= 0) {
+ throw new IllegalArgumentException("wordCapacity must be 1 or greater.");
+ }
+ mWordCapacity = wordCapacity;
+ mNumActualWords = 0;
+ }
+
+ protected int getNumActualWords() {
+ return mNumActualWords;
+ }
+
+ /**
+ * Adds a new LogUnit to the front of the LIFO queue, evicting existing LogUnit's
+ * (oldest first) if word capacity is reached.
+ */
+ @Override
+ public void shiftIn(final LogUnit newLogUnit) {
+ if (!newLogUnit.hasWord()) {
+ // This LogUnit isn't a word, so it doesn't count toward the word-limit.
+ super.shiftIn(newLogUnit);
+ return;
+ }
+ if (mNumActualWords >= mWordCapacity) {
+ // Give subclass a chance to handle the buffer full condition by shifting out logUnits.
+ onBufferFull();
+ // If still full, evict.
+ if (mNumActualWords >= mWordCapacity) {
+ shiftOutWords(1);
+ }
+ }
+ super.shiftIn(newLogUnit);
+ mNumActualWords++; // Must be a word, or we wouldn't be here.
+ }
+
+ @Override
+ public LogUnit unshiftIn() {
+ final LogUnit logUnit = super.unshiftIn();
+ if (logUnit != null && logUnit.hasWord()) {
+ mNumActualWords--;
+ }
+ return logUnit;
+ }
+
+ public int getNumWords() {
+ return mNumActualWords;
+ }
+
+ /**
+ * Removes all LogUnits from the buffer without calling onShiftOut().
+ */
+ @Override
+ public void clear() {
+ super.clear();
+ mNumActualWords = 0;
+ }
+
+ /**
+ * Called when the buffer has just shifted in one more word than its maximum, and its about to
+ * shift out LogUnits to bring it back down to the maximum.
+ *
+ * Base class does nothing; subclasses may override if they want to record non-privacy sensitive
+ * events that fall off the end.
+ */
+ protected void onBufferFull() {
+ }
+
+ @Override
+ public LogUnit shiftOut() {
+ final LogUnit logUnit = super.shiftOut();
+ if (logUnit != null && logUnit.hasWord()) {
+ mNumActualWords--;
+ }
+ return logUnit;
+ }
+
+ protected void shiftOutWords(final int numWords) {
+ final int targetNumWords = mNumActualWords - numWords;
+ final LinkedList<LogUnit> logUnits = getLogUnits();
+ while (mNumActualWords > targetNumWords && !logUnits.isEmpty()) {
+ shiftOut();
+ }
+ }
+
+ public void shiftOutAll() {
+ final LinkedList<LogUnit> logUnits = getLogUnits();
+ while (!logUnits.isEmpty()) {
+ shiftOut();
+ }
+ mNumActualWords = 0;
+ }
+
+ /**
+ * Returns a list of {@link LogUnit}s at the front of the buffer that have associated words. No
+ * more than {@code n} LogUnits will have words associated with them. If there are not enough
+ * LogUnits in the buffer to meet the word requirement, returns the all LogUnits.
+ *
+ * @param n The maximum number of {@link LogUnit}s with words to return.
+ * @return The list of the {@link LogUnit}s containing the first n words
+ */
+ public ArrayList<LogUnit> peekAtFirstNWords(int n) {
+ final LinkedList<LogUnit> logUnits = getLogUnits();
+ final int length = logUnits.size();
+ // Allocate space for n*2 logUnits. There will be at least n, one for each word, and
+ // there may be additional for punctuation, between-word commands, etc. This should be
+ // enough that reallocation won't be necessary.
+ final ArrayList<LogUnit> list = new ArrayList<LogUnit>(n * 2);
+ for (int i = 0; i < length && n > 0; i++) {
+ final LogUnit logUnit = logUnits.get(i);
+ list.add(logUnit);
+ if (logUnit.hasWord()) {
+ n--;
+ }
+ }
+ return list;
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/JsonUtils.java b/java/src/com/android/inputmethod/research/JsonUtils.java
new file mode 100644
index 000000000..24cd8d935
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/JsonUtils.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2012 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.research;
+
+import android.content.SharedPreferences;
+import android.util.JsonWriter;
+import android.view.MotionEvent;
+import android.view.inputmethod.CompletionInfo;
+
+import com.android.inputmethod.keyboard.Key;
+import com.android.inputmethod.latin.SuggestedWords;
+import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
+
+import java.io.IOException;
+import java.util.Map;
+
+/**
+ * Routines for mapping classes and variables to JSON representations for logging.
+ */
+/* package */ class JsonUtils {
+ private JsonUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ /* package */ static void writeJson(final CompletionInfo[] ci, final JsonWriter jsonWriter)
+ throws IOException {
+ jsonWriter.beginArray();
+ for (int j = 0; j < ci.length; j++) {
+ jsonWriter.value(ci[j].toString());
+ }
+ jsonWriter.endArray();
+ }
+
+ /* package */ static void writeJson(final SharedPreferences prefs, final JsonWriter jsonWriter)
+ throws IOException {
+ jsonWriter.beginObject();
+ for (Map.Entry<String,?> entry : prefs.getAll().entrySet()) {
+ jsonWriter.name(entry.getKey());
+ final Object innerValue = entry.getValue();
+ if (innerValue == null) {
+ jsonWriter.nullValue();
+ } else if (innerValue instanceof Boolean) {
+ jsonWriter.value((Boolean) innerValue);
+ } else if (innerValue instanceof Number) {
+ jsonWriter.value((Number) innerValue);
+ } else {
+ jsonWriter.value(innerValue.toString());
+ }
+ }
+ jsonWriter.endObject();
+ }
+
+ /* package */ static void writeJson(final Key[] keys, final JsonWriter jsonWriter)
+ throws IOException {
+ jsonWriter.beginArray();
+ for (Key key : keys) {
+ writeJson(key, jsonWriter);
+ }
+ jsonWriter.endArray();
+ }
+
+ private static void writeJson(final Key key, final JsonWriter jsonWriter) throws IOException {
+ jsonWriter.beginObject();
+ jsonWriter.name("code").value(key.mCode);
+ jsonWriter.name("altCode").value(key.getAltCode());
+ jsonWriter.name("x").value(key.mX);
+ jsonWriter.name("y").value(key.mY);
+ jsonWriter.name("w").value(key.mWidth);
+ jsonWriter.name("h").value(key.mHeight);
+ jsonWriter.endObject();
+ }
+
+ /* package */ static void writeJson(final SuggestedWords words, final JsonWriter jsonWriter)
+ throws IOException {
+ jsonWriter.beginObject();
+ jsonWriter.name("typedWordValid").value(words.mTypedWordValid);
+ jsonWriter.name("willAutoCorrect")
+ .value(words.mWillAutoCorrect);
+ jsonWriter.name("isPunctuationSuggestions")
+ .value(words.mIsPunctuationSuggestions);
+ jsonWriter.name("isObsoleteSuggestions").value(words.mIsObsoleteSuggestions);
+ jsonWriter.name("isPrediction").value(words.mIsPrediction);
+ jsonWriter.name("words");
+ jsonWriter.beginArray();
+ final int size = words.size();
+ for (int j = 0; j < size; j++) {
+ final SuggestedWordInfo wordInfo = words.getInfo(j);
+ jsonWriter.value(wordInfo.toString());
+ }
+ jsonWriter.endArray();
+ jsonWriter.endObject();
+ }
+
+ /* package */ static void writeJson(final MotionEvent me, final JsonWriter jsonWriter)
+ throws IOException {
+ jsonWriter.beginObject();
+ jsonWriter.name("pointerIds");
+ jsonWriter.beginArray();
+ final int pointerCount = me.getPointerCount();
+ for (int index = 0; index < pointerCount; index++) {
+ jsonWriter.value(me.getPointerId(index));
+ }
+ jsonWriter.endArray();
+
+ jsonWriter.name("xyt");
+ jsonWriter.beginArray();
+ final int historicalSize = me.getHistorySize();
+ for (int index = 0; index < historicalSize; index++) {
+ jsonWriter.beginObject();
+ jsonWriter.name("t");
+ jsonWriter.value(me.getHistoricalEventTime(index));
+ jsonWriter.name("d");
+ jsonWriter.beginArray();
+ for (int pointerIndex = 0; pointerIndex < pointerCount; pointerIndex++) {
+ jsonWriter.beginObject();
+ jsonWriter.name("x");
+ jsonWriter.value(me.getHistoricalX(pointerIndex, index));
+ jsonWriter.name("y");
+ jsonWriter.value(me.getHistoricalY(pointerIndex, index));
+ jsonWriter.endObject();
+ }
+ jsonWriter.endArray();
+ jsonWriter.endObject();
+ }
+ jsonWriter.beginObject();
+ jsonWriter.name("t");
+ jsonWriter.value(me.getEventTime());
+ jsonWriter.name("d");
+ jsonWriter.beginArray();
+ for (int pointerIndex = 0; pointerIndex < pointerCount; pointerIndex++) {
+ jsonWriter.beginObject();
+ jsonWriter.name("x");
+ jsonWriter.value(me.getX(pointerIndex));
+ jsonWriter.name("y");
+ jsonWriter.value(me.getY(pointerIndex));
+ jsonWriter.endObject();
+ }
+ jsonWriter.endArray();
+ jsonWriter.endObject();
+ jsonWriter.endArray();
+ jsonWriter.endObject();
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/LogBuffer.java b/java/src/com/android/inputmethod/research/LogBuffer.java
index ae7b1579a..b07b761f0 100644
--- a/java/src/com/android/inputmethod/research/LogBuffer.java
+++ b/java/src/com/android/inputmethod/research/LogBuffer.java
@@ -1,113 +1,73 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
-import com.android.inputmethod.latin.CollectionUtils;
-
import java.util.LinkedList;
/**
- * A buffer that holds a fixed number of LogUnits.
+ * Maintain a FIFO queue of LogUnits.
*
- * LogUnits are added in and shifted out in temporal order. Only a subset of the LogUnits are
- * actual words; the other LogUnits do not count toward the word limit. Once the buffer reaches
- * capacity, adding another LogUnit that is a word evicts the oldest LogUnits out one at a time to
- * stay under the capacity limit.
+ * This class provides an unbounded queue. This is useful when the user is aware that their actions
+ * are being recorded, such as when they are trying to reproduce a bug. In this case, there should
+ * not be artificial restrictions on how many events that can be saved.
*/
public class LogBuffer {
- protected final LinkedList<LogUnit> mLogUnits;
- /* package for test */ int mWordCapacity;
- // The number of members of mLogUnits that are actual words.
- protected int mNumActualWords;
+ // TODO: Gracefully handle situations in which this LogBuffer is consuming too much memory.
+ // This may happen, for example, if the user has forgotten that data is being logged.
+ private final LinkedList<LogUnit> mLogUnits;
- /**
- * Create a new LogBuffer that can hold a fixed number of LogUnits that are words (and
- * unlimited number of non-word LogUnits), and that outputs its result to a researchLog.
- *
- * @param wordCapacity maximum number of words
- */
- LogBuffer(final int wordCapacity) {
- if (wordCapacity <= 0) {
- throw new IllegalArgumentException("wordCapacity must be 1 or greater.");
- }
- mLogUnits = CollectionUtils.newLinkedList();
- mWordCapacity = wordCapacity;
- mNumActualWords = 0;
- }
-
- /**
- * Adds a new LogUnit to the front of the LIFO queue, evicting existing LogUnit's
- * (oldest first) if word capacity is reached.
- */
- public void shiftIn(LogUnit newLogUnit) {
- if (newLogUnit.getWord() == null) {
- // This LogUnit isn't a word, so it doesn't count toward the word-limit.
- mLogUnits.add(newLogUnit);
- return;
- }
- if (mNumActualWords == mWordCapacity) {
- shiftOutThroughFirstWord();
- }
- mLogUnits.add(newLogUnit);
- mNumActualWords++; // Must be a word, or we wouldn't be here.
+ public LogBuffer() {
+ mLogUnits = new LinkedList<LogUnit>();
}
- private void shiftOutThroughFirstWord() {
- while (!mLogUnits.isEmpty()) {
- final LogUnit logUnit = mLogUnits.removeFirst();
- onShiftOut(logUnit);
- if (logUnit.hasWord()) {
- // Successfully shifted out a word-containing LogUnit and made space for the new
- // LogUnit.
- mNumActualWords--;
- break;
- }
- }
+ protected LinkedList<LogUnit> getLogUnits() {
+ return mLogUnits;
}
- /**
- * Removes all LogUnits from the buffer without calling onShiftOut().
- */
public void clear() {
mLogUnits.clear();
- mNumActualWords = 0;
}
- /**
- * Called when a LogUnit is removed from the LogBuffer as a result of a shiftIn. LogUnits are
- * removed in the order entered. This method is not called when shiftOut is called directly.
- *
- * Base class does nothing; subclasses may override.
- */
- protected void onShiftOut(LogUnit logUnit) {
+ public void shiftIn(final LogUnit logUnit) {
+ mLogUnits.add(logUnit);
}
- /**
- * Called to deliberately remove the oldest LogUnit. Usually called when draining the
- * LogBuffer.
- */
- public LogUnit shiftOut() {
+ public LogUnit unshiftIn() {
if (mLogUnits.isEmpty()) {
return null;
}
- final LogUnit logUnit = mLogUnits.removeFirst();
- if (logUnit.hasWord()) {
- mNumActualWords--;
+ return mLogUnits.removeLast();
+ }
+
+ public LogUnit peekLastLogUnit() {
+ if (mLogUnits.isEmpty()) {
+ return null;
+ }
+ return mLogUnits.peekLast();
+ }
+
+ public boolean isEmpty() {
+ return mLogUnits.isEmpty();
+ }
+
+ public LogUnit shiftOut() {
+ if (isEmpty()) {
+ return null;
}
- return logUnit;
+ return mLogUnits.removeFirst();
}
}
diff --git a/java/src/com/android/inputmethod/research/LogStatement.java b/java/src/com/android/inputmethod/research/LogStatement.java
new file mode 100644
index 000000000..09b12fcfa
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/LogStatement.java
@@ -0,0 +1,224 @@
+/*
+ * Copyright (C) 2013 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.research;
+
+import android.content.SharedPreferences;
+import android.util.JsonWriter;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.inputmethod.CompletionInfo;
+
+import com.android.inputmethod.keyboard.Key;
+import com.android.inputmethod.latin.SuggestedWords;
+import com.android.inputmethod.latin.define.ProductionFlag;
+
+import java.io.IOException;
+
+/**
+ * A template for typed information stored in the logs.
+ *
+ * A LogStatement contains a name, keys, and flags about whether the {@code Object[] values}
+ * associated with the {@code String[] keys} are likely to reveal information about the user. The
+ * actual values are stored separately.
+ */
+public class LogStatement {
+ private static final String TAG = LogStatement.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+
+ // Constants for particular statements
+ public static final String TYPE_POINTER_TRACKER_CALL_LISTENER_ON_CODE_INPUT =
+ "PointerTrackerCallListenerOnCodeInput";
+ public static final String KEY_CODE = "code";
+ public static final String VALUE_RESEARCH = "research";
+ public static final String TYPE_MAIN_KEYBOARD_VIEW_ON_LONG_PRESS =
+ "MainKeyboardViewOnLongPress";
+ public static final String ACTION = "action";
+ public static final String VALUE_DOWN = "DOWN";
+ public static final String TYPE_MOTION_EVENT = "MotionEvent";
+ public static final String KEY_IS_LOGGING_RELATED = "isLoggingRelated";
+
+ // Keys for internal key/value pairs
+ private static final String CURRENT_TIME_KEY = "_ct";
+ private static final String UPTIME_KEY = "_ut";
+ private static final String EVENT_TYPE_KEY = "_ty";
+
+ // Name specifying the LogStatement type.
+ private final String mType;
+
+ // mIsPotentiallyPrivate indicates that event contains potentially private information. If
+ // the word that this event is a part of is determined to be privacy-sensitive, then this
+ // event should not be included in the output log. The system waits to output until the
+ // containing word is known.
+ private final boolean mIsPotentiallyPrivate;
+
+ // mIsPotentiallyRevealing indicates that this statement may disclose details about other
+ // words typed in other LogUnits. This can happen if the user is not inserting spaces, and
+ // data from Suggestions and/or Composing text reveals the entire "megaword". For example,
+ // say the user is typing "for the win", and the system wants to record the bigram "the
+ // win". If the user types "forthe", omitting the space, the system will give "for the" as
+ // a suggestion. If the user accepts the autocorrection, the suggestion for "for the" is
+ // included in the log for the word "the", disclosing that the previous word had been "for".
+ // For now, we simply do not include this data when logging part of a "megaword".
+ private final boolean mIsPotentiallyRevealing;
+
+ // mKeys stores the names that are the attributes in the output json objects
+ private final String[] mKeys;
+ private static final String[] NULL_KEYS = new String[0];
+
+ LogStatement(final String name, final boolean isPotentiallyPrivate,
+ final boolean isPotentiallyRevealing, final String... keys) {
+ mType = name;
+ mIsPotentiallyPrivate = isPotentiallyPrivate;
+ mIsPotentiallyRevealing = isPotentiallyRevealing;
+ mKeys = (keys == null) ? NULL_KEYS : keys;
+ }
+
+ public String getType() {
+ return mType;
+ }
+
+ public boolean isPotentiallyPrivate() {
+ return mIsPotentiallyPrivate;
+ }
+
+ public boolean isPotentiallyRevealing() {
+ return mIsPotentiallyRevealing;
+ }
+
+ public String[] getKeys() {
+ return mKeys;
+ }
+
+ /**
+ * Utility function to test whether a key-value pair exists in a LogStatement.
+ *
+ * A LogStatement is really just a template -- it does not contain the values, only the
+ * keys. So the values must be passed in as an argument.
+ *
+ * @param queryKey the String that is tested by {@code String.equals()} to the keys in the
+ * LogStatement
+ * @param queryValue an Object that must be {@code Object.equals()} to the key's corresponding
+ * value in the {@code values} array
+ * @param values the values corresponding to mKeys
+ *
+ * @returns {@true} if {@code queryKey} exists in the keys for this LogStatement, and {@code
+ * queryValue} matches the corresponding value in {@code values}
+ *
+ * @throws IllegalArgumentException if {@code values.length} is not equal to keys().length()
+ */
+ public boolean containsKeyValuePair(final String queryKey, final Object queryValue,
+ final Object[] values) {
+ if (mKeys.length != values.length) {
+ throw new IllegalArgumentException("Mismatched number of keys and values.");
+ }
+ final int length = mKeys.length;
+ for (int i = 0; i < length; i++) {
+ if (mKeys[i].equals(queryKey) && values[i].equals(queryValue)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Utility function to set a value in a LogStatement.
+ *
+ * A LogStatement is really just a template -- it does not contain the values, only the
+ * keys. So the values must be passed in as an argument.
+ *
+ * @param queryKey the String that is tested by {@code String.equals()} to the keys in the
+ * LogStatement
+ * @param values the array of values corresponding to mKeys
+ * @param newValue the replacement value to go into the {@code values} array
+ *
+ * @returns {@true} if the key exists and the value was successfully set, {@false} otherwise
+ *
+ * @throws IllegalArgumentException if {@code values.length} is not equal to keys().length()
+ */
+ public boolean setValue(final String queryKey, final Object[] values, final Object newValue) {
+ if (mKeys.length != values.length) {
+ throw new IllegalArgumentException("Mismatched number of keys and values.");
+ }
+ final int length = mKeys.length;
+ for (int i = 0; i < length; i++) {
+ if (mKeys[i].equals(queryKey)) {
+ values[i] = newValue;
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Write the contents out through jsonWriter.
+ *
+ * The JsonWriter class must have already had {@code JsonWriter.beginArray} called on it.
+ *
+ * Note that this method is not thread safe for the same jsonWriter. Callers must ensure
+ * thread safety.
+ */
+ public boolean outputToLocked(final JsonWriter jsonWriter, final Long time,
+ final Object... values) {
+ if (DEBUG) {
+ if (mKeys.length != values.length) {
+ Log.d(TAG, "Key and Value list sizes do not match. " + mType);
+ }
+ }
+ try {
+ jsonWriter.beginObject();
+ jsonWriter.name(CURRENT_TIME_KEY).value(System.currentTimeMillis());
+ jsonWriter.name(UPTIME_KEY).value(time);
+ jsonWriter.name(EVENT_TYPE_KEY).value(mType);
+ final int length = values.length;
+ for (int i = 0; i < length; i++) {
+ jsonWriter.name(mKeys[i]);
+ final Object value = values[i];
+ if (value instanceof CharSequence) {
+ jsonWriter.value(value.toString());
+ } else if (value instanceof Number) {
+ jsonWriter.value((Number) value);
+ } else if (value instanceof Boolean) {
+ jsonWriter.value((Boolean) value);
+ } else if (value instanceof CompletionInfo[]) {
+ JsonUtils.writeJson((CompletionInfo[]) value, jsonWriter);
+ } else if (value instanceof SharedPreferences) {
+ JsonUtils.writeJson((SharedPreferences) value, jsonWriter);
+ } else if (value instanceof Key[]) {
+ JsonUtils.writeJson((Key[]) value, jsonWriter);
+ } else if (value instanceof SuggestedWords) {
+ JsonUtils.writeJson((SuggestedWords) value, jsonWriter);
+ } else if (value instanceof MotionEvent) {
+ JsonUtils.writeJson((MotionEvent) value, jsonWriter);
+ } else if (value == null) {
+ jsonWriter.nullValue();
+ } else {
+ if (DEBUG) {
+ Log.w(TAG, "Unrecognized type to be logged: "
+ + (value == null ? "<null>" : value.getClass().getName()));
+ }
+ jsonWriter.nullValue();
+ }
+ }
+ jsonWriter.endObject();
+ } catch (IOException e) {
+ e.printStackTrace();
+ Log.w(TAG, "Error in JsonWriter; skipping LogStatement");
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/LogUnit.java b/java/src/com/android/inputmethod/research/LogUnit.java
index d8b3a29ff..e91976a03 100644
--- a/java/src/com/android/inputmethod/research/LogUnit.java
+++ b/java/src/com/android/inputmethod/research/LogUnit.java
@@ -1,24 +1,35 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
-import com.android.inputmethod.latin.CollectionUtils;
+import android.content.SharedPreferences;
+import android.os.SystemClock;
+import android.text.TextUtils;
+import android.util.JsonWriter;
+import android.util.Log;
+import com.android.inputmethod.latin.SuggestedWords;
+import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
+import com.android.inputmethod.latin.define.ProductionFlag;
+
+import java.io.IOException;
+import java.io.StringWriter;
import java.util.ArrayList;
+import java.util.List;
/**
* A group of log statements related to each other.
@@ -35,29 +46,200 @@ import java.util.ArrayList;
* been published recently, or whether the LogUnit contains numbers, etc.
*/
/* package */ class LogUnit {
- private final ArrayList<String[]> mKeysList = CollectionUtils.newArrayList();
- private final ArrayList<Object[]> mValuesList = CollectionUtils.newArrayList();
- private final ArrayList<Boolean> mIsPotentiallyPrivate = CollectionUtils.newArrayList();
+ private static final String TAG = LogUnit.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+
+ private final ArrayList<LogStatement> mLogStatementList;
+ private final ArrayList<Object[]> mValuesList;
+ // Assume that mTimeList is sorted in increasing order. Do not insert null values into
+ // mTimeList.
+ private final ArrayList<Long> mTimeList;
+ // Word that this LogUnit generates. Should be null if the LogUnit does not generate a genuine
+ // word (i.e. separators alone do not count as a word). Should never be empty.
private String mWord;
- private boolean mContainsDigit;
+ private boolean mMayContainDigit;
+ private boolean mIsPartOfMegaword;
+ private boolean mContainsCorrection;
+
+ // mCorrectionType indicates whether the word was corrected at all, and if so, whether it was
+ // to a different word or just a "typo" correction. It is considered a "typo" if the final
+ // word was listed in the suggestions available the first time the word was gestured or
+ // tapped.
+ private int mCorrectionType;
+ public static final int CORRECTIONTYPE_NO_CORRECTION = 0;
+ public static final int CORRECTIONTYPE_CORRECTION = 1;
+ public static final int CORRECTIONTYPE_DIFFERENT_WORD = 2;
+ public static final int CORRECTIONTYPE_TYPO = 3;
- public void addLogStatement(final String[] keys, final Object[] values,
- final Boolean isPotentiallyPrivate) {
- mKeysList.add(keys);
+ private SuggestedWords mSuggestedWords;
+
+ public LogUnit() {
+ mLogStatementList = new ArrayList<LogStatement>();
+ mValuesList = new ArrayList<Object[]>();
+ mTimeList = new ArrayList<Long>();
+ mIsPartOfMegaword = false;
+ mCorrectionType = CORRECTIONTYPE_NO_CORRECTION;
+ mSuggestedWords = null;
+ }
+
+ private LogUnit(final ArrayList<LogStatement> logStatementList,
+ final ArrayList<Object[]> valuesList,
+ final ArrayList<Long> timeList,
+ final boolean isPartOfMegaword) {
+ mLogStatementList = logStatementList;
+ mValuesList = valuesList;
+ mTimeList = timeList;
+ mIsPartOfMegaword = isPartOfMegaword;
+ mCorrectionType = CORRECTIONTYPE_NO_CORRECTION;
+ mSuggestedWords = null;
+ }
+
+ private static final Object[] NULL_VALUES = new Object[0];
+ /**
+ * Adds a new log statement. The time parameter in successive calls to this method must be
+ * monotonically increasing, or splitByTime() will not work.
+ */
+ public void addLogStatement(final LogStatement logStatement, final long time,
+ Object... values) {
+ if (values == null) {
+ values = NULL_VALUES;
+ }
+ mLogStatementList.add(logStatement);
mValuesList.add(values);
- mIsPotentiallyPrivate.add(isPotentiallyPrivate);
+ mTimeList.add(time);
}
- public void publishTo(final ResearchLog researchLog, final boolean isIncludingPrivateData) {
- final int size = mKeysList.size();
- for (int i = 0; i < size; i++) {
- if (!mIsPotentiallyPrivate.get(i) || isIncludingPrivateData) {
- researchLog.outputEvent(mKeysList.get(i), mValuesList.get(i));
+ /**
+ * Publish the contents of this LogUnit to {@code researchLog}.
+ *
+ * For each publishable {@code LogStatement}, invoke {@link LogStatement#outputToLocked}.
+ *
+ * @param researchLog where to publish the contents of this {@code LogUnit}
+ * @param canIncludePrivateData whether the private data in this {@code LogUnit} should be
+ * included
+ */
+ public synchronized void publishTo(final ResearchLog researchLog,
+ final boolean canIncludePrivateData) {
+ // Prepare debugging output if necessary
+ final StringWriter debugStringWriter;
+ final JsonWriter debugJsonWriter;
+ if (DEBUG) {
+ debugStringWriter = new StringWriter();
+ debugJsonWriter = new JsonWriter(debugStringWriter);
+ debugJsonWriter.setIndent(" ");
+ try {
+ debugJsonWriter.beginArray();
+ } catch (IOException e) {
+ Log.e(TAG, "Could not open array in JsonWriter", e);
+ }
+ } else {
+ debugStringWriter = null;
+ debugJsonWriter = null;
+ }
+ // Write out any logStatement that passes the privacy filter.
+ final int size = mLogStatementList.size();
+ if (size != 0) {
+ // Note that jsonWriter is only set to a non-null value if the logUnit start text is
+ // output and at least one logStatement is output.
+ JsonWriter jsonWriter = null;
+ for (int i = 0; i < size; i++) {
+ final LogStatement logStatement = mLogStatementList.get(i);
+ if (!canIncludePrivateData && logStatement.isPotentiallyPrivate()) {
+ continue;
+ }
+ if (mIsPartOfMegaword && logStatement.isPotentiallyRevealing()) {
+ continue;
+ }
+ // Only retrieve the jsonWriter if we need to. If we don't get this far, then
+ // researchLog.getInitializedJsonWriterLocked() will not ever be called, and the
+ // file will not have been opened for writing.
+ if (jsonWriter == null) {
+ jsonWriter = researchLog.getInitializedJsonWriterLocked();
+ outputLogUnitStart(jsonWriter, canIncludePrivateData);
+ }
+ logStatement.outputToLocked(jsonWriter, mTimeList.get(i), mValuesList.get(i));
+ if (DEBUG) {
+ logStatement.outputToLocked(debugJsonWriter, mTimeList.get(i),
+ mValuesList.get(i));
+ }
}
+ if (jsonWriter != null) {
+ // We must have called logUnitStart earlier, so emit a logUnitStop.
+ outputLogUnitStop(jsonWriter);
+ }
+ }
+ if (DEBUG) {
+ try {
+ debugJsonWriter.endArray();
+ debugJsonWriter.flush();
+ } catch (IOException e) {
+ Log.e(TAG, "Could not close array in JsonWriter", e);
+ }
+ final String bigString = debugStringWriter.getBuffer().toString();
+ final String[] lines = bigString.split("\n");
+ for (String line : lines) {
+ Log.d(TAG, line);
+ }
+ }
+ }
+
+ private static final String WORD_KEY = "_wo";
+ private static final String CORRECTION_TYPE_KEY = "_corType";
+ private static final String LOG_UNIT_BEGIN_KEY = "logUnitStart";
+ private static final String LOG_UNIT_END_KEY = "logUnitEnd";
+
+ final LogStatement LOGSTATEMENT_LOG_UNIT_BEGIN_WITH_PRIVATE_DATA =
+ new LogStatement(LOG_UNIT_BEGIN_KEY, false /* isPotentiallyPrivate */,
+ false /* isPotentiallyRevealing */, WORD_KEY, CORRECTION_TYPE_KEY);
+ final LogStatement LOGSTATEMENT_LOG_UNIT_BEGIN_WITHOUT_PRIVATE_DATA =
+ new LogStatement(LOG_UNIT_BEGIN_KEY, false /* isPotentiallyPrivate */,
+ false /* isPotentiallyRevealing */);
+ private void outputLogUnitStart(final JsonWriter jsonWriter,
+ final boolean canIncludePrivateData) {
+ final LogStatement logStatement;
+ if (canIncludePrivateData) {
+ LOGSTATEMENT_LOG_UNIT_BEGIN_WITH_PRIVATE_DATA.outputToLocked(jsonWriter,
+ SystemClock.uptimeMillis(), getWord(), getCorrectionType());
+ } else {
+ LOGSTATEMENT_LOG_UNIT_BEGIN_WITHOUT_PRIVATE_DATA.outputToLocked(jsonWriter,
+ SystemClock.uptimeMillis());
}
}
- public void setWord(String word) {
+ final LogStatement LOGSTATEMENT_LOG_UNIT_END =
+ new LogStatement(LOG_UNIT_END_KEY, false /* isPotentiallyPrivate */,
+ false /* isPotentiallyRevealing */);
+ private void outputLogUnitStop(final JsonWriter jsonWriter) {
+ LOGSTATEMENT_LOG_UNIT_END.outputToLocked(jsonWriter, SystemClock.uptimeMillis());
+ }
+
+ /**
+ * Mark the current logUnit as containing data to generate {@code word}.
+ *
+ * If {@code setWord()} was previously called for this LogUnit, then the method will try to
+ * determine what kind of correction it is, and update its internal state of the correctionType
+ * accordingly.
+ *
+ * @param word The word this LogUnit generates. Caller should not pass null or the empty
+ * string.
+ */
+ public void setWord(final String word) {
+ if (hasWord()) {
+ // The word was already set once, and it is now being changed. See if the new word
+ // is close to the old word. If so, then the change is probably a typo correction.
+ // If not, the user may have decided to enter a different word, so flag it.
+ if (mSuggestedWords != null) {
+ if (isInSuggestedWords(word, mSuggestedWords)) {
+ mCorrectionType = CORRECTIONTYPE_TYPO;
+ } else {
+ mCorrectionType = CORRECTIONTYPE_DIFFERENT_WORD;
+ }
+ } else {
+ // No suggested words, so it's not clear whether it's a typo or different word.
+ // Mark it as a generic correction.
+ mCorrectionType = CORRECTIONTYPE_CORRECTION;
+ }
+ }
mWord = word;
}
@@ -66,18 +248,234 @@ import java.util.ArrayList;
}
public boolean hasWord() {
- return mWord != null;
+ return mWord != null && !TextUtils.isEmpty(mWord.trim());
+ }
+
+ public void setMayContainDigit() {
+ mMayContainDigit = true;
+ }
+
+ public boolean mayContainDigit() {
+ return mMayContainDigit;
+ }
+
+ public void setContainsCorrection() {
+ mContainsCorrection = true;
+ }
+
+ public boolean containsCorrection() {
+ return mContainsCorrection;
}
- public void setContainsDigit() {
- mContainsDigit = true;
+ public void setCorrectionType(final int correctionType) {
+ mCorrectionType = correctionType;
}
- public boolean hasDigit() {
- return mContainsDigit;
+ public int getCorrectionType() {
+ return mCorrectionType;
}
public boolean isEmpty() {
- return mKeysList.isEmpty();
+ return mLogStatementList.isEmpty();
+ }
+
+ /**
+ * Split this logUnit, with all events before maxTime staying in the current logUnit, and all
+ * events after maxTime going into a new LogUnit that is returned.
+ */
+ public LogUnit splitByTime(final long maxTime) {
+ // Assume that mTimeList is in sorted order.
+ final int length = mTimeList.size();
+ // TODO: find time by binary search, e.g. using Collections#binarySearch()
+ for (int index = 0; index < length; index++) {
+ if (mTimeList.get(index) > maxTime) {
+ final List<LogStatement> laterLogStatements =
+ mLogStatementList.subList(index, length);
+ final List<Object[]> laterValues = mValuesList.subList(index, length);
+ final List<Long> laterTimes = mTimeList.subList(index, length);
+
+ // Create the LogUnit containing the later logStatements and associated data.
+ final LogUnit newLogUnit = new LogUnit(
+ new ArrayList<LogStatement>(laterLogStatements),
+ new ArrayList<Object[]>(laterValues),
+ new ArrayList<Long>(laterTimes),
+ true /* isPartOfMegaword */);
+ newLogUnit.mWord = null;
+ newLogUnit.mMayContainDigit = mMayContainDigit;
+ newLogUnit.mContainsCorrection = mContainsCorrection;
+
+ // Purge the logStatements and associated data from this LogUnit.
+ laterLogStatements.clear();
+ laterValues.clear();
+ laterTimes.clear();
+ mIsPartOfMegaword = true;
+
+ return newLogUnit;
+ }
+ }
+ return new LogUnit();
+ }
+
+ public void append(final LogUnit logUnit) {
+ mLogStatementList.addAll(logUnit.mLogStatementList);
+ mValuesList.addAll(logUnit.mValuesList);
+ mTimeList.addAll(logUnit.mTimeList);
+ mWord = null;
+ if (logUnit.mWord != null) {
+ setWord(logUnit.mWord);
+ }
+ mMayContainDigit = mMayContainDigit || logUnit.mMayContainDigit;
+ mContainsCorrection = mContainsCorrection || logUnit.mContainsCorrection;
+ mIsPartOfMegaword = false;
+ }
+
+ public SuggestedWords getSuggestions() {
+ return mSuggestedWords;
+ }
+
+ /**
+ * Initialize the suggestions.
+ *
+ * Once set to a non-null value, the suggestions may not be changed again. This is to keep
+ * track of the list of words that are close to the user's initial effort to type the word.
+ * Only words that are close to the initial effort are considered typo corrections.
+ */
+ public void initializeSuggestions(final SuggestedWords suggestedWords) {
+ if (mSuggestedWords == null) {
+ mSuggestedWords = suggestedWords;
+ }
+ }
+
+ private static boolean isInSuggestedWords(final String queryWord,
+ final SuggestedWords suggestedWords) {
+ if (TextUtils.isEmpty(queryWord)) {
+ return false;
+ }
+ final int size = suggestedWords.size();
+ for (int i = 0; i < size; i++) {
+ final SuggestedWordInfo wordInfo = suggestedWords.getInfo(i);
+ if (queryWord.equals(wordInfo.mWord)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Remove data associated with selecting the Research button.
+ *
+ * A LogUnit will capture all user interactions with the IME, including the "meta-interactions"
+ * of using the Research button to control the logging (e.g. by starting and stopping recording
+ * of a test case). Because meta-interactions should not be part of the normal log, calling
+ * this method will set a field in the LogStatements of the motion events to indiciate that
+ * they should be disregarded.
+ *
+ * This implementation assumes that the data recorded by the meta-interaction takes the
+ * form of all events following the first MotionEvent.ACTION_DOWN before the first long-press
+ * before the last onCodeEvent containing a code matching {@code LogStatement.VALUE_RESEARCH}.
+ *
+ * @returns true if data was removed
+ */
+ public boolean removeResearchButtonInvocation() {
+ // This method is designed to be idempotent.
+
+ // First, find last invocation of "research" key
+ final int indexOfLastResearchKey = findLastIndexContainingKeyValue(
+ LogStatement.TYPE_POINTER_TRACKER_CALL_LISTENER_ON_CODE_INPUT,
+ LogStatement.KEY_CODE, LogStatement.VALUE_RESEARCH);
+ if (indexOfLastResearchKey < 0) {
+ // Could not find invocation of "research" key. Leave log as is.
+ if (DEBUG) {
+ Log.d(TAG, "Could not find research key");
+ }
+ return false;
+ }
+
+ // Look for the long press that started the invocation of the research key code input.
+ final int indexOfLastLongPressBeforeResearchKey =
+ findLastIndexBefore(LogStatement.TYPE_MAIN_KEYBOARD_VIEW_ON_LONG_PRESS,
+ indexOfLastResearchKey);
+
+ // Look for DOWN event preceding the long press
+ final int indexOfLastDownEventBeforeLongPress =
+ findLastIndexContainingKeyValueBefore(LogStatement.TYPE_MOTION_EVENT,
+ LogStatement.ACTION, LogStatement.VALUE_DOWN,
+ indexOfLastLongPressBeforeResearchKey);
+
+ // Flag all LatinKeyboardViewProcessMotionEvents from the DOWN event to the research key as
+ // logging-related
+ final int startingIndex = indexOfLastDownEventBeforeLongPress == -1 ? 0
+ : indexOfLastDownEventBeforeLongPress;
+ for (int index = startingIndex; index < indexOfLastResearchKey; index++) {
+ final LogStatement logStatement = mLogStatementList.get(index);
+ final String type = logStatement.getType();
+ final Object[] values = mValuesList.get(index);
+ if (type.equals(LogStatement.TYPE_MOTION_EVENT)) {
+ logStatement.setValue(LogStatement.KEY_IS_LOGGING_RELATED, values, true);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Find the index of the last LogStatement before {@code startingIndex} of type {@code type}.
+ *
+ * @param queryType a String that must be {@code String.equals()} to the LogStatement type
+ * @param startingIndex the index to start the backward search from. Must be less than the
+ * length of mLogStatementList, or an IndexOutOfBoundsException is thrown. Can be negative,
+ * in which case -1 is returned.
+ *
+ * @return The index of the last LogStatement, -1 if none exists.
+ */
+ private int findLastIndexBefore(final String queryType, final int startingIndex) {
+ return findLastIndexContainingKeyValueBefore(queryType, null, null, startingIndex);
+ }
+
+ /**
+ * Find the index of the last LogStatement before {@code startingIndex} of type {@code type}
+ * containing the given key-value pair.
+ *
+ * @param queryType a String that must be {@code String.equals()} to the LogStatement type
+ * @param queryKey a String that must be {@code String.equals()} to a key in the LogStatement
+ * @param queryValue an Object that must be {@code String.equals()} to the key's corresponding
+ * value
+ *
+ * @return The index of the last LogStatement, -1 if none exists.
+ */
+ private int findLastIndexContainingKeyValue(final String queryType, final String queryKey,
+ final Object queryValue) {
+ return findLastIndexContainingKeyValueBefore(queryType, queryKey, queryValue,
+ mLogStatementList.size() - 1);
+ }
+
+ /**
+ * Find the index of the last LogStatement before {@code startingIndex} of type {@code type}
+ * containing the given key-value pair.
+ *
+ * @param queryType a String that must be {@code String.equals()} to the LogStatement type
+ * @param queryKey a String that must be {@code String.equals()} to a key in the LogStatement
+ * @param queryValue an Object that must be {@code String.equals()} to the key's corresponding
+ * value
+ * @param startingIndex the index to start the backward search from. Must be less than the
+ * length of mLogStatementList, or an IndexOutOfBoundsException is thrown. Can be negative,
+ * in which case -1 is returned.
+ *
+ * @return The index of the last LogStatement, -1 if none exists.
+ */
+ private int findLastIndexContainingKeyValueBefore(final String queryType, final String queryKey,
+ final Object queryValue, final int startingIndex) {
+ if (startingIndex < 0) {
+ return -1;
+ }
+ for (int index = startingIndex; index >= 0; index--) {
+ final LogStatement logStatement = mLogStatementList.get(index);
+ final String type = logStatement.getType();
+ if (type.equals(queryType) && (queryKey == null
+ || logStatement.containsKeyValuePair(queryKey, queryValue,
+ mValuesList.get(index)))) {
+ return index;
+ }
+ }
+ return -1;
}
}
diff --git a/java/src/com/android/inputmethod/research/LoggingUtils.java b/java/src/com/android/inputmethod/research/LoggingUtils.java
new file mode 100644
index 000000000..1261d6780
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/LoggingUtils.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2013 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.research;
+
+import android.view.MotionEvent;
+
+/* package */ class LoggingUtils {
+ private LoggingUtils() {
+ // This utility class is not publicly instantiable.
+ }
+
+ /* package */ static String getMotionEventActionTypeString(final int actionType) {
+ switch (actionType) {
+ case MotionEvent.ACTION_CANCEL: return "CANCEL";
+ case MotionEvent.ACTION_UP: return "UP";
+ case MotionEvent.ACTION_DOWN: return "DOWN";
+ case MotionEvent.ACTION_POINTER_UP: return "POINTER_UP";
+ case MotionEvent.ACTION_POINTER_DOWN: return "POINTER_DOWN";
+ case MotionEvent.ACTION_MOVE: return "MOVE";
+ case MotionEvent.ACTION_OUTSIDE: return "OUTSIDE";
+ default: return "ACTION_" + actionType;
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/MainLogBuffer.java b/java/src/com/android/inputmethod/research/MainLogBuffer.java
index 745768d35..45b83dd76 100644
--- a/java/src/com/android/inputmethod/research/MainLogBuffer.java
+++ b/java/src/com/android/inputmethod/research/MainLogBuffer.java
@@ -1,75 +1,104 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
+import android.util.Log;
+
import com.android.inputmethod.latin.Dictionary;
import com.android.inputmethod.latin.Suggest;
+import com.android.inputmethod.latin.define.ProductionFlag;
+import java.util.ArrayList;
+import java.util.LinkedList;
import java.util.Random;
-public class MainLogBuffer extends LogBuffer {
+/**
+ * MainLogBuffer is a FixedLogBuffer that tracks the state of LogUnits to make privacy guarantees.
+ *
+ * There are three forms of privacy protection: 1) only words in the main dictionary are allowed to
+ * be logged in enough detail to determine their contents, 2) only a subset of words are logged
+ * in detail, such as 10%, and 3) no numbers are logged.
+ *
+ * This class maintains a list of LogUnits, each corresponding to a word. As the user completes
+ * words, they are added here. But if the user backs up over their current word to edit a word
+ * entered earlier, then it is pulled out of this LogBuffer, changes are then added to the end of
+ * the LogUnit, and it is pushed back in here when the user is done. Because words may be pulled
+ * back out even after they are pushed in, we must not publish the contents of this LogBuffer too
+ * quickly. However, we cannot let the contents pile up either, or it will limit the editing that
+ * a user can perform.
+ *
+ * To balance these requirements (keep history so user can edit, flush history so it does not pile
+ * up), the LogBuffer is considered "complete" when the user has entered enough words to form an
+ * n-gram, followed by enough additional non-detailed words (that are in the 90%, as per above).
+ * Once complete, the n-gram may be published to flash storage (via the ResearchLog class).
+ * However, the additional non-detailed words are retained, in case the user backspaces to edit
+ * them. The MainLogBuffer then continues to add words, publishing individual non-detailed words
+ * as new words arrive. After enough non-detailed words have been pushed out to account for the
+ * 90% between words, the words at the front of the LogBuffer can be published as an n-gram again.
+ *
+ * If the words that would form the valid n-gram are not in the dictionary, then words are pushed
+ * through the LogBuffer one at a time until an n-gram is found that is entirely composed of
+ * dictionary words.
+ *
+ * If the user closes a session, then the entire LogBuffer is flushed, publishing any embedded
+ * n-gram containing dictionary words.
+ */
+public abstract class MainLogBuffer extends FixedLogBuffer {
+ private static final String TAG = MainLogBuffer.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+
// The size of the n-grams logged. E.g. N_GRAM_SIZE = 2 means to sample bigrams.
- private static final int N_GRAM_SIZE = 2;
- // The number of words between n-grams to omit from the log.
- private static final int DEFAULT_NUMBER_OF_WORDS_BETWEEN_SAMPLES = 18;
+ public static final int N_GRAM_SIZE = 2;
- private final ResearchLog mResearchLog;
private Suggest mSuggest;
+ private boolean mIsStopping = false;
- // The minimum periodicity with which n-grams can be sampled. E.g. mWinWordPeriod is 10 if
- // every 10th bigram is sampled, i.e., words 1-8 are not, but the bigram at words 9 and 10, etc.
- // for 11-18, and the bigram at words 19 and 20. If an n-gram is not safe (e.g. it contains a
- // number in the middle or an out-of-vocabulary word), then sampling is delayed until a safe
- // n-gram does appear.
- /* package for test */ int mMinWordPeriod;
+ /* package for test */ int mNumWordsBetweenNGrams;
// Counter for words left to suppress before an n-gram can be sampled. Reset to mMinWordPeriod
// after a sample is taken.
- /* package for test */ int mWordsUntilSafeToSample;
-
- public MainLogBuffer(final ResearchLog researchLog) {
- super(N_GRAM_SIZE);
- mResearchLog = researchLog;
- mMinWordPeriod = DEFAULT_NUMBER_OF_WORDS_BETWEEN_SAMPLES + N_GRAM_SIZE;
- final Random random = new Random();
- mWordsUntilSafeToSample = random.nextInt(mMinWordPeriod);
+ /* package for test */ int mNumWordsUntilSafeToSample;
+
+ public MainLogBuffer(final int wordsBetweenSamples, final int numInitialWordsToIgnore) {
+ super(N_GRAM_SIZE + wordsBetweenSamples);
+ mNumWordsBetweenNGrams = wordsBetweenSamples;
+ mNumWordsUntilSafeToSample = DEBUG ? 0 : numInitialWordsToIgnore;
}
- public void setSuggest(Suggest suggest) {
+ public void setSuggest(final Suggest suggest) {
mSuggest = suggest;
}
- @Override
- public void shiftIn(final LogUnit newLogUnit) {
- super.shiftIn(newLogUnit);
- if (newLogUnit.hasWord()) {
- if (mWordsUntilSafeToSample > 0) {
- mWordsUntilSafeToSample--;
- }
- }
+ private Dictionary getDictionary() {
+ if (mSuggest == null || !mSuggest.hasMainDictionary()) return null;
+ return mSuggest.getMainDictionary();
}
public void resetWordCounter() {
- mWordsUntilSafeToSample = mMinWordPeriod;
+ mNumWordsUntilSafeToSample = mNumWordsBetweenNGrams;
+ }
+
+ public void setIsStopping() {
+ mIsStopping = true;
}
/**
- * Determines whether the content of the MainLogBuffer can be safely uploaded in its complete
- * form and still protect the user's privacy.
+ * Determines whether uploading the n words at the front the MainLogBuffer will not violate
+ * user privacy.
*
* The size of the MainLogBuffer is just enough to hold one n-gram, its corrections, and any
* non-character data that is typed between words. The decision about privacy is made based on
@@ -78,50 +107,118 @@ public class MainLogBuffer extends LogBuffer {
* the screen orientation and other characteristics about the device can be uploaded without
* revealing much about the user.
*/
- public boolean isSafeToLog() {
+ private boolean isSafeNGram(final ArrayList<LogUnit> logUnits, final int minNGramSize) {
+ // Bypass privacy checks when debugging.
+ if (ResearchLogger.IS_LOGGING_EVERYTHING) {
+ if (mIsStopping) {
+ return true;
+ }
+ // Only check that it is the right length. If not, wait for later words to make
+ // complete n-grams.
+ int numWordsInLogUnitList = 0;
+ final int length = logUnits.size();
+ for (int i = 0; i < length; i++) {
+ final LogUnit logUnit = logUnits.get(i);
+ final String word = logUnit.getWord();
+ if (word != null) {
+ numWordsInLogUnitList++;
+ }
+ }
+ return numWordsInLogUnitList >= minNGramSize;
+ }
+
// Check that we are not sampling too frequently. Having sampled recently might disclose
// too much of the user's intended meaning.
- if (mWordsUntilSafeToSample > 0) {
- return false;
- }
- if (mSuggest == null || !mSuggest.hasMainDictionary()) {
- // Main dictionary is unavailable. Since we cannot check it, we cannot tell if a word
- // is out-of-vocabulary or not. Therefore, we must judge the entire buffer contents to
- // potentially pose a privacy risk.
+ if (mNumWordsUntilSafeToSample > 0) {
return false;
}
// Reload the dictionary in case it has changed (e.g., because the user has changed
// languages).
- final Dictionary dictionary = mSuggest.getMainDictionary();
+ final Dictionary dictionary = getDictionary();
if (dictionary == null) {
+ // Main dictionary is unavailable. Since we cannot check it, we cannot tell if a
+ // word is out-of-vocabulary or not. Therefore, we must judge the entire buffer
+ // contents to potentially pose a privacy risk.
return false;
}
- // Check each word in the buffer. If any word poses a privacy threat, we cannot upload the
- // complete buffer contents in detail.
- final int length = mLogUnits.size();
+
+ // Check each word in the buffer. If any word poses a privacy threat, we cannot upload
+ // the complete buffer contents in detail.
+ int numWordsInLogUnitList = 0;
+ final int length = logUnits.size();
for (int i = 0; i < length; i++) {
- final LogUnit logUnit = mLogUnits.get(i);
- final String word = logUnit.getWord();
- if (word == null) {
+ final LogUnit logUnit = logUnits.get(i);
+ if (!logUnit.hasWord()) {
// Digits outside words are a privacy threat.
- if (logUnit.hasDigit()) {
+ if (logUnit.mayContainDigit()) {
return false;
}
} else {
+ numWordsInLogUnitList++;
+ final String word = logUnit.getWord();
// Words not in the dictionary are a privacy threat.
- if (!(dictionary.isValidWord(word))) {
+ if (ResearchLogger.hasLetters(word) && !(dictionary.isValidWord(word))) {
+ if (DEBUG) {
+ Log.d(TAG, "NOT SAFE!: hasLetters: " + ResearchLogger.hasLetters(word)
+ + ", isValid: " + (dictionary.isValidWord(word)));
+ }
return false;
}
}
}
- // All checks have passed; this buffer's content can be safely uploaded.
- return true;
+
+ // Finally, only return true if the minNGramSize is met.
+ return numWordsInLogUnitList >= minNGramSize;
+ }
+
+ public void shiftAndPublishAll() {
+ final LinkedList<LogUnit> logUnits = getLogUnits();
+ while (!logUnits.isEmpty()) {
+ publishLogUnitsAtFrontOfBuffer();
+ }
+ }
+
+ @Override
+ protected final void onBufferFull() {
+ publishLogUnitsAtFrontOfBuffer();
+ }
+
+ protected final void publishLogUnitsAtFrontOfBuffer() {
+ ArrayList<LogUnit> logUnits = peekAtFirstNWords(N_GRAM_SIZE);
+ if (isSafeNGram(logUnits, N_GRAM_SIZE)) {
+ // Good n-gram at the front of the buffer. Publish it, disclosing details.
+ publish(logUnits, true /* canIncludePrivateData */);
+ shiftOutWords(N_GRAM_SIZE);
+ resetWordCounter();
+ } else {
+ // No good n-gram at front, and buffer is full. Shift out the first word (or if there
+ // is none, the existing logUnits).
+ logUnits = peekAtFirstNWords(1);
+ publish(logUnits, false /* canIncludePrivateData */);
+ shiftOutWords(1);
+ }
}
+ /**
+ * Called when a list of logUnits should be published.
+ *
+ * It is the subclass's responsibility to implement the publication.
+ *
+ * @param logUnits The list of logUnits to be published.
+ * @param canIncludePrivateData Whether the private data in the logUnits can be included in
+ * publication.
+ */
+ protected abstract void publish(final ArrayList<LogUnit> logUnits,
+ final boolean canIncludePrivateData);
+
@Override
- protected void onShiftOut(LogUnit logUnit) {
- if (mResearchLog != null) {
- mResearchLog.publish(logUnit, false /* isIncludingPrivateData */);
+ protected void shiftOutWords(final int numWords) {
+ final int oldNumActualWords = getNumActualWords();
+ super.shiftOutWords(numWords);
+ final int numWordsShifted = oldNumActualWords - getNumActualWords();
+ mNumWordsUntilSafeToSample -= numWordsShifted;
+ if (DEBUG) {
+ Log.d(TAG, "wordsUntilSafeToSample now at " + mNumWordsUntilSafeToSample);
}
}
}
diff --git a/java/src/com/android/inputmethod/research/MotionEventReader.java b/java/src/com/android/inputmethod/research/MotionEventReader.java
new file mode 100644
index 000000000..e59adfa19
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/MotionEventReader.java
@@ -0,0 +1,332 @@
+/*
+ * Copyright (C) 2013 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.research;
+
+import android.util.JsonReader;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.MotionEvent.PointerCoords;
+import android.view.MotionEvent.PointerProperties;
+
+import com.android.inputmethod.latin.define.ProductionFlag;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+
+public class MotionEventReader {
+ private static final String TAG = MotionEventReader.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ // Assumes that MotionEvent.ACTION_MASK does not have all bits set.`
+ private static final int UNINITIALIZED_ACTION = ~MotionEvent.ACTION_MASK;
+ // No legitimate int is negative
+ private static final int UNINITIALIZED_INT = -1;
+ // No legitimate long is negative
+ private static final long UNINITIALIZED_LONG = -1L;
+ // No legitimate float is negative
+ private static final float UNINITIALIZED_FLOAT = -1.0f;
+
+ public ReplayData readMotionEventData(final File file) {
+ final ReplayData replayData = new ReplayData();
+ try {
+ // Read file
+ final JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(
+ new FileInputStream(file))));
+ jsonReader.beginArray();
+ while (jsonReader.hasNext()) {
+ readLogStatement(jsonReader, replayData);
+ }
+ jsonReader.endArray();
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return replayData;
+ }
+
+ static class ReplayData {
+ final ArrayList<Integer> mActions = new ArrayList<Integer>();
+ final ArrayList<PointerProperties[]> mPointerPropertiesArrays
+ = new ArrayList<PointerProperties[]>();
+ final ArrayList<PointerCoords[]> mPointerCoordsArrays = new ArrayList<PointerCoords[]>();
+ final ArrayList<Long> mTimes = new ArrayList<Long>();
+ }
+
+ /**
+ * Read motion data from a logStatement and store it in {@code replayData}.
+ *
+ * Two kinds of logStatements can be read. In the first variant, the MotionEvent data is
+ * represented as attributes at the top level like so:
+ *
+ * <pre>
+ * {
+ * "_ct": 1359590400000,
+ * "_ut": 4381933,
+ * "_ty": "MotionEvent",
+ * "action": "UP",
+ * "isLoggingRelated": false,
+ * "x": 100,
+ * "y": 200
+ * }
+ * </pre>
+ *
+ * In the second variant, there is a separate attribute for the MotionEvent that includes
+ * historical data if present:
+ *
+ * <pre>
+ * {
+ * "_ct": 135959040000,
+ * "_ut": 4382702,
+ * "_ty": "MotionEvent",
+ * "action": "MOVE",
+ * "isLoggingRelated": false,
+ * "motionEvent": {
+ * "pointerIds": [
+ * 0
+ * ],
+ * "xyt": [
+ * {
+ * "t": 4382551,
+ * "d": [
+ * {
+ * "x": 141.25,
+ * "y": 151.8485107421875,
+ * "toma": 101.82337188720703,
+ * "tomi": 101.82337188720703,
+ * "o": 0.0
+ * }
+ * ]
+ * },
+ * {
+ * "t": 4382559,
+ * "d": [
+ * {
+ * "x": 140.7266082763672,
+ * "y": 151.8485107421875,
+ * "toma": 101.82337188720703,
+ * "tomi": 101.82337188720703,
+ * "o": 0.0
+ * }
+ * ]
+ * }
+ * ]
+ * }
+ * },
+ * </pre>
+ */
+ /* package for test */ void readLogStatement(final JsonReader jsonReader,
+ final ReplayData replayData) throws IOException {
+ String logStatementType = null;
+ int actionType = UNINITIALIZED_ACTION;
+ int x = UNINITIALIZED_INT;
+ int y = UNINITIALIZED_INT;
+ long time = UNINITIALIZED_LONG;
+ boolean isLoggingRelated = false;
+
+ jsonReader.beginObject();
+ while (jsonReader.hasNext()) {
+ final String key = jsonReader.nextName();
+ if (key.equals("_ty")) {
+ logStatementType = jsonReader.nextString();
+ } else if (key.equals("_ut")) {
+ time = jsonReader.nextLong();
+ } else if (key.equals("x")) {
+ x = jsonReader.nextInt();
+ } else if (key.equals("y")) {
+ y = jsonReader.nextInt();
+ } else if (key.equals("action")) {
+ final String s = jsonReader.nextString();
+ if (s.equals("UP")) {
+ actionType = MotionEvent.ACTION_UP;
+ } else if (s.equals("DOWN")) {
+ actionType = MotionEvent.ACTION_DOWN;
+ } else if (s.equals("MOVE")) {
+ actionType = MotionEvent.ACTION_MOVE;
+ }
+ } else if (key.equals("loggingRelated")) {
+ isLoggingRelated = jsonReader.nextBoolean();
+ } else if (logStatementType != null && logStatementType.equals("MotionEvent")
+ && key.equals("motionEvent")) {
+ if (actionType == UNINITIALIZED_ACTION) {
+ Log.e(TAG, "no actionType assigned in MotionEvent json");
+ }
+ // Second variant of LogStatement.
+ if (isLoggingRelated) {
+ jsonReader.skipValue();
+ } else {
+ readEmbeddedMotionEvent(jsonReader, replayData, actionType);
+ }
+ } else {
+ if (DEBUG) {
+ Log.w(TAG, "Unknown JSON key in LogStatement: " + key);
+ }
+ jsonReader.skipValue();
+ }
+ }
+ jsonReader.endObject();
+
+ if (logStatementType != null && time != UNINITIALIZED_LONG && x != UNINITIALIZED_INT
+ && y != UNINITIALIZED_INT && actionType != UNINITIALIZED_ACTION
+ && logStatementType.equals("MotionEvent") && !isLoggingRelated) {
+ // First variant of LogStatement.
+ final PointerProperties pointerProperties = new PointerProperties();
+ pointerProperties.id = 0;
+ pointerProperties.toolType = MotionEvent.TOOL_TYPE_UNKNOWN;
+ final PointerProperties[] pointerPropertiesArray = {
+ pointerProperties
+ };
+ final PointerCoords pointerCoords = new PointerCoords();
+ pointerCoords.x = x;
+ pointerCoords.y = y;
+ pointerCoords.pressure = 1.0f;
+ pointerCoords.size = 1.0f;
+ final PointerCoords[] pointerCoordsArray = {
+ pointerCoords
+ };
+ addMotionEventData(replayData, actionType, time, pointerPropertiesArray,
+ pointerCoordsArray);
+ }
+ }
+
+ private void readEmbeddedMotionEvent(final JsonReader jsonReader, final ReplayData replayData,
+ final int actionType) throws IOException {
+ jsonReader.beginObject();
+ PointerProperties[] pointerPropertiesArray = null;
+ while (jsonReader.hasNext()) { // pointerIds/xyt
+ final String name = jsonReader.nextName();
+ if (name.equals("pointerIds")) {
+ pointerPropertiesArray = readPointerProperties(jsonReader);
+ } else if (name.equals("xyt")) {
+ readPointerData(jsonReader, replayData, actionType, pointerPropertiesArray);
+ }
+ }
+ jsonReader.endObject();
+ }
+
+ private PointerProperties[] readPointerProperties(final JsonReader jsonReader)
+ throws IOException {
+ final ArrayList<PointerProperties> pointerPropertiesArrayList =
+ new ArrayList<PointerProperties>();
+ jsonReader.beginArray();
+ while (jsonReader.hasNext()) {
+ final PointerProperties pointerProperties = new PointerProperties();
+ pointerProperties.id = jsonReader.nextInt();
+ pointerProperties.toolType = MotionEvent.TOOL_TYPE_UNKNOWN;
+ pointerPropertiesArrayList.add(pointerProperties);
+ }
+ jsonReader.endArray();
+ return pointerPropertiesArrayList.toArray(
+ new PointerProperties[pointerPropertiesArrayList.size()]);
+ }
+
+ private void readPointerData(final JsonReader jsonReader, final ReplayData replayData,
+ final int actionType, final PointerProperties[] pointerPropertiesArray)
+ throws IOException {
+ if (pointerPropertiesArray == null) {
+ Log.e(TAG, "PointerIDs must be given before xyt data in json for MotionEvent");
+ jsonReader.skipValue();
+ return;
+ }
+ long time = UNINITIALIZED_LONG;
+ jsonReader.beginArray();
+ while (jsonReader.hasNext()) { // Array of historical data
+ jsonReader.beginObject();
+ final ArrayList<PointerCoords> pointerCoordsArrayList = new ArrayList<PointerCoords>();
+ while (jsonReader.hasNext()) { // Time/data object
+ final String name = jsonReader.nextName();
+ if (name.equals("t")) {
+ time = jsonReader.nextLong();
+ } else if (name.equals("d")) {
+ jsonReader.beginArray();
+ while (jsonReader.hasNext()) { // array of data per pointer
+ final PointerCoords pointerCoords = readPointerCoords(jsonReader);
+ if (pointerCoords != null) {
+ pointerCoordsArrayList.add(pointerCoords);
+ }
+ }
+ jsonReader.endArray();
+ } else {
+ jsonReader.skipValue();
+ }
+ }
+ jsonReader.endObject();
+ // Data was recorded as historical events, but must be split apart into
+ // separate MotionEvents for replaying
+ if (time != UNINITIALIZED_LONG) {
+ addMotionEventData(replayData, actionType, time, pointerPropertiesArray,
+ pointerCoordsArrayList.toArray(
+ new PointerCoords[pointerCoordsArrayList.size()]));
+ } else {
+ Log.e(TAG, "Time not assigned in json for MotionEvent");
+ }
+ }
+ jsonReader.endArray();
+ }
+
+ private PointerCoords readPointerCoords(final JsonReader jsonReader) throws IOException {
+ jsonReader.beginObject();
+ float x = UNINITIALIZED_FLOAT;
+ float y = UNINITIALIZED_FLOAT;
+ while (jsonReader.hasNext()) { // x,y
+ final String name = jsonReader.nextName();
+ if (name.equals("x")) {
+ x = (float) jsonReader.nextDouble();
+ } else if (name.equals("y")) {
+ y = (float) jsonReader.nextDouble();
+ } else {
+ jsonReader.skipValue();
+ }
+ }
+ jsonReader.endObject();
+
+ if (Float.compare(x, UNINITIALIZED_FLOAT) == 0
+ || Float.compare(y, UNINITIALIZED_FLOAT) == 0) {
+ Log.w(TAG, "missing x or y value in MotionEvent json");
+ return null;
+ }
+ final PointerCoords pointerCoords = new PointerCoords();
+ pointerCoords.x = x;
+ pointerCoords.y = y;
+ pointerCoords.pressure = 1.0f;
+ pointerCoords.size = 1.0f;
+ return pointerCoords;
+ }
+
+ /**
+ * Tests that {@code x} is uninitialized.
+ *
+ * Assumes that {@code x} will never be given a valid value less than 0, and that
+ * UNINITIALIZED_FLOAT is less than 0.0f.
+ */
+ private boolean isUninitializedFloat(final float x) {
+ return x < 0.0f;
+ }
+
+ private void addMotionEventData(final ReplayData replayData, final int actionType,
+ final long time, final PointerProperties[] pointerProperties,
+ final PointerCoords[] pointerCoords) {
+ replayData.mActions.add(actionType);
+ replayData.mTimes.add(time);
+ replayData.mPointerPropertiesArrays.add(pointerProperties);
+ replayData.mPointerCoordsArrays.add(pointerCoords);
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/Replayer.java b/java/src/com/android/inputmethod/research/Replayer.java
new file mode 100644
index 000000000..a9b7a9d0c
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/Replayer.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2012 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.research;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+import android.os.SystemClock;
+import android.util.Log;
+import android.view.MotionEvent;
+import android.view.MotionEvent.PointerCoords;
+import android.view.MotionEvent.PointerProperties;
+
+import com.android.inputmethod.keyboard.KeyboardSwitcher;
+import com.android.inputmethod.keyboard.MainKeyboardView;
+import com.android.inputmethod.latin.define.ProductionFlag;
+import com.android.inputmethod.research.MotionEventReader.ReplayData;
+
+/**
+ * Replays a sequence of motion events in realtime on the screen.
+ *
+ * Useful for user inspection of logged data.
+ */
+public class Replayer {
+ private static final String TAG = Replayer.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ private static final long START_TIME_DELAY_MS = 500;
+
+ private boolean mIsReplaying = false;
+ private KeyboardSwitcher mKeyboardSwitcher;
+
+ private Replayer() {
+ }
+
+ private static final Replayer sInstance = new Replayer();
+ public static Replayer getInstance() {
+ return sInstance;
+ }
+
+ public void setKeyboardSwitcher(final KeyboardSwitcher keyboardSwitcher) {
+ mKeyboardSwitcher = keyboardSwitcher;
+ }
+
+ private static final int MSG_MOTION_EVENT = 0;
+ private static final int MSG_DONE = 1;
+ private static final int COMPLETION_TIME_MS = 500;
+
+ // TODO: Support historical events and multi-touch.
+ public void replay(final ReplayData replayData, final Runnable callback) {
+ if (mIsReplaying) {
+ return;
+ }
+ mIsReplaying = true;
+ final int numActions = replayData.mActions.size();
+ if (DEBUG) {
+ Log.d(TAG, "replaying " + numActions + " actions");
+ }
+ if (numActions == 0) {
+ mIsReplaying = false;
+ return;
+ }
+ final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
+
+ // The reference time relative to the times stored in events.
+ final long origStartTime = replayData.mTimes.get(0);
+ // The reference time relative to which events are replayed in the present.
+ final long currentStartTime = SystemClock.uptimeMillis() + START_TIME_DELAY_MS;
+ // The adjustment needed to translate times from the original recorded time to the current
+ // time.
+ final long timeAdjustment = currentStartTime - origStartTime;
+ final Handler handler = new Handler(Looper.getMainLooper()) {
+ // Track the time of the most recent DOWN event, to be passed as a parameter when
+ // constructing a MotionEvent. It's initialized here to the origStartTime, but this is
+ // only a precaution. The value should be overwritten by the first ACTION_DOWN event
+ // before the first use of the variable. Note that this may cause the first few events
+ // to have incorrect {@code downTime}s.
+ private long mOrigDownTime = origStartTime;
+
+ @Override
+ public void handleMessage(final Message msg) {
+ switch (msg.what) {
+ case MSG_MOTION_EVENT:
+ final int index = msg.arg1;
+ final int action = replayData.mActions.get(index);
+ final PointerProperties[] pointerPropertiesArray =
+ replayData.mPointerPropertiesArrays.get(index);
+ final PointerCoords[] pointerCoordsArray =
+ replayData.mPointerCoordsArrays.get(index);
+ final long origTime = replayData.mTimes.get(index);
+ if (action == MotionEvent.ACTION_DOWN) {
+ mOrigDownTime = origTime;
+ }
+
+ final MotionEvent me = MotionEvent.obtain(mOrigDownTime + timeAdjustment,
+ origTime + timeAdjustment, action,
+ pointerPropertiesArray.length, pointerPropertiesArray,
+ pointerCoordsArray, 0, 0, 1.0f, 1.0f, 0, 0, 0, 0);
+ mainKeyboardView.processMotionEvent(me);
+ me.recycle();
+ break;
+ case MSG_DONE:
+ mIsReplaying = false;
+ ResearchLogger.getInstance().requestIndicatorRedraw();
+ break;
+ }
+ }
+ };
+
+ handler.post(new Runnable() {
+ @Override
+ public void run() {
+ ResearchLogger.getInstance().requestIndicatorRedraw();
+ }
+ });
+ for (int i = 0; i < numActions; i++) {
+ final Message msg = Message.obtain(handler, MSG_MOTION_EVENT, i, 0);
+ final long msgTime = replayData.mTimes.get(i) + timeAdjustment;
+ handler.sendMessageAtTime(msg, msgTime);
+ if (DEBUG) {
+ Log.d(TAG, "queuing event at " + msgTime);
+ }
+ }
+
+ final long presentDoneTime = replayData.mTimes.get(numActions - 1) + timeAdjustment
+ + COMPLETION_TIME_MS;
+ handler.sendMessageAtTime(Message.obtain(handler, MSG_DONE), presentDoneTime);
+ if (callback != null) {
+ handler.postAtTime(callback, presentDoneTime + 1);
+ }
+ }
+
+ public boolean isReplaying() {
+ return mIsReplaying;
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/ReplayerService.java b/java/src/com/android/inputmethod/research/ReplayerService.java
new file mode 100644
index 000000000..88d9033cf
--- /dev/null
+++ b/java/src/com/android/inputmethod/research/ReplayerService.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2012 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.research;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.util.Log;
+
+import com.android.inputmethod.research.MotionEventReader.ReplayData;
+
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Provide a mechanism to invoke the replayer from outside.
+ *
+ * In particular, makes access from a host possible through {@code adb am startservice}.
+ */
+public class ReplayerService extends IntentService {
+ private static final String TAG = ReplayerService.class.getSimpleName();
+ private static final String EXTRA_FILENAME = "com.android.inputmethod.research.extra.FILENAME";
+ private static final long MAX_REPLAY_TIME = TimeUnit.SECONDS.toMillis(60);
+
+ public ReplayerService() {
+ super(ReplayerService.class.getSimpleName());
+ }
+
+ @Override
+ protected void onHandleIntent(final Intent intent) {
+ final String filename = intent.getStringExtra(EXTRA_FILENAME);
+ if (filename == null) return;
+
+ final ReplayData replayData = new MotionEventReader().readMotionEventData(
+ new File(filename));
+ synchronized (this) {
+ Replayer.getInstance().replay(replayData, new Runnable() {
+ @Override
+ public void run() {
+ synchronized (ReplayerService.this) {
+ ReplayerService.this.notify();
+ }
+ }
+ });
+ try {
+ wait(MAX_REPLAY_TIME);
+ } catch (InterruptedException e) {
+ Log.e(TAG, "Timeout while replaying.", e);
+ }
+ }
+ }
+}
diff --git a/java/src/com/android/inputmethod/research/ResearchLog.java b/java/src/com/android/inputmethod/research/ResearchLog.java
index 70c38e909..99d84938f 100644
--- a/java/src/com/android/inputmethod/research/ResearchLog.java
+++ b/java/src/com/android/inputmethod/research/ResearchLog.java
@@ -1,39 +1,33 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
-import android.content.SharedPreferences;
-import android.os.SystemClock;
+import android.content.Context;
import android.util.JsonWriter;
import android.util.Log;
-import android.view.inputmethod.CompletionInfo;
-import com.android.inputmethod.keyboard.Key;
-import com.android.inputmethod.latin.SuggestedWords;
-import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.define.ProductionFlag;
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileWriter;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
-import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
@@ -51,12 +45,14 @@ import java.util.concurrent.TimeUnit;
*/
public class ResearchLog {
private static final String TAG = ResearchLog.class.getSimpleName();
- private static final boolean DEBUG = false;
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
private static final long FLUSH_DELAY_IN_MS = 1000 * 5;
private static final int ABORT_TIMEOUT_IN_MS = 1000 * 4;
/* package */ final ScheduledExecutorService mExecutor;
/* package */ final File mFile;
+ private final Context mContext;
+
private JsonWriter mJsonWriter = NULL_JSON_WRITER;
// true if at least one byte of data has been written out to the log file. This must be
// remembered because JsonWriter requires that calls matching calls to beginObject and
@@ -85,12 +81,10 @@ public class ResearchLog {
}
}
- public ResearchLog(final File outputFile) {
- if (outputFile == null) {
- throw new IllegalArgumentException();
- }
+ public ResearchLog(final File outputFile, final Context context) {
mExecutor = Executors.newSingleThreadScheduledExecutor();
mFile = outputFile;
+ mContext = context;
}
public synchronized void close(final Runnable onClosed) {
@@ -115,7 +109,7 @@ public class ResearchLog {
Log.d(TAG, "error when closing ResearchLog:");
e.printStackTrace();
} finally {
- if (mFile.exists()) {
+ if (mFile != null && mFile.exists()) {
mFile.setWritable(false, false);
}
if (onClosed != null) {
@@ -142,7 +136,9 @@ public class ResearchLog {
mHasWrittenData = false;
}
} finally {
- mIsAbortSuccessful = mFile.delete();
+ if (mFile != null) {
+ mIsAbortSuccessful = mFile.delete();
+ }
}
return null;
}
@@ -188,133 +184,61 @@ public class ResearchLog {
mFlushFuture = mExecutor.schedule(mFlushCallable, FLUSH_DELAY_IN_MS, TimeUnit.MILLISECONDS);
}
- public synchronized void publish(final LogUnit logUnit, final boolean isIncludingPrivateData) {
+ public synchronized void publish(final LogUnit logUnit, final boolean canIncludePrivateData) {
try {
mExecutor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
- logUnit.publishTo(ResearchLog.this, isIncludingPrivateData);
+ logUnit.publishTo(ResearchLog.this, canIncludePrivateData);
scheduleFlush();
return null;
}
});
} catch (RejectedExecutionException e) {
// TODO: Add code to record loss of data, and report.
+ if (DEBUG) {
+ Log.d(TAG, "ResearchLog.publish() rejecting scheduled execution");
+ }
}
}
- private static final String CURRENT_TIME_KEY = "_ct";
- private static final String UPTIME_KEY = "_ut";
- private static final String EVENT_TYPE_KEY = "_ty";
-
- void outputEvent(final String[] keys, final Object[] values) {
- // Not thread safe.
- if (keys.length == 0) {
- return;
- }
- if (DEBUG) {
- if (keys.length != values.length + 1) {
- Log.d(TAG, "Key and Value list sizes do not match. " + keys[0]);
- }
- }
+ /**
+ * Return a JsonWriter for this ResearchLog. It is initialized the first time this method is
+ * called. The cached value is returned in future calls.
+ */
+ public JsonWriter getInitializedJsonWriterLocked() {
+ if (mJsonWriter != NULL_JSON_WRITER || mFile == null) return mJsonWriter;
try {
- if (mJsonWriter == NULL_JSON_WRITER) {
- mJsonWriter = new JsonWriter(new BufferedWriter(new FileWriter(mFile)));
- mJsonWriter.beginArray();
+ final JsonWriter jsonWriter = createJsonWriter(mContext, mFile);
+ if (jsonWriter != null) {
+ jsonWriter.beginArray();
+ mJsonWriter = jsonWriter;
mHasWrittenData = true;
}
- mJsonWriter.beginObject();
- mJsonWriter.name(CURRENT_TIME_KEY).value(System.currentTimeMillis());
- mJsonWriter.name(UPTIME_KEY).value(SystemClock.uptimeMillis());
- mJsonWriter.name(EVENT_TYPE_KEY).value(keys[0]);
- final int length = values.length;
- for (int i = 0; i < length; i++) {
- mJsonWriter.name(keys[i + 1]);
- Object value = values[i];
- if (value instanceof CharSequence) {
- mJsonWriter.value(value.toString());
- } else if (value instanceof Number) {
- mJsonWriter.value((Number) value);
- } else if (value instanceof Boolean) {
- mJsonWriter.value((Boolean) value);
- } else if (value instanceof CompletionInfo[]) {
- CompletionInfo[] ci = (CompletionInfo[]) value;
- mJsonWriter.beginArray();
- for (int j = 0; j < ci.length; j++) {
- mJsonWriter.value(ci[j].toString());
- }
- mJsonWriter.endArray();
- } else if (value instanceof SharedPreferences) {
- SharedPreferences prefs = (SharedPreferences) value;
- mJsonWriter.beginObject();
- for (Map.Entry<String,?> entry : prefs.getAll().entrySet()) {
- mJsonWriter.name(entry.getKey());
- final Object innerValue = entry.getValue();
- if (innerValue == null) {
- mJsonWriter.nullValue();
- } else if (innerValue instanceof Boolean) {
- mJsonWriter.value((Boolean) innerValue);
- } else if (innerValue instanceof Number) {
- mJsonWriter.value((Number) innerValue);
- } else {
- mJsonWriter.value(innerValue.toString());
- }
- }
- mJsonWriter.endObject();
- } else if (value instanceof Key[]) {
- Key[] keyboardKeys = (Key[]) value;
- mJsonWriter.beginArray();
- for (Key keyboardKey : keyboardKeys) {
- mJsonWriter.beginObject();
- mJsonWriter.name("code").value(keyboardKey.mCode);
- mJsonWriter.name("altCode").value(keyboardKey.getAltCode());
- mJsonWriter.name("x").value(keyboardKey.mX);
- mJsonWriter.name("y").value(keyboardKey.mY);
- mJsonWriter.name("w").value(keyboardKey.mWidth);
- mJsonWriter.name("h").value(keyboardKey.mHeight);
- mJsonWriter.endObject();
- }
- mJsonWriter.endArray();
- } else if (value instanceof SuggestedWords) {
- SuggestedWords words = (SuggestedWords) value;
- mJsonWriter.beginObject();
- mJsonWriter.name("typedWordValid").value(words.mTypedWordValid);
- mJsonWriter.name("willAutoCorrect").value(words.mWillAutoCorrect);
- mJsonWriter.name("isPunctuationSuggestions")
- .value(words.mIsPunctuationSuggestions);
- mJsonWriter.name("isObsoleteSuggestions").value(words.mIsObsoleteSuggestions);
- mJsonWriter.name("isPrediction").value(words.mIsPrediction);
- mJsonWriter.name("words");
- mJsonWriter.beginArray();
- final int size = words.size();
- for (int j = 0; j < size; j++) {
- SuggestedWordInfo wordInfo = words.getWordInfo(j);
- mJsonWriter.value(wordInfo.toString());
- }
- mJsonWriter.endArray();
- mJsonWriter.endObject();
- } else if (value == null) {
- mJsonWriter.nullValue();
- } else {
- Log.w(TAG, "Unrecognized type to be logged: " +
- (value == null ? "<null>" : value.getClass().getName()));
- mJsonWriter.nullValue();
- }
- }
- mJsonWriter.endObject();
- } catch (IOException e) {
- e.printStackTrace();
- Log.w(TAG, "Error in JsonWriter; disabling logging");
+ } catch (final IOException e) {
+ Log.w(TAG, "Error in JsonWriter; disabling logging", e);
try {
mJsonWriter.close();
- } catch (IllegalStateException e1) {
+ } catch (final IllegalStateException e1) {
// Assume that this is just the json not being terminated properly.
// Ignore
- } catch (IOException e1) {
- e1.printStackTrace();
+ } catch (final IOException e1) {
+ Log.w(TAG, "Error in closing JsonWriter; disabling logging", e1);
} finally {
mJsonWriter = NULL_JSON_WRITER;
}
}
+ return mJsonWriter;
+ }
+
+ /**
+ * Create the JsonWriter to write the ResearchLog to.
+ *
+ * This method may be overriden in testing to redirect the output.
+ */
+ /* package for test */ JsonWriter createJsonWriter(final Context context, final File file)
+ throws IOException {
+ return new JsonWriter(new BufferedWriter(new OutputStreamWriter(
+ context.openFileOutput(file.getName(), Context.MODE_PRIVATE))));
}
}
diff --git a/java/src/com/android/inputmethod/research/ResearchLogger.java b/java/src/com/android/inputmethod/research/ResearchLogger.java
index 763fd6e00..25633d630 100644
--- a/java/src/com/android/inputmethod/research/ResearchLogger.java
+++ b/java/src/com/android/inputmethod/research/ResearchLogger.java
@@ -1,23 +1,25 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
import static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.KEYBOARD_LAYOUT_SET;
+import android.accounts.Account;
+import android.accounts.AccountManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
@@ -30,15 +32,18 @@ import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
-import android.inputmethodservice.InputMethodService;
import android.net.Uri;
import android.os.Build;
+import android.os.Bundle;
+import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
+import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
@@ -47,7 +52,6 @@ import android.view.MotionEvent;
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.InputConnection;
import android.widget.Toast;
@@ -55,11 +59,12 @@ import android.widget.Toast;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardId;
+import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.MainKeyboardView;
-import com.android.inputmethod.latin.CollectionUtils;
import com.android.inputmethod.latin.Constants;
import com.android.inputmethod.latin.Dictionary;
+import com.android.inputmethod.latin.InputTypeUtils;
import com.android.inputmethod.latin.LatinIME;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.RichInputConnection;
@@ -67,11 +72,23 @@ import com.android.inputmethod.latin.RichInputConnection.Range;
import com.android.inputmethod.latin.Suggest;
import com.android.inputmethod.latin.SuggestedWords;
import com.android.inputmethod.latin.define.ProductionFlag;
+import com.android.inputmethod.research.MotionEventReader.ReplayData;
+import java.io.BufferedReader;
import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.List;
import java.util.Locale;
+import java.util.Random;
import java.util.UUID;
/**
@@ -83,28 +100,66 @@ import java.util.UUID;
* This functionality is off by default. See {@link ProductionFlag#IS_EXPERIMENTAL}.
*/
public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChangeListener {
+ // TODO: This class has grown quite large and combines several concerns that should be
+ // separated. The following refactorings will be applied as soon as possible after adding
+ // support for replaying historical events, fixing some replay bugs, adding some ui constraints
+ // on the feedback dialog, and adding the survey dialog.
+ // TODO: Refactor. Move splash screen code into separate class.
+ // TODO: Refactor. Move feedback screen code into separate class.
+ // TODO: Refactor. Move logging invocations into their own class.
+ // TODO: Refactor. Move currentLogUnit management into separate class.
private static final String TAG = ResearchLogger.class.getSimpleName();
- private static final boolean DEBUG = false;
- private static final boolean OUTPUT_ENTIRE_BUFFER = false; // true may disclose private info
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ private static final boolean DEBUG_REPLAY_AFTER_FEEDBACK = false
+ && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ // Whether the TextView contents are logged at the end of the session. true will disclose
+ // private info.
+ private static final boolean LOG_FULL_TEXTVIEW_CONTENTS = false
+ && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ // Whether the feedback dialog preserves the editable text across invocations. Should be false
+ // for normal research builds so users do not have to delete the same feedback string they
+ // entered earlier. Should be true for builds internal to a development team so when the text
+ // field holds a channel name, the developer does not have to re-enter it when using the
+ // feedback mechanism to generate multiple tests.
+ private static final boolean FEEDBACK_DIALOG_SHOULD_PRESERVE_TEXT_FIELD = false;
public static final boolean DEFAULT_USABILITY_STUDY_MODE = false;
/* package */ static boolean sIsLogging = false;
- private static final int OUTPUT_FORMAT_VERSION = 1;
+ private static final int OUTPUT_FORMAT_VERSION = 5;
private static final String PREF_USABILITY_STUDY_MODE = "usability_study_mode";
private static final String PREF_RESEARCH_HAS_SEEN_SPLASH = "pref_research_has_seen_splash";
- /* package */ static final String FILENAME_PREFIX = "researchLog";
- private static final String FILENAME_SUFFIX = ".txt";
+ /* package */ static final String LOG_FILENAME_PREFIX = "researchLog";
+ private static final String LOG_FILENAME_SUFFIX = ".txt";
+ /* package */ static final String USER_RECORDING_FILENAME_PREFIX = "recording";
+ private static final String USER_RECORDING_FILENAME_SUFFIX = ".txt";
private static final SimpleDateFormat TIMESTAMP_DATEFORMAT =
new SimpleDateFormat("yyyyMMddHHmmssS", Locale.US);
+ // Whether all words should be recorded, leaving unsampled word between bigrams. Useful for
+ // testing.
+ /* package for test */ static final boolean IS_LOGGING_EVERYTHING = false
+ && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ // The number of words between n-grams to omit from the log.
+ private static final int NUMBER_OF_WORDS_BETWEEN_SAMPLES =
+ IS_LOGGING_EVERYTHING ? 0 : (DEBUG ? 2 : 18);
+
+ // Whether to show an indicator on the screen that logging is on. Currently a very small red
+ // dot in the lower right hand corner. Most users should not notice it.
private static final boolean IS_SHOWING_INDICATOR = true;
- private static final boolean IS_SHOWING_INDICATOR_CLEARLY = false;
- public static final int FEEDBACK_WORD_BUFFER_SIZE = 5;
+ // Change the default indicator to something very visible. Currently two red vertical bars on
+ // either side of they keyboard.
+ private static final boolean IS_SHOWING_INDICATOR_CLEARLY = false ||
+ (IS_LOGGING_EVERYTHING && ProductionFlag.IS_EXPERIMENTAL_DEBUG);
+ // FEEDBACK_WORD_BUFFER_SIZE should add 1 because it must also hold the feedback LogUnit itself.
+ public static final int FEEDBACK_WORD_BUFFER_SIZE = (Integer.MAX_VALUE - 1) + 1;
// constants related to specific log points
private static final String WHITESPACE_SEPARATORS = " \t\n\r";
private static final int MAX_INPUTVIEW_LENGTH_TO_CAPTURE = 8192; // must be >=1
private static final String PREF_RESEARCH_LOGGER_UUID_STRING = "pref_research_logger_uuid";
+ private static final String PREF_RESEARCH_SAVED_CHANNEL = "pref_research_saved_channel";
private static final ResearchLogger sInstance = new ResearchLogger();
+ private static String sAccountType = null;
+ private static String sAllowedAccountDomain = null;
// to write to a different filename, e.g., for testing, set mFile before calling start()
/* package */ File mFilesDir;
/* package */ String mUUIDString;
@@ -114,9 +169,15 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
// the system to do so.
// LogUnits are queued in the LogBuffers and published to the ResearchLogs when words are
// complete.
- /* package */ ResearchLog mFeedbackLog;
/* package */ MainLogBuffer mMainLogBuffer;
+ // TODO: Remove the feedback log. The feedback log continuously captured user data in case the
+ // user wanted to submit it. We now use the mUserRecordingLogBuffer to allow the user to
+ // explicitly reproduce a problem.
+ /* package */ ResearchLog mFeedbackLog;
/* package */ LogBuffer mFeedbackLogBuffer;
+ /* package */ ResearchLog mUserRecordingLog;
+ /* package */ LogBuffer mUserRecordingLogBuffer;
+ private File mUserRecordingFile = null;
private boolean mIsPasswordView = false;
private boolean mIsLoggingSuspended = false;
@@ -129,7 +190,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
/* package for test */ static final String WORD_REPLACEMENT_STRING = "\uE001";
private static final String PREF_LAST_CLEANUP_TIME = "pref_last_cleanup_time";
private static final long DURATION_BETWEEN_DIR_CLEANUP_IN_MS = DateUtils.DAY_IN_MILLIS;
- private static final long MAX_LOGFILE_AGE_IN_MS = DateUtils.DAY_IN_MILLIS;
+ private static final long MAX_LOGFILE_AGE_IN_MS = 4 * DateUtils.DAY_IN_MILLIS;
protected static final int SUSPEND_DURATION_IN_MINUTES = 1;
// set when LatinIME should ignore an onUpdateSelection() callback that
// arises from operations in this class
@@ -137,16 +198,37 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
// used to check whether words are not unique
private Suggest mSuggest;
- private Dictionary mDictionary;
private MainKeyboardView mMainKeyboardView;
- private InputMethodService mInputMethodService;
+ // TODO: Check whether a superclass can be used instead of LatinIME.
+ /* package for test */ LatinIME mLatinIME;
private final Statistics mStatistics;
+ private final MotionEventReader mMotionEventReader = new MotionEventReader();
+ private final Replayer mReplayer = Replayer.getInstance();
private Intent mUploadIntent;
- private PendingIntent mUploadPendingIntent;
+ private Intent mUploadNowIntent;
private LogUnit mCurrentLogUnit = new LogUnit();
+ // Gestured or tapped words may be committed after the gesture of the next word has started.
+ // To ensure that the gesture data of the next word is not associated with the previous word,
+ // thereby leaking private data, we store the time of the down event that started the second
+ // gesture, and when committing the earlier word, split the LogUnit.
+ private long mSavedDownEventTime;
+ private Bundle mFeedbackDialogBundle = null;
+ private boolean mInFeedbackDialog = false;
+ // The feedback dialog causes stop() to be called for the keyboard connected to the original
+ // window. This is because the feedback dialog must present its own EditText box that displays
+ // a keyboard. stop() normally causes mFeedbackLogBuffer, which contains the user's data, to be
+ // cleared, and causes mFeedbackLog, which is ready to collect information in case the user
+ // wants to upload, to be closed. This is good because we don't need to log information about
+ // what the user is typing in the feedback dialog, but bad because this data must be uploaded.
+ // Here we save the LogBuffer and Log so the feedback dialog can later access their data.
+ private LogBuffer mSavedFeedbackLogBuffer;
+ private ResearchLog mSavedFeedbackLog;
+ private Handler mUserRecordingTimeoutHandler;
+ private static final long USER_RECORDING_TIMEOUT_MS = 30L * DateUtils.SECOND_IN_MILLIS;
+
private ResearchLogger() {
mStatistics = Statistics.getInstance();
}
@@ -155,16 +237,17 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
return sInstance;
}
- public void init(final InputMethodService ims, final SharedPreferences prefs) {
- assert ims != null;
- if (ims == null) {
+ public void init(final LatinIME latinIME, final KeyboardSwitcher keyboardSwitcher) {
+ assert latinIME != null;
+ if (latinIME == null) {
Log.w(TAG, "IMS is null; logging is off");
} else {
- mFilesDir = ims.getFilesDir();
+ mFilesDir = latinIME.getFilesDir();
if (mFilesDir == null || !mFilesDir.exists()) {
Log.w(TAG, "IME storage directory does not exist.");
}
}
+ final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(latinIME);
if (prefs != null) {
mUUIDString = getUUID(prefs);
if (!prefs.contains(PREF_USABILITY_STUDY_MODE)) {
@@ -185,13 +268,18 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
e.apply();
}
}
- mInputMethodService = ims;
+ final Resources res = latinIME.getResources();
+ sAccountType = res.getString(R.string.research_account_type);
+ sAllowedAccountDomain = res.getString(R.string.research_allowed_account_domain);
+ mLatinIME = latinIME;
mPrefs = prefs;
- mUploadIntent = new Intent(mInputMethodService, UploaderService.class);
- mUploadPendingIntent = PendingIntent.getService(mInputMethodService, 0, mUploadIntent, 0);
+ mUploadIntent = new Intent(mLatinIME, UploaderService.class);
+ mUploadNowIntent = new Intent(mLatinIME, UploaderService.class);
+ mUploadNowIntent.putExtra(UploaderService.EXTRA_UPLOAD_UNCONDITIONALLY, true);
+ mReplayer.setKeyboardSwitcher(keyboardSwitcher);
if (ProductionFlag.IS_EXPERIMENTAL) {
- scheduleUploadingService(mInputMethodService);
+ scheduleUploadingService(mLatinIME);
}
}
@@ -216,8 +304,10 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
private void cleanupLoggingDir(final File dir, final long time) {
for (File file : dir.listFiles()) {
- if (file.getName().startsWith(ResearchLogger.FILENAME_PREFIX) &&
- file.lastModified() < time) {
+ final String filename = file.getName();
+ if ((filename.startsWith(ResearchLogger.LOG_FILENAME_PREFIX)
+ || filename.startsWith(ResearchLogger.USER_RECORDING_FILENAME_PREFIX))
+ && file.lastModified() < time) {
file.delete();
}
}
@@ -250,7 +340,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
if (windowToken == null) {
return;
}
- final AlertDialog.Builder builder = new AlertDialog.Builder(mInputMethodService)
+ final AlertDialog.Builder builder = new AlertDialog.Builder(mLatinIME)
.setTitle(R.string.research_splash_title)
.setMessage(R.string.research_splash_content)
.setPositiveButton(android.R.string.yes,
@@ -265,12 +355,12 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
- final String packageName = mInputMethodService.getPackageName();
+ final String packageName = mLatinIME.getPackageName();
final Uri packageUri = Uri.parse("package:" + packageName);
final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE,
packageUri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- mInputMethodService.startActivity(intent);
+ mLatinIME.startActivity(intent);
}
})
.setCancelable(true)
@@ -278,7 +368,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
- mInputMethodService.requestHideSelf(0);
+ mLatinIME.requestHideSelf(0);
}
});
mSplashDialog = builder.create();
@@ -312,20 +402,40 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
sIsLogging = enableLogging;
}
- private File createLogFile(File filesDir) {
+ private static int sLogFileCounter = 0;
+
+ private File createLogFile(final File filesDir) {
final StringBuilder sb = new StringBuilder();
- sb.append(FILENAME_PREFIX).append('-');
+ sb.append(LOG_FILENAME_PREFIX).append('-');
+ sb.append(mUUIDString).append('-');
+ sb.append(TIMESTAMP_DATEFORMAT.format(new Date())).append('-');
+ // Sometimes logFiles are created within milliseconds of each other. Append a counter to
+ // separate these.
+ if (sLogFileCounter < Integer.MAX_VALUE) {
+ sLogFileCounter++;
+ } else {
+ // Wrap the counter, in the unlikely event of overflow.
+ sLogFileCounter = 0;
+ }
+ sb.append(sLogFileCounter);
+ sb.append(LOG_FILENAME_SUFFIX);
+ return new File(filesDir, sb.toString());
+ }
+
+ private File createUserRecordingFile(final File filesDir) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(USER_RECORDING_FILENAME_PREFIX).append('-');
sb.append(mUUIDString).append('-');
sb.append(TIMESTAMP_DATEFORMAT.format(new Date()));
- sb.append(FILENAME_SUFFIX);
+ sb.append(USER_RECORDING_FILENAME_SUFFIX);
return new File(filesDir, sb.toString());
}
private void checkForEmptyEditor() {
- if (mInputMethodService == null) {
+ if (mLatinIME == null) {
return;
}
- final InputConnection ic = mInputMethodService.getCurrentInputConnection();
+ final InputConnection ic = mLatinIME.getCurrentInputConnection();
if (ic == null) {
return;
}
@@ -362,27 +472,56 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
return;
}
if (mMainLogBuffer == null) {
- mMainResearchLog = new ResearchLog(createLogFile(mFilesDir));
- mMainLogBuffer = new MainLogBuffer(mMainResearchLog);
+ mMainResearchLog = new ResearchLog(createLogFile(mFilesDir), mLatinIME);
+ final int numWordsToIgnore = new Random().nextInt(NUMBER_OF_WORDS_BETWEEN_SAMPLES + 1);
+ mMainLogBuffer = new MainLogBuffer(NUMBER_OF_WORDS_BETWEEN_SAMPLES, numWordsToIgnore) {
+ @Override
+ protected void publish(final ArrayList<LogUnit> logUnits,
+ boolean canIncludePrivateData) {
+ canIncludePrivateData |= IS_LOGGING_EVERYTHING;
+ final int length = logUnits.size();
+ for (int i = 0; i < length; i++) {
+ final LogUnit logUnit = logUnits.get(i);
+ final String word = logUnit.getWord();
+ if (word != null && word.length() > 0 && hasLetters(word)) {
+ Log.d(TAG, "onPublish: " + word + ", hc: "
+ + logUnit.containsCorrection());
+ final Dictionary dictionary = getDictionary();
+ mStatistics.recordWordEntered(
+ dictionary != null && dictionary.isValidWord(word),
+ logUnit.containsCorrection());
+ }
+ }
+ if (mMainResearchLog != null) {
+ publishLogUnits(logUnits, mMainResearchLog, canIncludePrivateData);
+ }
+ }
+ };
mMainLogBuffer.setSuggest(mSuggest);
}
if (mFeedbackLogBuffer == null) {
- mFeedbackLog = new ResearchLog(createLogFile(mFilesDir));
- // LogBuffer is one more than FEEDBACK_WORD_BUFFER_SIZE, because it must also hold
- // the feedback LogUnit itself.
- mFeedbackLogBuffer = new LogBuffer(FEEDBACK_WORD_BUFFER_SIZE + 1);
+ resetFeedbackLogging();
}
}
+ private void resetFeedbackLogging() {
+ mFeedbackLog = new ResearchLog(createLogFile(mFilesDir), mLatinIME);
+ mFeedbackLogBuffer = new FixedLogBuffer(FEEDBACK_WORD_BUFFER_SIZE);
+ }
+
/* package */ void stop() {
if (DEBUG) {
Log.d(TAG, "stop called");
}
- logStatistics();
+ // Commit mCurrentLogUnit before closing.
commitCurrentLogUnit();
if (mMainLogBuffer != null) {
- publishLogBuffer(mMainLogBuffer, mMainResearchLog, false /* isIncludingPrivateData */);
+ mMainLogBuffer.shiftAndPublishAll();
+ logStatistics();
+ commitCurrentLogUnit();
+ mMainLogBuffer.setIsStopping();
+ mMainLogBuffer.shiftAndPublishAll();
mMainResearchLog.close(null /* callback */);
mMainLogBuffer = null;
}
@@ -427,21 +566,6 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
private long mResumeTime = 0L;
- private void suspendLoggingUntil(long time) {
- mIsLoggingSuspended = true;
- mResumeTime = time;
- requestIndicatorRedraw();
- }
-
- private void resumeLogging() {
- mResumeTime = 0L;
- updateSuspendedState();
- requestIndicatorRedraw();
- if (isAllowedToLog()) {
- restart();
- }
- }
-
private void updateSuspendedState() {
final long time = System.currentTimeMillis();
if (time > mResumeTime) {
@@ -472,42 +596,108 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
presentFeedbackDialog(latinIME);
}
- // TODO: currently unreachable. Remove after being sure no menu is needed.
- /*
- public void presentResearchDialog(final LatinIME latinIME) {
- final CharSequence title = latinIME.getString(R.string.english_ime_research_log);
- final boolean showEnable = mIsLoggingSuspended || !sIsLogging;
- final CharSequence[] items = new CharSequence[] {
- latinIME.getString(R.string.research_feedback_menu_option),
- showEnable ? latinIME.getString(R.string.research_enable_session_logging) :
- latinIME.getString(R.string.research_do_not_log_this_session)
- };
- final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface di, int position) {
- di.dismiss();
- switch (position) {
- case 0:
- presentFeedbackDialog(latinIME);
- break;
- case 1:
- enableOrDisable(showEnable, latinIME);
- break;
- }
+ public void presentFeedbackDialog(LatinIME latinIME) {
+ if (isMakingUserRecording()) {
+ saveRecording();
+ }
+ mInFeedbackDialog = true;
+ mSavedFeedbackLogBuffer = mFeedbackLogBuffer;
+ mSavedFeedbackLog = mFeedbackLog;
+ // Set the non-saved versions to null so that the stop() caused by switching to the
+ // Feedback dialog will not close them.
+ mFeedbackLogBuffer = null;
+ mFeedbackLog = null;
+
+ final Intent intent = new Intent();
+ intent.setClass(mLatinIME, FeedbackActivity.class);
+ if (mFeedbackDialogBundle == null) {
+ // Restore feedback field with channel name
+ final Bundle bundle = new Bundle();
+ bundle.putBoolean(FeedbackFragment.KEY_INCLUDE_ACCOUNT_NAME, true);
+ bundle.putBoolean(FeedbackFragment.KEY_HAS_USER_RECORDING, false);
+ if (FEEDBACK_DIALOG_SHOULD_PRESERVE_TEXT_FIELD) {
+ final String savedChannelName = mPrefs.getString(PREF_RESEARCH_SAVED_CHANNEL, "");
+ bundle.putString(FeedbackFragment.KEY_FEEDBACK_STRING, savedChannelName);
}
+ mFeedbackDialogBundle = bundle;
+ }
+ intent.putExtras(mFeedbackDialogBundle);
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ latinIME.startActivity(intent);
+ }
- };
- final AlertDialog.Builder builder = new AlertDialog.Builder(latinIME)
- .setItems(items, listener)
- .setTitle(title);
- latinIME.showOptionDialog(builder.create());
+ public void setFeedbackDialogBundle(final Bundle bundle) {
+ mFeedbackDialogBundle = bundle;
}
- */
- private boolean mInFeedbackDialog = false;
- public void presentFeedbackDialog(LatinIME latinIME) {
- mInFeedbackDialog = true;
- latinIME.launchKeyboardedDialogActivity(FeedbackActivity.class);
+ public void startRecording() {
+ final Resources res = mLatinIME.getResources();
+ Toast.makeText(mLatinIME,
+ res.getString(R.string.research_feedback_demonstration_instructions),
+ Toast.LENGTH_LONG).show();
+ startRecordingInternal();
+ }
+
+ private void startRecordingInternal() {
+ if (mUserRecordingLog != null) {
+ mUserRecordingLog.abort();
+ }
+ mUserRecordingFile = createUserRecordingFile(mFilesDir);
+ mUserRecordingLog = new ResearchLog(mUserRecordingFile, mLatinIME);
+ mUserRecordingLogBuffer = new LogBuffer();
+ resetRecordingTimer();
+ }
+
+ private boolean isMakingUserRecording() {
+ return mUserRecordingLog != null;
+ }
+
+ private void resetRecordingTimer() {
+ if (mUserRecordingTimeoutHandler == null) {
+ mUserRecordingTimeoutHandler = new Handler();
+ }
+ clearRecordingTimer();
+ mUserRecordingTimeoutHandler.postDelayed(mRecordingHandlerTimeoutRunnable,
+ USER_RECORDING_TIMEOUT_MS);
+ }
+
+ private void clearRecordingTimer() {
+ mUserRecordingTimeoutHandler.removeCallbacks(mRecordingHandlerTimeoutRunnable);
+ }
+
+ private Runnable mRecordingHandlerTimeoutRunnable = new Runnable() {
+ @Override
+ public void run() {
+ cancelRecording();
+ requestIndicatorRedraw();
+ final Resources res = mLatinIME.getResources();
+ Toast.makeText(mLatinIME, res.getString(R.string.research_feedback_recording_failure),
+ Toast.LENGTH_LONG).show();
+ }
+ };
+
+ private void cancelRecording() {
+ if (mUserRecordingLog != null) {
+ mUserRecordingLog.abort();
+ }
+ mUserRecordingLog = null;
+ mUserRecordingLogBuffer = null;
+ if (mFeedbackDialogBundle != null) {
+ mFeedbackDialogBundle.putBoolean("HasRecording", false);
+ }
+ }
+
+ private void saveRecording() {
+ commitCurrentLogUnit();
+ publishLogBuffer(mUserRecordingLogBuffer, mUserRecordingLog, true);
+ mUserRecordingLog.close(null);
+ mUserRecordingLog = null;
+ mUserRecordingLogBuffer = null;
+
+ if (mFeedbackDialogBundle != null) {
+ mFeedbackDialogBundle.putBoolean(FeedbackFragment.KEY_HAS_USER_RECORDING, true);
+ }
+ clearRecordingTimer();
}
// TODO: currently unreachable. Remove after being sure enable/disable is
@@ -539,40 +729,116 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
*/
- private static final String[] EVENTKEYS_FEEDBACK = {
- "UserTimestamp", "contents"
- };
- public void sendFeedback(final String feedbackContents, final boolean includeHistory) {
- if (mFeedbackLogBuffer == null) {
+ /**
+ * Get the name of the first allowed account on the device.
+ *
+ * Allowed accounts must be in the domain given by ALLOWED_ACCOUNT_DOMAIN.
+ *
+ * @return The user's account name.
+ */
+ public String getAccountName() {
+ if (sAccountType == null || sAccountType.isEmpty()) {
+ return null;
+ }
+ if (sAllowedAccountDomain == null || sAllowedAccountDomain.isEmpty()) {
+ return null;
+ }
+ final AccountManager manager = AccountManager.get(mLatinIME);
+ // Filter first by account type.
+ final Account[] accounts = manager.getAccountsByType(sAccountType);
+
+ for (final Account account : accounts) {
+ if (DEBUG) {
+ Log.d(TAG, account.name);
+ }
+ final String[] parts = account.name.split("@");
+ if (parts.length > 1 && parts[1].equals(sAllowedAccountDomain)) {
+ return parts[0];
+ }
+ }
+ return null;
+ }
+
+ private static final LogStatement LOGSTATEMENT_FEEDBACK =
+ new LogStatement("UserFeedback", false, false, "contents", "accountName", "recording");
+ public void sendFeedback(final String feedbackContents, final boolean includeHistory,
+ final boolean isIncludingAccountName, final boolean isIncludingRecording) {
+ if (mSavedFeedbackLogBuffer == null) {
return;
}
- if (includeHistory) {
- commitCurrentLogUnit();
- } else {
- mFeedbackLogBuffer.clear();
+ if (!includeHistory) {
+ mSavedFeedbackLogBuffer.clear();
+ }
+ String recording = "";
+ if (isIncludingRecording) {
+ // Try to read recording from recently written json file
+ if (mUserRecordingFile != null) {
+ FileChannel channel = null;
+ try {
+ channel = new FileInputStream(mUserRecordingFile).getChannel();
+ final MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
+ channel.size());
+ // Android's openFileOutput() creates the file, so we use Android's default
+ // Charset (UTF-8) here to read it.
+ recording = Charset.defaultCharset().decode(buffer).toString();
+ } catch (FileNotFoundException e) {
+ Log.e(TAG, "Could not find recording file", e);
+ } catch (IOException e) {
+ Log.e(TAG, "Error reading recording file", e);
+ } finally {
+ if (channel != null) {
+ try {
+ channel.close();
+ } catch (IOException e) {
+ Log.e(TAG, "Error closing recording file", e);
+ }
+ }
+ }
+ }
}
final LogUnit feedbackLogUnit = new LogUnit();
- final Object[] values = {
- feedbackContents
- };
- feedbackLogUnit.addLogStatement(EVENTKEYS_FEEDBACK, values,
- false /* isPotentiallyPrivate */);
+ final String accountName = isIncludingAccountName ? getAccountName() : "";
+ feedbackLogUnit.addLogStatement(LOGSTATEMENT_FEEDBACK, SystemClock.uptimeMillis(),
+ feedbackContents, accountName, recording);
mFeedbackLogBuffer.shiftIn(feedbackLogUnit);
- publishLogBuffer(mFeedbackLogBuffer, mFeedbackLog, true /* isIncludingPrivateData */);
- mFeedbackLog.close(new Runnable() {
+ publishLogBuffer(mFeedbackLogBuffer, mSavedFeedbackLog, true /* isIncludingPrivateData */);
+ mSavedFeedbackLog.close(new Runnable() {
@Override
public void run() {
uploadNow();
}
});
- mFeedbackLog = new ResearchLog(createLogFile(mFilesDir));
+
+ if (isIncludingRecording && DEBUG_REPLAY_AFTER_FEEDBACK) {
+ final Handler handler = new Handler();
+ handler.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ final ReplayData replayData =
+ mMotionEventReader.readMotionEventData(mUserRecordingFile);
+ mReplayer.replay(replayData, null);
+ }
+ }, 1000);
+ }
+
+ if (FEEDBACK_DIALOG_SHOULD_PRESERVE_TEXT_FIELD) {
+ // Use feedback string as a channel name to label feedback strings. Here we record the
+ // string for prepopulating the field next time.
+ final String channelName = feedbackContents;
+ if (mPrefs == null) {
+ return;
+ }
+ final Editor e = mPrefs.edit();
+ e.putString(PREF_RESEARCH_SAVED_CHANNEL, channelName);
+ e.apply();
+ }
}
public void uploadNow() {
if (DEBUG) {
Log.d(TAG, "calling uploadNow()");
}
- mInputMethodService.startService(mUploadIntent);
+ mLatinIME.startService(mUploadNowIntent);
}
public void onLeavingSendFeedbackDialog() {
@@ -586,19 +852,20 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
}
+ private Dictionary getDictionary() {
+ if (mSuggest == null) {
+ return null;
+ }
+ return mSuggest.getMainDictionary();
+ }
+
private void setIsPasswordView(boolean isPasswordView) {
mIsPasswordView = isPasswordView;
}
private boolean isAllowedToLog() {
- if (DEBUG) {
- Log.d(TAG, "iatl: " +
- "mipw=" + mIsPasswordView +
- ", mils=" + mIsLoggingSuspended +
- ", sil=" + sIsLogging +
- ", mInFeedbackDialog=" + mInFeedbackDialog);
- }
- return !mIsPasswordView && !mIsLoggingSuspended && sIsLogging && !mInFeedbackDialog;
+ return !mIsPasswordView && !mIsLoggingSuspended && sIsLogging && !mInFeedbackDialog
+ && !isReplaying();
}
public void requestIndicatorRedraw() {
@@ -611,27 +878,41 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
mMainKeyboardView.invalidateAllKeys();
}
+ private boolean isReplaying() {
+ return mReplayer.isReplaying();
+ }
+
+ private int getIndicatorColor() {
+ if (isMakingUserRecording()) {
+ return Color.YELLOW;
+ }
+ if (isReplaying()) {
+ return Color.GREEN;
+ }
+ return Color.RED;
+ }
public void paintIndicator(KeyboardView view, Paint paint, Canvas canvas, int width,
int height) {
// TODO: Reimplement using a keyboard background image specific to the ResearchLogger
// and remove this method.
- // The check for MainKeyboardView ensures that a red border is only placed around
- // the main keyboard, not every keyboard.
- if (IS_SHOWING_INDICATOR && isAllowedToLog() && view instanceof MainKeyboardView) {
+ // The check for MainKeyboardView ensures that the indicator only decorates the main
+ // keyboard, not every keyboard.
+ if (IS_SHOWING_INDICATOR && (isAllowedToLog() || isReplaying())
+ && view instanceof MainKeyboardView) {
final int savedColor = paint.getColor();
- paint.setColor(Color.RED);
+ paint.setColor(getIndicatorColor());
final Style savedStyle = paint.getStyle();
paint.setStyle(Style.STROKE);
final float savedStrokeWidth = paint.getStrokeWidth();
if (IS_SHOWING_INDICATOR_CLEARLY) {
paint.setStrokeWidth(5);
- canvas.drawRect(0, 0, width, height, paint);
+ canvas.drawLine(0, 0, 0, height, paint);
+ canvas.drawLine(width, 0, width, height, paint);
} else {
- // Put a tiny red dot on the screen so a knowledgeable user can check whether
- // it is enabled. The dot is actually a zero-width, zero-height rectangle,
- // placed at the lower-right corner of the canvas, painted with a non-zero border
- // width.
+ // Put a tiny dot on the screen so a knowledgeable user can check whether it is
+ // enabled. The dot is actually a zero-width, zero-height rectangle, placed at the
+ // lower-right corner of the canvas, painted with a non-zero border width.
paint.setStrokeWidth(3);
canvas.drawRect(width, height, width, height, paint);
}
@@ -641,97 +922,191 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
}
- private static final Object[] EVENTKEYS_NULLVALUES = {};
-
/**
* Buffer a research log event, flagging it as privacy-sensitive.
- *
- * This event contains potentially private information. If the word that this event is a part
- * of is determined to be privacy-sensitive, then this event should not be included in the
- * output log. The system waits to output until the containing word is known.
- *
- * @param keys an array containing a descriptive name for the event, followed by the keys
- * @param values an array of values, either a String or Number. length should be one
- * less than the keys array
*/
- private synchronized void enqueuePotentiallyPrivateEvent(final String[] keys,
- final Object[] values) {
- assert values.length + 1 == keys.length;
- if (isAllowedToLog()) {
- mCurrentLogUnit.addLogStatement(keys, values, true /* isPotentiallyPrivate */);
+ private synchronized void enqueueEvent(final LogStatement logStatement,
+ final Object... values) {
+ enqueueEvent(mCurrentLogUnit, logStatement, values);
+ }
+
+ private synchronized void enqueueEvent(final LogUnit logUnit, final LogStatement logStatement,
+ final Object... values) {
+ assert values.length == logStatement.getKeys().length;
+ if (isAllowedToLog() && logUnit != null) {
+ final long time = SystemClock.uptimeMillis();
+ logUnit.addLogStatement(logStatement, time, values);
}
}
private void setCurrentLogUnitContainsDigitFlag() {
- mCurrentLogUnit.setContainsDigit();
+ mCurrentLogUnit.setMayContainDigit();
}
- /**
- * Buffer a research log event, flaggint it as not privacy-sensitive.
- *
- * This event contains no potentially private information. Even if the word that this event
- * is privacy-sensitive, this event can still safely be sent to the output log. The system
- * waits until the containing word is known so that this event can be written in the proper
- * temporal order with other events that may be privacy sensitive.
- *
- * @param keys an array containing a descriptive name for the event, followed by the keys
- * @param values an array of values, either a String or Number. length should be one
- * less than the keys array
- */
- private synchronized void enqueueEvent(final String[] keys, final Object[] values) {
- assert values.length + 1 == keys.length;
- if (isAllowedToLog()) {
- mCurrentLogUnit.addLogStatement(keys, values, false /* isPotentiallyPrivate */);
- }
+ private void setCurrentLogUnitContainsCorrection() {
+ mCurrentLogUnit.setContainsCorrection();
+ }
+
+ private void setCurrentLogUnitCorrectionType(final int correctionType) {
+ mCurrentLogUnit.setCorrectionType(correctionType);
}
/* package for test */ void commitCurrentLogUnit() {
if (DEBUG) {
- Log.d(TAG, "commitCurrentLogUnit");
+ Log.d(TAG, "commitCurrentLogUnit" + (mCurrentLogUnit.hasWord() ?
+ ": " + mCurrentLogUnit.getWord() : ""));
}
if (!mCurrentLogUnit.isEmpty()) {
if (mMainLogBuffer != null) {
mMainLogBuffer.shiftIn(mCurrentLogUnit);
- if (mMainLogBuffer.isSafeToLog() && mMainResearchLog != null) {
- publishLogBuffer(mMainLogBuffer, mMainResearchLog,
- true /* isIncludingPrivateData */);
- mMainLogBuffer.resetWordCounter();
- }
}
if (mFeedbackLogBuffer != null) {
mFeedbackLogBuffer.shiftIn(mCurrentLogUnit);
}
+ if (mUserRecordingLogBuffer != null) {
+ mUserRecordingLogBuffer.shiftIn(mCurrentLogUnit);
+ }
+ mCurrentLogUnit = new LogUnit();
+ } else {
+ if (DEBUG) {
+ Log.d(TAG, "Warning: tried to commit empty log unit.");
+ }
+ }
+ }
+
+ private static final LogStatement LOGSTATEMENT_UNCOMMIT_CURRENT_LOGUNIT =
+ new LogStatement("UncommitCurrentLogUnit", false, false);
+ public void uncommitCurrentLogUnit(final String expectedWord,
+ final boolean dumpCurrentLogUnit) {
+ // The user has deleted this word and returned to the previous. Check that the word in the
+ // logUnit matches the expected word. If so, restore the last log unit committed to be the
+ // current logUnit. I.e., pull out the last LogUnit from all the LogBuffers, and make
+ // restore it to mCurrentLogUnit so the new edits are captured with the word. Optionally
+ // dump the contents of mCurrentLogUnit (useful if they contain deletions of the next word
+ // that should not be reported to protect user privacy)
+ //
+ // Note that we don't use mLastLogUnit here, because it only goes one word back and is only
+ // needed for reverts, which only happen one back.
+ if (mMainLogBuffer == null) {
+ return;
+ }
+ final LogUnit oldLogUnit = mMainLogBuffer.peekLastLogUnit();
+
+ // Check that expected word matches.
+ if (oldLogUnit != null) {
+ final String oldLogUnitWord = oldLogUnit.getWord();
+ if (!oldLogUnitWord.equals(expectedWord)) {
+ return;
+ }
+ }
+
+ // Uncommit, merging if necessary.
+ mMainLogBuffer.unshiftIn();
+ if (oldLogUnit != null && !dumpCurrentLogUnit) {
+ oldLogUnit.append(mCurrentLogUnit);
+ mSavedDownEventTime = Long.MAX_VALUE;
+ }
+ if (oldLogUnit == null) {
mCurrentLogUnit = new LogUnit();
- Log.d(TAG, "commitCurrentLogUnit");
+ } else {
+ mCurrentLogUnit = oldLogUnit;
+ }
+ if (mFeedbackLogBuffer != null) {
+ mFeedbackLogBuffer.unshiftIn();
+ }
+ enqueueEvent(LOGSTATEMENT_UNCOMMIT_CURRENT_LOGUNIT);
+ if (DEBUG) {
+ Log.d(TAG, "uncommitCurrentLogUnit (dump=" + dumpCurrentLogUnit + ") back to "
+ + (mCurrentLogUnit.hasWord() ? ": '" + mCurrentLogUnit.getWord() + "'" : ""));
}
}
+ /**
+ * Publish all the logUnits in the logBuffer, without doing any privacy filtering.
+ */
/* package for test */ void publishLogBuffer(final LogBuffer logBuffer,
- final ResearchLog researchLog, final boolean isIncludingPrivateData) {
- LogUnit logUnit;
- while ((logUnit = logBuffer.shiftOut()) != null) {
- researchLog.publish(logUnit, isIncludingPrivateData);
+ final ResearchLog researchLog, final boolean canIncludePrivateData) {
+ publishLogUnits(logBuffer.getLogUnits(), researchLog, canIncludePrivateData);
+ }
+
+ private static final LogStatement LOGSTATEMENT_LOG_SEGMENT_OPENING =
+ new LogStatement("logSegmentStart", false, false, "isIncludingPrivateData");
+ private static final LogStatement LOGSTATEMENT_LOG_SEGMENT_CLOSING =
+ new LogStatement("logSegmentEnd", false, false);
+ /**
+ * Publish all LogUnits in a list.
+ *
+ * Any privacy checks should be performed before calling this method.
+ */
+ /* package for test */ void publishLogUnits(final List<LogUnit> logUnits,
+ final ResearchLog researchLog, final boolean canIncludePrivateData) {
+ final LogUnit openingLogUnit = new LogUnit();
+ if (logUnits.isEmpty()) return;
+ // LogUnits not containing private data, such as contextual data for the log, do not require
+ // logSegment boundary statements.
+ if (canIncludePrivateData) {
+ openingLogUnit.addLogStatement(LOGSTATEMENT_LOG_SEGMENT_OPENING,
+ SystemClock.uptimeMillis(), canIncludePrivateData);
+ researchLog.publish(openingLogUnit, true /* isIncludingPrivateData */);
+ }
+ for (LogUnit logUnit : logUnits) {
+ if (DEBUG) {
+ Log.d(TAG, "publishLogBuffer: " + (logUnit.hasWord() ? logUnit.getWord()
+ : "<wordless>") + ", correction?: " + logUnit.containsCorrection());
+ }
+ researchLog.publish(logUnit, canIncludePrivateData);
+ }
+ if (canIncludePrivateData) {
+ final LogUnit closingLogUnit = new LogUnit();
+ closingLogUnit.addLogStatement(LOGSTATEMENT_LOG_SEGMENT_CLOSING,
+ SystemClock.uptimeMillis());
+ researchLog.publish(closingLogUnit, true /* isIncludingPrivateData */);
}
}
- private boolean hasOnlyLetters(final String word) {
+ public static boolean hasLetters(final String word) {
final int length = word.length();
for (int i = 0; i < length; i = word.offsetByCodePoints(i, 1)) {
final int codePoint = word.codePointAt(i);
- if (!Character.isLetter(codePoint)) {
- return false;
+ if (Character.isLetter(codePoint)) {
+ return true;
}
}
- return true;
+ return false;
}
- private void onWordComplete(final String word) {
- Log.d(TAG, "onWordComplete: " + word);
- if (word != null && word.length() > 0 && hasOnlyLetters(word)) {
+ /**
+ * Commit the portion of mCurrentLogUnit before maxTime as a worded logUnit.
+ *
+ * After this operation completes, mCurrentLogUnit will hold any logStatements that happened
+ * after maxTime.
+ */
+ /* package for test */ void commitCurrentLogUnitAsWord(final String word, final long maxTime,
+ final boolean isBatchMode) {
+ if (word == null) {
+ return;
+ }
+ if (word.length() > 0 && hasLetters(word)) {
mCurrentLogUnit.setWord(word);
- mStatistics.recordWordEntered();
}
+ final LogUnit newLogUnit = mCurrentLogUnit.splitByTime(maxTime);
+ enqueueCommitText(word, isBatchMode);
commitCurrentLogUnit();
+ mCurrentLogUnit = newLogUnit;
+ }
+
+ /**
+ * Record the time of a MotionEvent.ACTION_DOWN.
+ *
+ * Warning: Not thread safe. Only call from the main thread.
+ */
+ private void setSavedDownEventTime(final long time) {
+ mSavedDownEventTime = time;
+ }
+
+ public void onWordFinished(final String word, final boolean isBatchMode) {
+ commitCurrentLogUnitAsWord(word, mSavedDownEventTime, isBatchMode);
+ mSavedDownEventTime = Long.MAX_VALUE;
}
private static int scrubDigitFromCodePoint(int codePoint) {
@@ -775,120 +1150,141 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
private String scrubWord(String word) {
- if (mDictionary == null) {
+ final Dictionary dictionary = getDictionary();
+ if (dictionary == null) {
return WORD_REPLACEMENT_STRING;
}
- if (mDictionary.isValidWord(word)) {
+ if (dictionary.isValidWord(word)) {
return word;
}
return WORD_REPLACEMENT_STRING;
}
- private static final String[] EVENTKEYS_LATINIME_ONSTARTINPUTVIEWINTERNAL = {
- "LatinIMEOnStartInputViewInternal", "uuid", "packageName", "inputType", "imeOptions",
- "fieldId", "display", "model", "prefs", "versionCode", "versionName", "outputFormatVersion"
- };
+ // Specific logging methods follow below. The comments for each logging method should
+ // indicate what specific method is logged, and how to trigger it from the user interface.
+ //
+ // Logging methods can be generally classified into two flavors, "UserAction", which should
+ // correspond closely to an event that is sensed by the IME, and is usually generated
+ // directly by the user, and "SystemResponse" which corresponds to an event that the IME
+ // generates, often after much processing of user input. SystemResponses should correspond
+ // closely to user-visible events.
+ // TODO: Consider exposing the UserAction classification in the log output.
+
+ /**
+ * Log a call to LatinIME.onStartInputViewInternal().
+ *
+ * UserAction: called each time the keyboard is opened up.
+ */
+ private static final LogStatement LOGSTATEMENT_LATIN_IME_ON_START_INPUT_VIEW_INTERNAL =
+ new LogStatement("LatinImeOnStartInputViewInternal", false, false, "uuid",
+ "packageName", "inputType", "imeOptions", "fieldId", "display", "model",
+ "prefs", "versionCode", "versionName", "outputFormatVersion", "logEverything",
+ "isExperimentalDebug");
public static void latinIME_onStartInputViewInternal(final EditorInfo editorInfo,
final SharedPreferences prefs) {
final ResearchLogger researchLogger = getInstance();
- researchLogger.start();
if (editorInfo != null) {
- final Context context = researchLogger.mInputMethodService;
+ final boolean isPassword = InputTypeUtils.isPasswordInputType(editorInfo.inputType)
+ || InputTypeUtils.isVisiblePasswordInputType(editorInfo.inputType);
+ getInstance().setIsPasswordView(isPassword);
+ researchLogger.start();
+ final Context context = researchLogger.mLatinIME;
try {
final PackageInfo packageInfo;
packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
0);
final Integer versionCode = packageInfo.versionCode;
final String versionName = packageInfo.versionName;
- final Object[] values = {
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATIN_IME_ON_START_INPUT_VIEW_INTERNAL,
researchLogger.mUUIDString, editorInfo.packageName,
Integer.toHexString(editorInfo.inputType),
Integer.toHexString(editorInfo.imeOptions), editorInfo.fieldId,
Build.DISPLAY, Build.MODEL, prefs, versionCode, versionName,
- OUTPUT_FORMAT_VERSION
- };
- researchLogger.enqueueEvent(EVENTKEYS_LATINIME_ONSTARTINPUTVIEWINTERNAL, values);
+ OUTPUT_FORMAT_VERSION, IS_LOGGING_EVERYTHING,
+ ProductionFlag.IS_EXPERIMENTAL_DEBUG);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
- public void latinIME_onFinishInputInternal() {
+ public void latinIME_onFinishInputViewInternal() {
stop();
}
- private static final String[] EVENTKEYS_USER_FEEDBACK = {
- "UserFeedback", "FeedbackContents"
- };
-
- private static final String[] EVENTKEYS_PREFS_CHANGED = {
- "PrefsChanged", "prefs"
- };
+ /**
+ * Log a change in preferences.
+ *
+ * UserAction: called when the user changes the settings.
+ */
+ private static final LogStatement LOGSTATEMENT_PREFS_CHANGED =
+ new LogStatement("PrefsChanged", false, false, "prefs");
public static void prefsChanged(final SharedPreferences prefs) {
final ResearchLogger researchLogger = getInstance();
- final Object[] values = {
- prefs
- };
- researchLogger.enqueueEvent(EVENTKEYS_PREFS_CHANGED, values);
+ researchLogger.enqueueEvent(LOGSTATEMENT_PREFS_CHANGED, prefs);
}
- // Regular logging methods
-
- private static final String[] EVENTKEYS_MAINKEYBOARDVIEW_PROCESSMOTIONEVENT = {
- "MainKeyboardViewProcessMotionEvent", "action", "eventTime", "id", "x", "y", "size",
- "pressure"
- };
+ /**
+ * Log a call to MainKeyboardView.processMotionEvent().
+ *
+ * UserAction: called when the user puts their finger onto the screen (ACTION_DOWN).
+ *
+ */
+ private static final LogStatement LOGSTATEMENT_MAIN_KEYBOARD_VIEW_PROCESS_MOTION_EVENT =
+ new LogStatement("MotionEvent", true, false, "action",
+ LogStatement.KEY_IS_LOGGING_RELATED, "motionEvent");
public static void mainKeyboardView_processMotionEvent(final MotionEvent me, final int action,
final long eventTime, final int index, final int id, final int x, final int y) {
if (me != null) {
- final String actionString;
- switch (action) {
- case MotionEvent.ACTION_CANCEL: actionString = "CANCEL"; break;
- case MotionEvent.ACTION_UP: actionString = "UP"; break;
- case MotionEvent.ACTION_DOWN: actionString = "DOWN"; break;
- case MotionEvent.ACTION_POINTER_UP: actionString = "POINTER_UP"; break;
- case MotionEvent.ACTION_POINTER_DOWN: actionString = "POINTER_DOWN"; break;
- case MotionEvent.ACTION_MOVE: actionString = "MOVE"; break;
- case MotionEvent.ACTION_OUTSIDE: actionString = "OUTSIDE"; break;
- default: actionString = "ACTION_" + action; break;
+ final String actionString = LoggingUtils.getMotionEventActionTypeString(action);
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_MAIN_KEYBOARD_VIEW_PROCESS_MOTION_EVENT,
+ actionString, false /* IS_LOGGING_RELATED */, MotionEvent.obtain(me));
+ if (action == MotionEvent.ACTION_DOWN) {
+ // Subtract 1 from eventTime so the down event is included in the later
+ // LogUnit, not the earlier (the test is for inequality).
+ researchLogger.setSavedDownEventTime(eventTime - 1);
+ }
+ // Refresh the timer in case we are capturing user feedback.
+ if (researchLogger.isMakingUserRecording()) {
+ researchLogger.resetRecordingTimer();
}
- final float size = me.getSize(index);
- final float pressure = me.getPressure(index);
- final Object[] values = {
- actionString, eventTime, id, x, y, size, pressure
- };
- getInstance().enqueuePotentiallyPrivateEvent(
- EVENTKEYS_MAINKEYBOARDVIEW_PROCESSMOTIONEVENT, values);
}
}
- private static final String[] EVENTKEYS_LATINIME_ONCODEINPUT = {
- "LatinIMEOnCodeInput", "code", "x", "y"
- };
+ /**
+ * Log a call to LatinIME.onCodeInput().
+ *
+ * SystemResponse: The main processing step for entering text. Called when the user performs a
+ * tap, a flick, a long press, releases a gesture, or taps a punctuation suggestion.
+ */
+ private static final LogStatement LOGSTATEMENT_LATIN_IME_ON_CODE_INPUT =
+ new LogStatement("LatinImeOnCodeInput", true, false, "code", "x", "y");
public static void latinIME_onCodeInput(final int code, final int x, final int y) {
final long time = SystemClock.uptimeMillis();
final ResearchLogger researchLogger = getInstance();
- final Object[] values = {
- Keyboard.printableCode(scrubDigitFromCodePoint(code)), x, y
- };
- researchLogger.enqueuePotentiallyPrivateEvent(EVENTKEYS_LATINIME_ONCODEINPUT, values);
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATIN_IME_ON_CODE_INPUT,
+ Constants.printableCode(scrubDigitFromCodePoint(code)), x, y);
if (Character.isDigit(code)) {
researchLogger.setCurrentLogUnitContainsDigitFlag();
}
researchLogger.mStatistics.recordChar(code, time);
}
-
- private static final String[] EVENTKEYS_LATINIME_ONDISPLAYCOMPLETIONS = {
- "LatinIMEOnDisplayCompletions", "applicationSpecifiedCompletions"
- };
+ /**
+ * Log a call to LatinIME.onDisplayCompletions().
+ *
+ * SystemResponse: The IME has displayed application-specific completions. They may show up
+ * in the suggestion strip, such as a landscape phone.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_ONDISPLAYCOMPLETIONS =
+ new LogStatement("LatinIMEOnDisplayCompletions", true, true,
+ "applicationSpecifiedCompletions");
public static void latinIME_onDisplayCompletions(
final CompletionInfo[] applicationSpecifiedCompletions) {
- final Object[] values = {
- applicationSpecifiedCompletions
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_LATINIME_ONDISPLAYCOMPLETIONS,
- values);
+ // Note; passing an array as a single element in a vararg list. Must create a new
+ // dummy array around it or it will get expanded.
+ getInstance().enqueueEvent(LOGSTATEMENT_LATINIME_ONDISPLAYCOMPLETIONS,
+ new Object[] { applicationSpecifiedCompletions });
}
public static boolean getAndClearLatinIMEExpectingUpdateSelection() {
@@ -897,27 +1293,35 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
return returnValue;
}
- private static final String[] EVENTKEYS_LATINIME_ONWINDOWHIDDEN = {
- "LatinIMEOnWindowHidden", "isTextTruncated", "text"
- };
+ /**
+ * Log a call to LatinIME.onWindowHidden().
+ *
+ * UserAction: The user has performed an action that has caused the IME to be closed. They may
+ * have focused on something other than a text field, or explicitly closed it.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_ONWINDOWHIDDEN =
+ new LogStatement("LatinIMEOnWindowHidden", false, false, "isTextTruncated", "text");
public static void latinIME_onWindowHidden(final int savedSelectionStart,
final int savedSelectionEnd, final InputConnection ic) {
if (ic != null) {
- // Capture the TextView contents. This will trigger onUpdateSelection(), so we
- // set sLatinIMEExpectingUpdateSelection so that when onUpdateSelection() is called,
- // it can tell that it was generated by the logging code, and not by the user, and
- // therefore keep user-visible state as is.
- ic.beginBatchEdit();
- ic.performContextMenuAction(android.R.id.selectAll);
- CharSequence charSequence = ic.getSelectedText(0);
- ic.setSelection(savedSelectionStart, savedSelectionEnd);
- ic.endBatchEdit();
- sLatinIMEExpectingUpdateSelection = true;
- final Object[] values = new Object[2];
- if (OUTPUT_ENTIRE_BUFFER) {
+ final boolean isTextTruncated;
+ final String text;
+ if (LOG_FULL_TEXTVIEW_CONTENTS) {
+ // Capture the TextView contents. This will trigger onUpdateSelection(), so we
+ // set sLatinIMEExpectingUpdateSelection so that when onUpdateSelection() is called,
+ // it can tell that it was generated by the logging code, and not by the user, and
+ // therefore keep user-visible state as is.
+ ic.beginBatchEdit();
+ ic.performContextMenuAction(android.R.id.selectAll);
+ CharSequence charSequence = ic.getSelectedText(0);
+ if (savedSelectionStart != -1 && savedSelectionEnd != -1) {
+ ic.setSelection(savedSelectionStart, savedSelectionEnd);
+ }
+ ic.endBatchEdit();
+ sLatinIMEExpectingUpdateSelection = true;
if (TextUtils.isEmpty(charSequence)) {
- values[0] = false;
- values[1] = "";
+ isTextTruncated = false;
+ text = "";
} else {
if (charSequence.length() > MAX_INPUTVIEW_LENGTH_TO_CAPTURE) {
int length = MAX_INPUTVIEW_LENGTH_TO_CAPTURE;
@@ -928,29 +1332,39 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
final CharSequence truncatedCharSequence = charSequence.subSequence(0,
length);
- values[0] = true;
- values[1] = truncatedCharSequence.toString();
+ isTextTruncated = true;
+ text = truncatedCharSequence.toString();
} else {
- values[0] = false;
- values[1] = charSequence.toString();
+ isTextTruncated = false;
+ text = charSequence.toString();
}
}
} else {
- values[0] = true;
- values[1] = "";
+ isTextTruncated = true;
+ text = "";
}
final ResearchLogger researchLogger = getInstance();
- researchLogger.enqueueEvent(EVENTKEYS_LATINIME_ONWINDOWHIDDEN, values);
+ // Assume that OUTPUT_ENTIRE_BUFFER is only true when we don't care about privacy (e.g.
+ // during a live user test), so the normal isPotentiallyPrivate and
+ // isPotentiallyRevealing flags do not apply
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_ONWINDOWHIDDEN, isTextTruncated,
+ text);
researchLogger.commitCurrentLogUnit();
getInstance().stop();
}
}
- private static final String[] EVENTKEYS_LATINIME_ONUPDATESELECTION = {
- "LatinIMEOnUpdateSelection", "lastSelectionStart", "lastSelectionEnd", "oldSelStart",
- "oldSelEnd", "newSelStart", "newSelEnd", "composingSpanStart", "composingSpanEnd",
- "expectingUpdateSelection", "expectingUpdateSelectionFromLogger", "context"
- };
+ /**
+ * Log a call to LatinIME.onUpdateSelection().
+ *
+ * UserAction/SystemResponse: The user has moved the cursor or selection. This function may
+ * be called, however, when the system has moved the cursor, say by inserting a character.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_ONUPDATESELECTION =
+ new LogStatement("LatinIMEOnUpdateSelection", true, false, "lastSelectionStart",
+ "lastSelectionEnd", "oldSelStart", "oldSelEnd", "newSelStart", "newSelEnd",
+ "composingSpanStart", "composingSpanEnd", "expectingUpdateSelection",
+ "expectingUpdateSelectionFromLogger", "context");
public static void latinIME_onUpdateSelection(final int lastSelectionStart,
final int lastSelectionEnd, final int oldSelStart, final int oldSelEnd,
final int newSelStart, final int newSelEnd, final int composingSpanStart,
@@ -966,350 +1380,649 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
final ResearchLogger researchLogger = getInstance();
final String scrubbedWord = researchLogger.scrubWord(word);
- final Object[] values = {
- lastSelectionStart, lastSelectionEnd, oldSelStart, oldSelEnd, newSelStart,
- newSelEnd, composingSpanStart, composingSpanEnd, expectingUpdateSelection,
- expectingUpdateSelectionFromLogger, scrubbedWord
- };
- researchLogger.enqueuePotentiallyPrivateEvent(EVENTKEYS_LATINIME_ONUPDATESELECTION, values);
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_ONUPDATESELECTION, lastSelectionStart,
+ lastSelectionEnd, oldSelStart, oldSelEnd, newSelStart, newSelEnd,
+ composingSpanStart, composingSpanEnd, expectingUpdateSelection,
+ expectingUpdateSelectionFromLogger, scrubbedWord);
}
- private static final String[] EVENTKEYS_LATINIME_PICKSUGGESTIONMANUALLY = {
- "LatinIMEPickSuggestionManually", "replacedWord", "index", "suggestion", "x", "y"
- };
+ /**
+ * Log a call to LatinIME.onTextInput().
+ *
+ * SystemResponse: Raw text is added to the TextView.
+ */
+ public static void latinIME_onTextInput(final String text, final boolean isBatchMode) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.commitCurrentLogUnitAsWord(text, Long.MAX_VALUE, isBatchMode);
+ }
+
+ /**
+ * Log a call to LatinIME.pickSuggestionManually().
+ *
+ * UserAction: The user has chosen a specific word from the suggestion strip.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_PICKSUGGESTIONMANUALLY =
+ new LogStatement("LatinIMEPickSuggestionManually", true, false, "replacedWord", "index",
+ "suggestion", "x", "y", "isBatchMode");
public static void latinIME_pickSuggestionManually(final String replacedWord,
- final int index, CharSequence suggestion) {
- final Object[] values = {
- scrubDigitsFromString(replacedWord), index,
- (suggestion == null ? null : scrubDigitsFromString(suggestion.toString())),
- Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE
- };
+ final int index, final String suggestion, final boolean isBatchMode) {
final ResearchLogger researchLogger = getInstance();
- researchLogger.enqueuePotentiallyPrivateEvent(EVENTKEYS_LATINIME_PICKSUGGESTIONMANUALLY,
- values);
+ if (!replacedWord.equals(suggestion.toString())) {
+ // The user chose something other than what was already there.
+ researchLogger.setCurrentLogUnitContainsCorrection();
+ researchLogger.setCurrentLogUnitCorrectionType(LogUnit.CORRECTIONTYPE_TYPO);
+ }
+ final String scrubbedWord = scrubDigitsFromString(suggestion);
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_PICKSUGGESTIONMANUALLY,
+ scrubDigitsFromString(replacedWord), index,
+ suggestion == null ? null : scrubbedWord, Constants.SUGGESTION_STRIP_COORDINATE,
+ Constants.SUGGESTION_STRIP_COORDINATE, isBatchMode);
+ researchLogger.commitCurrentLogUnitAsWord(scrubbedWord, Long.MAX_VALUE, isBatchMode);
+ researchLogger.mStatistics.recordManualSuggestion(SystemClock.uptimeMillis());
}
- private static final String[] EVENTKEYS_LATINIME_PUNCTUATIONSUGGESTION = {
- "LatinIMEPunctuationSuggestion", "index", "suggestion", "x", "y"
- };
- public static void latinIME_punctuationSuggestion(final int index,
- final CharSequence suggestion) {
- final Object[] values = {
- index, suggestion,
- Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE
- };
- getInstance().enqueueEvent(EVENTKEYS_LATINIME_PUNCTUATIONSUGGESTION, values);
+ /**
+ * Log a call to LatinIME.punctuationSuggestion().
+ *
+ * UserAction: The user has chosen punctuation from the punctuation suggestion strip.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_PUNCTUATIONSUGGESTION =
+ new LogStatement("LatinIMEPunctuationSuggestion", false, false, "index", "suggestion",
+ "x", "y", "isPrediction");
+ public static void latinIME_punctuationSuggestion(final int index, final String suggestion,
+ final boolean isBatchMode, final boolean isPrediction) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_PUNCTUATIONSUGGESTION, index, suggestion,
+ Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE,
+ isPrediction);
+ researchLogger.commitCurrentLogUnitAsWord(suggestion, Long.MAX_VALUE, isBatchMode);
}
- private static final String[] EVENTKEYS_LATINIME_SENDKEYCODEPOINT = {
- "LatinIMESendKeyCodePoint", "code"
- };
+ /**
+ * Log a call to LatinIME.sendKeyCodePoint().
+ *
+ * SystemResponse: The IME is inserting text into the TextView for numbers, fixed strings, or
+ * some other unusual mechanism.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_SENDKEYCODEPOINT =
+ new LogStatement("LatinIMESendKeyCodePoint", true, false, "code");
public static void latinIME_sendKeyCodePoint(final int code) {
- final Object[] values = {
- Keyboard.printableCode(scrubDigitFromCodePoint(code))
- };
final ResearchLogger researchLogger = getInstance();
- researchLogger.enqueuePotentiallyPrivateEvent(EVENTKEYS_LATINIME_SENDKEYCODEPOINT, values);
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_SENDKEYCODEPOINT,
+ Constants.printableCode(scrubDigitFromCodePoint(code)));
if (Character.isDigit(code)) {
researchLogger.setCurrentLogUnitContainsDigitFlag();
}
}
- private static final String[] EVENTKEYS_LATINIME_SWAPSWAPPERANDSPACE = {
- "LatinIMESwapSwapperAndSpace"
- };
- public static void latinIME_swapSwapperAndSpace() {
- getInstance().enqueueEvent(EVENTKEYS_LATINIME_SWAPSWAPPERANDSPACE, EVENTKEYS_NULLVALUES);
+ /**
+ * Log a call to LatinIME.promotePhantomSpace().
+ *
+ * SystemResponse: The IME is inserting a real space in place of a phantom space.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_PROMOTEPHANTOMSPACE =
+ new LogStatement("LatinIMEPromotPhantomSpace", false, false);
+ public static void latinIME_promotePhantomSpace() {
+ final ResearchLogger researchLogger = getInstance();
+ final LogUnit logUnit;
+ if (researchLogger.mMainLogBuffer == null) {
+ logUnit = researchLogger.mCurrentLogUnit;
+ } else {
+ logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
+ }
+ researchLogger.enqueueEvent(logUnit, LOGSTATEMENT_LATINIME_PROMOTEPHANTOMSPACE);
}
- private static final String[] EVENTKEYS_MAINKEYBOARDVIEW_ONLONGPRESS = {
- "MainKeyboardViewOnLongPress"
- };
+ /**
+ * Log a call to LatinIME.swapSwapperAndSpace().
+ *
+ * SystemResponse: A symbol has been swapped with a space character. E.g. punctuation may swap
+ * if a soft space is inserted after a word.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_SWAPSWAPPERANDSPACE =
+ new LogStatement("LatinIMESwapSwapperAndSpace", false, false, "originalCharacters",
+ "charactersAfterSwap");
+ public static void latinIME_swapSwapperAndSpace(final CharSequence originalCharacters,
+ final String charactersAfterSwap) {
+ final ResearchLogger researchLogger = getInstance();
+ final LogUnit logUnit;
+ if (researchLogger.mMainLogBuffer == null) {
+ logUnit = null;
+ } else {
+ logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
+ }
+ if (logUnit != null) {
+ researchLogger.enqueueEvent(logUnit, LOGSTATEMENT_LATINIME_SWAPSWAPPERANDSPACE,
+ originalCharacters, charactersAfterSwap);
+ }
+ }
+
+ /**
+ * Log a call to LatinIME.maybeDoubleSpacePeriod().
+ *
+ * SystemResponse: Two spaces have been replaced by period space.
+ */
+ public static void latinIME_maybeDoubleSpacePeriod(final String text,
+ final boolean isBatchMode) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.commitCurrentLogUnitAsWord(text, Long.MAX_VALUE, isBatchMode);
+ }
+
+ /**
+ * Log a call to MainKeyboardView.onLongPress().
+ *
+ * UserAction: The user has performed a long-press on a key.
+ */
+ private static final LogStatement LOGSTATEMENT_MAINKEYBOARDVIEW_ONLONGPRESS =
+ new LogStatement("MainKeyboardViewOnLongPress", false, false);
public static void mainKeyboardView_onLongPress() {
- getInstance().enqueueEvent(EVENTKEYS_MAINKEYBOARDVIEW_ONLONGPRESS, EVENTKEYS_NULLVALUES);
+ getInstance().enqueueEvent(LOGSTATEMENT_MAINKEYBOARDVIEW_ONLONGPRESS);
}
- private static final String[] EVENTKEYS_MAINKEYBOARDVIEW_SETKEYBOARD = {
- "MainKeyboardViewSetKeyboard", "elementId", "locale", "orientation", "width",
- "modeName", "action", "navigateNext", "navigatePrevious", "clobberSettingsKey",
- "passwordInput", "shortcutKeyEnabled", "hasShortcutKey", "languageSwitchKeyEnabled",
- "isMultiLine", "tw", "th", "keys"
- };
+ /**
+ * Log a call to MainKeyboardView.setKeyboard().
+ *
+ * SystemResponse: The IME has switched to a new keyboard (e.g. French, English).
+ * This is typically called right after LatinIME.onStartInputViewInternal (when starting a new
+ * IME), but may happen at other times if the user explicitly requests a keyboard change.
+ */
+ private static final LogStatement LOGSTATEMENT_MAINKEYBOARDVIEW_SETKEYBOARD =
+ new LogStatement("MainKeyboardViewSetKeyboard", false, false, "elementId", "locale",
+ "orientation", "width", "modeName", "action", "navigateNext",
+ "navigatePrevious", "clobberSettingsKey", "passwordInput", "shortcutKeyEnabled",
+ "hasShortcutKey", "languageSwitchKeyEnabled", "isMultiLine", "tw", "th",
+ "keys");
public static void mainKeyboardView_setKeyboard(final Keyboard keyboard) {
- if (keyboard != null) {
- final KeyboardId kid = keyboard.mId;
- final boolean isPasswordView = kid.passwordInput();
- getInstance().setIsPasswordView(isPasswordView);
- final Object[] values = {
+ final KeyboardId kid = keyboard.mId;
+ final boolean isPasswordView = kid.passwordInput();
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.setIsPasswordView(isPasswordView);
+ researchLogger.enqueueEvent(LOGSTATEMENT_MAINKEYBOARDVIEW_SETKEYBOARD,
KeyboardId.elementIdToName(kid.mElementId),
kid.mLocale + ":" + kid.mSubtype.getExtraValueOf(KEYBOARD_LAYOUT_SET),
- kid.mOrientation,
- kid.mWidth,
- KeyboardId.modeName(kid.mMode),
- kid.imeAction(),
- kid.navigateNext(),
- kid.navigatePrevious(),
- kid.mClobberSettingsKey,
- isPasswordView,
- kid.mShortcutKeyEnabled,
- kid.mHasShortcutKey,
- kid.mLanguageSwitchKeyEnabled,
- kid.isMultiLine(),
- keyboard.mOccupiedWidth,
- keyboard.mOccupiedHeight,
- keyboard.mKeys
- };
- getInstance().setIsPasswordView(isPasswordView);
- getInstance().enqueueEvent(EVENTKEYS_MAINKEYBOARDVIEW_SETKEYBOARD, values);
- }
+ kid.mOrientation, kid.mWidth, KeyboardId.modeName(kid.mMode), kid.imeAction(),
+ kid.navigateNext(), kid.navigatePrevious(), kid.mClobberSettingsKey,
+ isPasswordView, kid.mShortcutKeyEnabled, kid.mHasShortcutKey,
+ kid.mLanguageSwitchKeyEnabled, kid.isMultiLine(), keyboard.mOccupiedWidth,
+ keyboard.mOccupiedHeight, keyboard.mKeys);
}
- private static final String[] EVENTKEYS_LATINIME_REVERTCOMMIT = {
- "LatinIMERevertCommit", "originallyTypedWord"
- };
- public static void latinIME_revertCommit(final String originallyTypedWord) {
- final Object[] values = {
- originallyTypedWord
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_LATINIME_REVERTCOMMIT, values);
+ /**
+ * Log a call to LatinIME.revertCommit().
+ *
+ * SystemResponse: The IME has reverted commited text. This happens when the user enters
+ * a word, commits it by pressing space or punctuation, and then reverts the commit by hitting
+ * backspace.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_REVERTCOMMIT =
+ new LogStatement("LatinIMERevertCommit", true, false, "committedWord",
+ "originallyTypedWord", "separatorString");
+ public static void latinIME_revertCommit(final String committedWord,
+ final String originallyTypedWord, final boolean isBatchMode,
+ final String separatorString) {
+ final ResearchLogger researchLogger = getInstance();
+ // TODO: Verify that mCurrentLogUnit has been restored and contains the reverted word.
+ final LogUnit logUnit;
+ if (researchLogger.mMainLogBuffer == null) {
+ logUnit = null;
+ } else {
+ logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
+ }
+ if (originallyTypedWord.length() > 0 && hasLetters(originallyTypedWord)) {
+ if (logUnit != null) {
+ logUnit.setWord(originallyTypedWord);
+ }
+ }
+ researchLogger.enqueueEvent(logUnit != null ? logUnit : researchLogger.mCurrentLogUnit,
+ LOGSTATEMENT_LATINIME_REVERTCOMMIT, committedWord, originallyTypedWord,
+ separatorString);
+ if (logUnit != null) {
+ logUnit.setContainsCorrection();
+ }
+ researchLogger.mStatistics.recordRevertCommit(SystemClock.uptimeMillis());
+ researchLogger.commitCurrentLogUnitAsWord(originallyTypedWord, Long.MAX_VALUE, isBatchMode);
}
- private static final String[] EVENTKEYS_POINTERTRACKER_CALLLISTENERONCANCELINPUT = {
- "PointerTrackerCallListenerOnCancelInput"
- };
+ /**
+ * Log a call to PointerTracker.callListenerOnCancelInput().
+ *
+ * UserAction: The user has canceled the input, e.g., by pressing down, but then removing
+ * outside the keyboard area.
+ * TODO: Verify
+ */
+ private static final LogStatement LOGSTATEMENT_POINTERTRACKER_CALLLISTENERONCANCELINPUT =
+ new LogStatement("PointerTrackerCallListenerOnCancelInput", false, false);
public static void pointerTracker_callListenerOnCancelInput() {
- getInstance().enqueueEvent(EVENTKEYS_POINTERTRACKER_CALLLISTENERONCANCELINPUT,
- EVENTKEYS_NULLVALUES);
+ getInstance().enqueueEvent(LOGSTATEMENT_POINTERTRACKER_CALLLISTENERONCANCELINPUT);
}
- private static final String[] EVENTKEYS_POINTERTRACKER_CALLLISTENERONCODEINPUT = {
- "PointerTrackerCallListenerOnCodeInput", "code", "outputText", "x", "y",
- "ignoreModifierKey", "altersCode", "isEnabled"
- };
+ /**
+ * Log a call to PointerTracker.callListenerOnCodeInput().
+ *
+ * SystemResponse: The user has entered a key through the normal tapping mechanism.
+ * LatinIME.onCodeInput will also be called.
+ */
+ private static final LogStatement LOGSTATEMENT_POINTERTRACKER_CALLLISTENERONCODEINPUT =
+ new LogStatement("PointerTrackerCallListenerOnCodeInput", true, false, "code",
+ "outputText", "x", "y", "ignoreModifierKey", "altersCode", "isEnabled");
public static void pointerTracker_callListenerOnCodeInput(final Key key, final int x,
final int y, final boolean ignoreModifierKey, final boolean altersCode,
final int code) {
if (key != null) {
String outputText = key.getOutputText();
- final Object[] values = {
- Keyboard.printableCode(scrubDigitFromCodePoint(code)), outputText == null ? null
- : scrubDigitsFromString(outputText.toString()),
- x, y, ignoreModifierKey, altersCode, key.isEnabled()
- };
- getInstance().enqueuePotentiallyPrivateEvent(
- EVENTKEYS_POINTERTRACKER_CALLLISTENERONCODEINPUT, values);
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_POINTERTRACKER_CALLLISTENERONCODEINPUT,
+ Constants.printableCode(scrubDigitFromCodePoint(code)),
+ outputText == null ? null : scrubDigitsFromString(outputText.toString()),
+ x, y, ignoreModifierKey, altersCode, key.isEnabled());
+ if (code == Constants.CODE_RESEARCH) {
+ researchLogger.suppressResearchKeyMotionData();
+ }
}
}
- private static final String[] EVENTKEYS_POINTERTRACKER_CALLLISTENERONRELEASE = {
- "PointerTrackerCallListenerOnRelease", "code", "withSliding", "ignoreModifierKey",
- "isEnabled"
- };
+ private void suppressResearchKeyMotionData() {
+ mCurrentLogUnit.removeResearchButtonInvocation();
+ }
+
+ /**
+ * Log a call to PointerTracker.callListenerCallListenerOnRelease().
+ *
+ * UserAction: The user has released their finger or thumb from the screen.
+ */
+ private static final LogStatement LOGSTATEMENT_POINTERTRACKER_CALLLISTENERONRELEASE =
+ new LogStatement("PointerTrackerCallListenerOnRelease", true, false, "code",
+ "withSliding", "ignoreModifierKey", "isEnabled");
public static void pointerTracker_callListenerOnRelease(final Key key, final int primaryCode,
final boolean withSliding, final boolean ignoreModifierKey) {
if (key != null) {
- final Object[] values = {
- Keyboard.printableCode(scrubDigitFromCodePoint(primaryCode)), withSliding,
- ignoreModifierKey, key.isEnabled()
- };
- getInstance().enqueuePotentiallyPrivateEvent(
- EVENTKEYS_POINTERTRACKER_CALLLISTENERONRELEASE, values);
+ getInstance().enqueueEvent(LOGSTATEMENT_POINTERTRACKER_CALLLISTENERONRELEASE,
+ Constants.printableCode(scrubDigitFromCodePoint(primaryCode)), withSliding,
+ ignoreModifierKey, key.isEnabled());
}
}
- private static final String[] EVENTKEYS_POINTERTRACKER_ONDOWNEVENT = {
- "PointerTrackerOnDownEvent", "deltaT", "distanceSquared"
- };
+ /**
+ * Log a call to PointerTracker.onDownEvent().
+ *
+ * UserAction: The user has pressed down on a key.
+ * TODO: Differentiate with LatinIME.processMotionEvent.
+ */
+ private static final LogStatement LOGSTATEMENT_POINTERTRACKER_ONDOWNEVENT =
+ new LogStatement("PointerTrackerOnDownEvent", true, false, "deltaT", "distanceSquared");
public static void pointerTracker_onDownEvent(long deltaT, int distanceSquared) {
- final Object[] values = {
- deltaT, distanceSquared
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_POINTERTRACKER_ONDOWNEVENT, values);
+ getInstance().enqueueEvent(LOGSTATEMENT_POINTERTRACKER_ONDOWNEVENT, deltaT,
+ distanceSquared);
}
- private static final String[] EVENTKEYS_POINTERTRACKER_ONMOVEEVENT = {
- "PointerTrackerOnMoveEvent", "x", "y", "lastX", "lastY"
- };
+ /**
+ * Log a call to PointerTracker.onMoveEvent().
+ *
+ * UserAction: The user has moved their finger while pressing on the screen.
+ * TODO: Differentiate with LatinIME.processMotionEvent().
+ */
+ private static final LogStatement LOGSTATEMENT_POINTERTRACKER_ONMOVEEVENT =
+ new LogStatement("PointerTrackerOnMoveEvent", true, false, "x", "y", "lastX", "lastY");
public static void pointerTracker_onMoveEvent(final int x, final int y, final int lastX,
final int lastY) {
- final Object[] values = {
- x, y, lastX, lastY
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_POINTERTRACKER_ONMOVEEVENT, values);
+ getInstance().enqueueEvent(LOGSTATEMENT_POINTERTRACKER_ONMOVEEVENT, x, y, lastX, lastY);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_COMMITCOMPLETION = {
- "RichInputConnectionCommitCompletion", "completionInfo"
- };
+ /**
+ * Log a call to RichInputConnection.commitCompletion().
+ *
+ * SystemResponse: The IME has committed a completion. A completion is an application-
+ * specific suggestion that is presented in a pop-up menu in the TextView.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_COMMITCOMPLETION =
+ new LogStatement("RichInputConnectionCommitCompletion", true, false, "completionInfo");
public static void richInputConnection_commitCompletion(final CompletionInfo completionInfo) {
- final Object[] values = {
- completionInfo
- };
final ResearchLogger researchLogger = getInstance();
- researchLogger.enqueuePotentiallyPrivateEvent(
- EVENTKEYS_RICHINPUTCONNECTION_COMMITCOMPLETION, values);
- }
-
- // Disabled for privacy-protection reasons. Because this event comes after
- // richInputConnection_commitText, which is the event used to separate LogUnits, the
- // data in this event can be associated with the next LogUnit, revealing information
- // about the current word even if it was supposed to be suppressed. The occurrance of
- // autocorrection can be determined by examining the difference between the text strings in
- // the last call to richInputConnection_setComposingText before
- // richInputConnection_commitText, so it's not a data loss.
- // TODO: Figure out how to log this event without loss of privacy.
- /*
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_COMMITCORRECTION = {
- "RichInputConnectionCommitCorrection", "typedWord", "autoCorrection"
- };
- */
- public static void richInputConnection_commitCorrection(CorrectionInfo correctionInfo) {
- /*
- final String typedWord = correctionInfo.getOldText().toString();
- final String autoCorrection = correctionInfo.getNewText().toString();
- final Object[] values = {
- scrubDigitsFromString(typedWord), scrubDigitsFromString(autoCorrection)
- };
+ researchLogger.enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_COMMITCOMPLETION,
+ completionInfo);
+ }
+
+ /**
+ * Log a call to RichInputConnection.revertDoubleSpacePeriod().
+ *
+ * SystemResponse: The IME has reverted ". ", which had previously replaced two typed spaces.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_REVERTDOUBLESPACEPERIOD =
+ new LogStatement("RichInputConnectionRevertDoubleSpacePeriod", false, false);
+ public static void richInputConnection_revertDoubleSpacePeriod() {
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_REVERTDOUBLESPACEPERIOD);
+ }
+
+ /**
+ * Log a call to RichInputConnection.revertSwapPunctuation().
+ *
+ * SystemResponse: The IME has reverted a punctuation swap.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_REVERTSWAPPUNCTUATION =
+ new LogStatement("RichInputConnectionRevertSwapPunctuation", false, false);
+ public static void richInputConnection_revertSwapPunctuation() {
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_REVERTSWAPPUNCTUATION);
+ }
+
+ /**
+ * Log a call to LatinIME.commitCurrentAutoCorrection().
+ *
+ * SystemResponse: The IME has committed an auto-correction. An auto-correction changes the raw
+ * text input to another word that the user more likely desired to type.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_COMMITCURRENTAUTOCORRECTION =
+ new LogStatement("LatinIMECommitCurrentAutoCorrection", true, true, "typedWord",
+ "autoCorrection", "separatorString");
+ public static void latinIme_commitCurrentAutoCorrection(final String typedWord,
+ final String autoCorrection, final String separatorString, final boolean isBatchMode,
+ final SuggestedWords suggestedWords) {
+ final String scrubbedTypedWord = scrubDigitsFromString(typedWord);
+ final String scrubbedAutoCorrection = scrubDigitsFromString(autoCorrection);
final ResearchLogger researchLogger = getInstance();
- researchLogger.enqueuePotentiallyPrivateEvent(
- EVENTKEYS_RICHINPUTCONNECTION_COMMITCORRECTION, values);
- */
+ researchLogger.mCurrentLogUnit.initializeSuggestions(suggestedWords);
+ researchLogger.commitCurrentLogUnitAsWord(scrubbedAutoCorrection, Long.MAX_VALUE,
+ isBatchMode);
+
+ // Add the autocorrection logStatement at the end of the logUnit for the committed word.
+ // We have to do this after calling commitCurrentLogUnitAsWord, because it may split the
+ // current logUnit, and then we have to peek to get the logUnit reference back.
+ final LogUnit logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
+ // TODO: Add test to confirm that the commitCurrentAutoCorrection log statement should
+ // always be added to logUnit (if non-null) and not mCurrentLogUnit.
+ researchLogger.enqueueEvent(logUnit, LOGSTATEMENT_LATINIME_COMMITCURRENTAUTOCORRECTION,
+ scrubbedTypedWord, scrubbedAutoCorrection, separatorString);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_COMMITTEXT = {
- "RichInputConnectionCommitText", "typedWord", "newCursorPosition"
- };
- public static void richInputConnection_commitText(final CharSequence typedWord,
- final int newCursorPosition) {
- final String scrubbedWord = scrubDigitsFromString(typedWord.toString());
- final Object[] values = {
- scrubbedWord, newCursorPosition
- };
+ private boolean isExpectingCommitText = false;
+ /**
+ * Log a call to (UnknownClass).commitPartialText
+ *
+ * SystemResponse: The IME is committing part of a word. This happens if a space is
+ * automatically inserted to split a single typed string into two or more words.
+ */
+ // TODO: This method is currently unused. Find where it should be called from in the IME and
+ // add invocations.
+ private static final LogStatement LOGSTATEMENT_COMMIT_PARTIAL_TEXT =
+ new LogStatement("CommitPartialText", true, false, "newCursorPosition");
+ public static void commitPartialText(final String committedWord,
+ final long lastTimestampOfWordData, final boolean isBatchMode) {
final ResearchLogger researchLogger = getInstance();
- researchLogger.enqueuePotentiallyPrivateEvent(EVENTKEYS_RICHINPUTCONNECTION_COMMITTEXT,
- values);
- researchLogger.onWordComplete(scrubbedWord);
+ final String scrubbedWord = scrubDigitsFromString(committedWord);
+ researchLogger.enqueueEvent(LOGSTATEMENT_COMMIT_PARTIAL_TEXT);
+ researchLogger.mStatistics.recordAutoCorrection(SystemClock.uptimeMillis());
+ researchLogger.commitCurrentLogUnitAsWord(scrubbedWord, lastTimestampOfWordData,
+ isBatchMode);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_DELETESURROUNDINGTEXT = {
- "RichInputConnectionDeleteSurroundingText", "beforeLength", "afterLength"
- };
+ /**
+ * Log a call to RichInputConnection.commitText().
+ *
+ * SystemResponse: The IME is committing text. This happens after the user has typed a word
+ * and then a space or punctuation key.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTIONCOMMITTEXT =
+ new LogStatement("RichInputConnectionCommitText", true, false, "newCursorPosition");
+ public static void richInputConnection_commitText(final String committedWord,
+ final int newCursorPosition, final boolean isBatchMode) {
+ final ResearchLogger researchLogger = getInstance();
+ // Only include opening and closing logSegments if private data is included
+ final String scrubbedWord = scrubDigitsFromString(committedWord);
+ if (!researchLogger.isExpectingCommitText) {
+ researchLogger.enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTIONCOMMITTEXT,
+ newCursorPosition);
+ researchLogger.commitCurrentLogUnitAsWord(scrubbedWord, Long.MAX_VALUE, isBatchMode);
+ }
+ researchLogger.isExpectingCommitText = false;
+ }
+
+ /**
+ * Shared event for logging committed text.
+ */
+ private static final LogStatement LOGSTATEMENT_COMMITTEXT =
+ new LogStatement("CommitText", true, false, "committedText", "isBatchMode");
+ private void enqueueCommitText(final String word, final boolean isBatchMode) {
+ enqueueEvent(LOGSTATEMENT_COMMITTEXT, word, isBatchMode);
+ }
+
+ /**
+ * Log a call to RichInputConnection.deleteSurroundingText().
+ *
+ * SystemResponse: The IME has deleted text.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_DELETESURROUNDINGTEXT =
+ new LogStatement("RichInputConnectionDeleteSurroundingText", true, false,
+ "beforeLength", "afterLength");
public static void richInputConnection_deleteSurroundingText(final int beforeLength,
final int afterLength) {
- final Object[] values = {
- beforeLength, afterLength
- };
- getInstance().enqueuePotentiallyPrivateEvent(
- EVENTKEYS_RICHINPUTCONNECTION_DELETESURROUNDINGTEXT, values);
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_DELETESURROUNDINGTEXT,
+ beforeLength, afterLength);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_FINISHCOMPOSINGTEXT = {
- "RichInputConnectionFinishComposingText"
- };
+ /**
+ * Log a call to RichInputConnection.finishComposingText().
+ *
+ * SystemResponse: The IME has left the composing text as-is.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_FINISHCOMPOSINGTEXT =
+ new LogStatement("RichInputConnectionFinishComposingText", false, false);
public static void richInputConnection_finishComposingText() {
- getInstance().enqueueEvent(EVENTKEYS_RICHINPUTCONNECTION_FINISHCOMPOSINGTEXT,
- EVENTKEYS_NULLVALUES);
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_FINISHCOMPOSINGTEXT);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_PERFORMEDITORACTION = {
- "RichInputConnectionPerformEditorAction", "imeActionNext"
- };
- public static void richInputConnection_performEditorAction(final int imeActionNext) {
- final Object[] values = {
- imeActionNext
- };
- getInstance().enqueueEvent(EVENTKEYS_RICHINPUTCONNECTION_PERFORMEDITORACTION, values);
+ /**
+ * Log a call to RichInputConnection.performEditorAction().
+ *
+ * SystemResponse: The IME is invoking an action specific to the editor.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_PERFORMEDITORACTION =
+ new LogStatement("RichInputConnectionPerformEditorAction", false, false,
+ "imeActionId");
+ public static void richInputConnection_performEditorAction(final int imeActionId) {
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_PERFORMEDITORACTION,
+ imeActionId);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_SENDKEYEVENT = {
- "RichInputConnectionSendKeyEvent", "eventTime", "action", "code"
- };
+ /**
+ * Log a call to RichInputConnection.sendKeyEvent().
+ *
+ * SystemResponse: The IME is telling the TextView that a key is being pressed through an
+ * alternate channel.
+ * TODO: only for hardware keys?
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_SENDKEYEVENT =
+ new LogStatement("RichInputConnectionSendKeyEvent", true, false, "eventTime", "action",
+ "code");
public static void richInputConnection_sendKeyEvent(final KeyEvent keyEvent) {
- final Object[] values = {
- keyEvent.getEventTime(),
- keyEvent.getAction(),
- keyEvent.getKeyCode()
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_RICHINPUTCONNECTION_SENDKEYEVENT,
- values);
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_SENDKEYEVENT,
+ keyEvent.getEventTime(), keyEvent.getAction(), keyEvent.getKeyCode());
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_SETCOMPOSINGTEXT = {
- "RichInputConnectionSetComposingText", "text", "newCursorPosition"
- };
+ /**
+ * Log a call to RichInputConnection.setComposingText().
+ *
+ * SystemResponse: The IME is setting the composing text. Happens each time a character is
+ * entered.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_SETCOMPOSINGTEXT =
+ new LogStatement("RichInputConnectionSetComposingText", true, true, "text",
+ "newCursorPosition");
public static void richInputConnection_setComposingText(final CharSequence text,
final int newCursorPosition) {
if (text == null) {
throw new RuntimeException("setComposingText is null");
}
- final Object[] values = {
- text, newCursorPosition
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_RICHINPUTCONNECTION_SETCOMPOSINGTEXT,
- values);
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_SETCOMPOSINGTEXT, text,
+ newCursorPosition);
}
- private static final String[] EVENTKEYS_RICHINPUTCONNECTION_SETSELECTION = {
- "RichInputConnectionSetSelection", "from", "to"
- };
+ /**
+ * Log a call to RichInputConnection.setSelection().
+ *
+ * SystemResponse: The IME is requesting that the selection change. User-initiated selection-
+ * change requests do not go through this method -- it's only when the system wants to change
+ * the selection.
+ */
+ private static final LogStatement LOGSTATEMENT_RICHINPUTCONNECTION_SETSELECTION =
+ new LogStatement("RichInputConnectionSetSelection", true, false, "from", "to");
public static void richInputConnection_setSelection(final int from, final int to) {
- final Object[] values = {
- from, to
- };
- getInstance().enqueuePotentiallyPrivateEvent(EVENTKEYS_RICHINPUTCONNECTION_SETSELECTION,
- values);
+ getInstance().enqueueEvent(LOGSTATEMENT_RICHINPUTCONNECTION_SETSELECTION, from, to);
}
- private static final String[] EVENTKEYS_SUDDENJUMPINGTOUCHEVENTHANDLER_ONTOUCHEVENT = {
- "SuddenJumpingTouchEventHandlerOnTouchEvent", "motionEvent"
- };
+ /**
+ * Log a call to SuddenJumpingTouchEventHandler.onTouchEvent().
+ *
+ * SystemResponse: The IME has filtered input events in case of an erroneous sensor reading.
+ */
+ private static final LogStatement LOGSTATEMENT_SUDDENJUMPINGTOUCHEVENTHANDLER_ONTOUCHEVENT =
+ new LogStatement("SuddenJumpingTouchEventHandlerOnTouchEvent", true, false,
+ "motionEvent");
public static void suddenJumpingTouchEventHandler_onTouchEvent(final MotionEvent me) {
if (me != null) {
- final Object[] values = {
- me.toString()
- };
- getInstance().enqueuePotentiallyPrivateEvent(
- EVENTKEYS_SUDDENJUMPINGTOUCHEVENTHANDLER_ONTOUCHEVENT, values);
+ getInstance().enqueueEvent(LOGSTATEMENT_SUDDENJUMPINGTOUCHEVENTHANDLER_ONTOUCHEVENT,
+ me.toString());
}
}
- private static final String[] EVENTKEYS_SUGGESTIONSTRIPVIEW_SETSUGGESTIONS = {
- "SuggestionStripViewSetSuggestions", "suggestedWords"
- };
+ /**
+ * Log a call to SuggestionsView.setSuggestions().
+ *
+ * SystemResponse: The IME is setting the suggestions in the suggestion strip.
+ */
+ private static final LogStatement LOGSTATEMENT_SUGGESTIONSTRIPVIEW_SETSUGGESTIONS =
+ new LogStatement("SuggestionStripViewSetSuggestions", true, true, "suggestedWords");
public static void suggestionStripView_setSuggestions(final SuggestedWords suggestedWords) {
if (suggestedWords != null) {
- final Object[] values = {
- suggestedWords
- };
- getInstance().enqueuePotentiallyPrivateEvent(
- EVENTKEYS_SUGGESTIONSTRIPVIEW_SETSUGGESTIONS, values);
+ getInstance().enqueueEvent(LOGSTATEMENT_SUGGESTIONSTRIPVIEW_SETSUGGESTIONS,
+ suggestedWords);
}
}
- private static final String[] EVENTKEYS_USER_TIMESTAMP = {
- "UserTimestamp"
- };
+ /**
+ * The user has indicated a particular point in the log that is of interest.
+ *
+ * UserAction: From direct menu invocation.
+ */
+ private static final LogStatement LOGSTATEMENT_USER_TIMESTAMP =
+ new LogStatement("UserTimestamp", false, false);
public void userTimestamp() {
- getInstance().enqueueEvent(EVENTKEYS_USER_TIMESTAMP, EVENTKEYS_NULLVALUES);
+ getInstance().enqueueEvent(LOGSTATEMENT_USER_TIMESTAMP);
}
- private static final String[] EVENTKEYS_STATISTICS = {
- "Statistics", "charCount", "letterCount", "numberCount", "spaceCount", "deleteOpsCount",
- "wordCount", "isEmptyUponStarting", "isEmptinessStateKnown", "averageTimeBetweenKeys",
- "averageTimeBeforeDelete", "averageTimeDuringRepeatedDelete", "averageTimeAfterDelete"
- };
+ /**
+ * Log a call to LatinIME.onEndBatchInput().
+ *
+ * SystemResponse: The system has completed a gesture.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_ONENDBATCHINPUT =
+ new LogStatement("LatinIMEOnEndBatchInput", true, false, "enteredText",
+ "enteredWordPos");
+ public static void latinIME_onEndBatchInput(final CharSequence enteredText,
+ final int enteredWordPos, final SuggestedWords suggestedWords) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_ONENDBATCHINPUT, enteredText,
+ enteredWordPos);
+ researchLogger.mCurrentLogUnit.initializeSuggestions(suggestedWords);
+ researchLogger.mStatistics.recordGestureInput(enteredText.length(),
+ SystemClock.uptimeMillis());
+ }
+
+ /**
+ * Log a call to LatinIME.handleBackspace() that is not a batch delete.
+ *
+ * UserInput: The user is deleting one or more characters by hitting the backspace key once.
+ * The covers single character deletes as well as deleting selections.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_HANDLEBACKSPACE =
+ new LogStatement("LatinIMEHandleBackspace", true, false, "numCharacters");
+ public static void latinIME_handleBackspace(final int numCharacters) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_HANDLEBACKSPACE, numCharacters);
+ }
+
+ /**
+ * Log a call to LatinIME.handleBackspace() that is a batch delete.
+ *
+ * UserInput: The user is deleting a gestured word by hitting the backspace key once.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_HANDLEBACKSPACE_BATCH =
+ new LogStatement("LatinIMEHandleBackspaceBatch", true, false, "deletedText",
+ "numCharacters");
+ public static void latinIME_handleBackspace_batch(final CharSequence deletedText,
+ final int numCharacters) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_HANDLEBACKSPACE_BATCH, deletedText,
+ numCharacters);
+ researchLogger.mStatistics.recordGestureDelete(deletedText.length(),
+ SystemClock.uptimeMillis());
+ }
+
+ /**
+ * Log a long interval between user operation.
+ *
+ * UserInput: The user has not done anything for a while.
+ */
+ private static final LogStatement LOGSTATEMENT_ONUSERPAUSE = new LogStatement("OnUserPause",
+ false, false, "intervalInMs");
+ public static void onUserPause(final long interval) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_ONUSERPAUSE, interval);
+ }
+
+ /**
+ * Record the current time in case the LogUnit is later split.
+ *
+ * If the current logUnit is split, then tapping, motion events, etc. before this time should
+ * be assigned to one LogUnit, and events after this time should go into the following LogUnit.
+ */
+ public static void recordTimeForLogUnitSplit() {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.setSavedDownEventTime(SystemClock.uptimeMillis());
+ researchLogger.mSavedDownEventTime = Long.MAX_VALUE;
+ }
+
+ /**
+ * Log a call to LatinIME.handleSeparator()
+ *
+ * SystemResponse: The system is inserting a separator character, possibly performing auto-
+ * correction or other actions appropriate at the end of a word.
+ */
+ private static final LogStatement LOGSTATEMENT_LATINIME_HANDLESEPARATOR =
+ new LogStatement("LatinIMEHandleSeparator", false, false, "primaryCode",
+ "isComposingWord");
+ public static void latinIME_handleSeparator(final int primaryCode,
+ final boolean isComposingWord) {
+ final ResearchLogger researchLogger = getInstance();
+ researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_HANDLESEPARATOR, primaryCode,
+ isComposingWord);
+ }
+
+ /**
+ * Log statistics.
+ *
+ * ContextualData, recorded at the end of a session.
+ */
+ private static final LogStatement LOGSTATEMENT_STATISTICS =
+ new LogStatement("Statistics", false, false, "charCount", "letterCount", "numberCount",
+ "spaceCount", "deleteOpsCount", "wordCount", "isEmptyUponStarting",
+ "isEmptinessStateKnown", "averageTimeBetweenKeys", "averageTimeBeforeDelete",
+ "averageTimeDuringRepeatedDelete", "averageTimeAfterDelete",
+ "dictionaryWordCount", "splitWordsCount", "gestureInputCount",
+ "gestureCharsCount", "gesturesDeletedCount", "manualSuggestionsCount",
+ "revertCommitsCount", "correctedWordsCount", "autoCorrectionsCount");
private static void logStatistics() {
final ResearchLogger researchLogger = getInstance();
final Statistics statistics = researchLogger.mStatistics;
- final Object[] values = {
- statistics.mCharCount, statistics.mLetterCount, statistics.mNumberCount,
- statistics.mSpaceCount, statistics.mDeleteKeyCount,
- statistics.mWordCount, statistics.mIsEmptyUponStarting,
- statistics.mIsEmptinessStateKnown, statistics.mKeyCounter.getAverageTime(),
- statistics.mBeforeDeleteKeyCounter.getAverageTime(),
- statistics.mDuringRepeatedDeleteKeysCounter.getAverageTime(),
- statistics.mAfterDeleteKeyCounter.getAverageTime()
- };
- researchLogger.enqueueEvent(EVENTKEYS_STATISTICS, values);
+ researchLogger.enqueueEvent(LOGSTATEMENT_STATISTICS, statistics.mCharCount,
+ statistics.mLetterCount, statistics.mNumberCount, statistics.mSpaceCount,
+ statistics.mDeleteKeyCount, statistics.mWordCount, statistics.mIsEmptyUponStarting,
+ statistics.mIsEmptinessStateKnown, statistics.mKeyCounter.getAverageTime(),
+ statistics.mBeforeDeleteKeyCounter.getAverageTime(),
+ statistics.mDuringRepeatedDeleteKeysCounter.getAverageTime(),
+ statistics.mAfterDeleteKeyCounter.getAverageTime(),
+ statistics.mDictionaryWordCount, statistics.mSplitWordsCount,
+ statistics.mGesturesInputCount, statistics.mGesturesCharsCount,
+ statistics.mGesturesDeletedCount, statistics.mManualSuggestionsCount,
+ statistics.mRevertCommitsCount, statistics.mCorrectedWordsCount,
+ statistics.mAutoCorrectionsCount);
}
}
diff --git a/java/src/com/android/inputmethod/research/Statistics.java b/java/src/com/android/inputmethod/research/Statistics.java
index eab465aa2..50e2b7fbc 100644
--- a/java/src/com/android/inputmethod/research/Statistics.java
+++ b/java/src/com/android/inputmethod/research/Statistics.java
@@ -1,24 +1,31 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
-import com.android.inputmethod.keyboard.Keyboard;
+import android.util.Log;
+
+import com.android.inputmethod.latin.Constants;
+import com.android.inputmethod.latin.define.ProductionFlag;
public class Statistics {
+ private static final String TAG = Statistics.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+
+ // TODO: Cleanup comments to only including those giving meaningful information.
// Number of characters entered during a typing session
int mCharCount;
// Number of letter characters entered during a typing session
@@ -31,6 +38,24 @@ public class Statistics {
int mDeleteKeyCount;
// Number of words entered during a session.
int mWordCount;
+ // Number of words found in the dictionary.
+ int mDictionaryWordCount;
+ // Number of words split and spaces automatically entered.
+ int mSplitWordsCount;
+ // Number of words entered during a session.
+ int mCorrectedWordsCount;
+ // Number of gestures that were input.
+ int mGesturesInputCount;
+ // Number of gestures that were deleted.
+ int mGesturesDeletedCount;
+ // Total number of characters in words entered by gesture.
+ int mGesturesCharsCount;
+ // Number of manual suggestions chosen.
+ int mManualSuggestionsCount;
+ // Number of times that autocorrection was invoked.
+ int mAutoCorrectionsCount;
+ // Number of times a commit was reverted in this session.
+ int mRevertCommitsCount;
// Whether the text field was empty upon editing
boolean mIsEmptyUponStarting;
boolean mIsEmptinessStateKnown;
@@ -91,29 +116,34 @@ public class Statistics {
mSpaceCount = 0;
mDeleteKeyCount = 0;
mWordCount = 0;
+ mDictionaryWordCount = 0;
+ mSplitWordsCount = 0;
+ mCorrectedWordsCount = 0;
+ mGesturesInputCount = 0;
+ mGesturesDeletedCount = 0;
+ mManualSuggestionsCount = 0;
+ mRevertCommitsCount = 0;
+ mAutoCorrectionsCount = 0;
mIsEmptyUponStarting = true;
mIsEmptinessStateKnown = false;
mKeyCounter.reset();
mBeforeDeleteKeyCounter.reset();
mDuringRepeatedDeleteKeysCounter.reset();
mAfterDeleteKeyCounter.reset();
+ mGesturesCharsCount = 0;
+ mGesturesDeletedCount = 0;
mLastTapTime = 0;
mIsLastKeyDeleteKey = false;
}
public void recordChar(int codePoint, long time) {
- final long delta = time - mLastTapTime;
- if (codePoint == Keyboard.CODE_DELETE) {
+ if (DEBUG) {
+ Log.d(TAG, "recordChar() called");
+ }
+ if (codePoint == Constants.CODE_DELETE) {
mDeleteKeyCount++;
- if (delta < MIN_DELETION_INTERMISSION) {
- if (mIsLastKeyDeleteKey) {
- mDuringRepeatedDeleteKeysCounter.add(delta);
- } else {
- mBeforeDeleteKeyCounter.add(delta);
- }
- }
- mIsLastKeyDeleteKey = true;
+ recordUserAction(time, true /* isDeletion */);
} else {
mCharCount++;
if (Character.isDigit(codePoint)) {
@@ -125,22 +155,78 @@ public class Statistics {
if (Character.isSpaceChar(codePoint)) {
mSpaceCount++;
}
- if (mIsLastKeyDeleteKey && delta < MIN_DELETION_INTERMISSION) {
- mAfterDeleteKeyCounter.add(delta);
- } else if (!mIsLastKeyDeleteKey && delta < MIN_TYPING_INTERMISSION) {
- mKeyCounter.add(delta);
- }
- mIsLastKeyDeleteKey = false;
+ recordUserAction(time, false /* isDeletion */);
}
- mLastTapTime = time;
}
- public void recordWordEntered() {
+ public void recordWordEntered(final boolean isDictionaryWord,
+ final boolean containsCorrection) {
mWordCount++;
+ if (isDictionaryWord) {
+ mDictionaryWordCount++;
+ }
+ if (containsCorrection) {
+ mCorrectedWordsCount++;
+ }
+ }
+
+ public void recordSplitWords() {
+ mSplitWordsCount++;
+ }
+
+ public void recordGestureInput(final int numCharsEntered, final long time) {
+ mGesturesInputCount++;
+ mGesturesCharsCount += numCharsEntered;
+ recordUserAction(time, false /* isDeletion */);
}
public void setIsEmptyUponStarting(final boolean isEmpty) {
mIsEmptyUponStarting = isEmpty;
mIsEmptinessStateKnown = true;
}
+
+ public void recordGestureDelete(final int length, final long time) {
+ mGesturesDeletedCount++;
+ recordUserAction(time, true /* isDeletion */);
+ }
+
+ public void recordManualSuggestion(final long time) {
+ mManualSuggestionsCount++;
+ recordUserAction(time, false /* isDeletion */);
+ }
+
+ public void recordAutoCorrection(final long time) {
+ mAutoCorrectionsCount++;
+ recordUserAction(time, false /* isDeletion */);
+ }
+
+ public void recordRevertCommit(final long time) {
+ mRevertCommitsCount++;
+ recordUserAction(time, true /* isDeletion */);
+ }
+
+ private void recordUserAction(final long time, final boolean isDeletion) {
+ final long delta = time - mLastTapTime;
+ if (isDeletion) {
+ if (delta < MIN_DELETION_INTERMISSION) {
+ if (mIsLastKeyDeleteKey) {
+ mDuringRepeatedDeleteKeysCounter.add(delta);
+ } else {
+ mBeforeDeleteKeyCounter.add(delta);
+ }
+ } else {
+ ResearchLogger.onUserPause(delta);
+ }
+ } else {
+ if (mIsLastKeyDeleteKey && delta < MIN_DELETION_INTERMISSION) {
+ mAfterDeleteKeyCounter.add(delta);
+ } else if (!mIsLastKeyDeleteKey && delta < MIN_TYPING_INTERMISSION) {
+ mKeyCounter.add(delta);
+ } else {
+ ResearchLogger.onUserPause(delta);
+ }
+ }
+ mIsLastKeyDeleteKey = isDeletion;
+ mLastTapTime = time;
+ }
}
diff --git a/java/src/com/android/inputmethod/research/UploaderService.java b/java/src/com/android/inputmethod/research/UploaderService.java
index 7a5749096..89c67fbb2 100644
--- a/java/src/com/android/inputmethod/research/UploaderService.java
+++ b/java/src/com/android/inputmethod/research/UploaderService.java
@@ -1,17 +1,17 @@
/*
* Copyright (C) 2012 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
+ * 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
+ * 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.
+ * 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.research;
@@ -30,6 +30,7 @@ import android.os.Bundle;
import android.util.Log;
import com.android.inputmethod.latin.R;
+import com.android.inputmethod.latin.define.ProductionFlag;
import java.io.BufferedReader;
import java.io.File;
@@ -45,8 +46,12 @@ import java.net.URL;
public final class UploaderService extends IntentService {
private static final String TAG = UploaderService.class.getSimpleName();
+ private static final boolean DEBUG = false && ProductionFlag.IS_EXPERIMENTAL_DEBUG;
+ // Set IS_INHIBITING_AUTO_UPLOAD to true for local testing
+ private static final boolean IS_INHIBITING_AUTO_UPLOAD = false
+ && ProductionFlag.IS_EXPERIMENTAL_DEBUG; // Force false in production
public static final long RUN_INTERVAL = AlarmManager.INTERVAL_HOUR;
- private static final String EXTRA_UPLOAD_UNCONDITIONALLY = UploaderService.class.getName()
+ public static final String EXTRA_UPLOAD_UNCONDITIONALLY = UploaderService.class.getName()
+ ".extra.UPLOAD_UNCONDITIONALLY";
private static final int BUF_SIZE = 1024 * 8;
protected static final int TIMEOUT_IN_MS = 1000 * 4;
@@ -116,7 +121,8 @@ public final class UploaderService extends IntentService {
}
private void doUpload(final boolean isUploadingUnconditionally) {
- if (!isUploadingUnconditionally && (!isExternallyPowered() || !hasWifiConnection())) {
+ if (!isUploadingUnconditionally && (!isExternallyPowered() || !hasWifiConnection()
+ || IS_INHIBITING_AUTO_UPLOAD)) {
return;
}
if (mFilesDir == null) {
@@ -125,7 +131,7 @@ public final class UploaderService extends IntentService {
final File[] files = mFilesDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
- return pathname.getName().startsWith(ResearchLogger.FILENAME_PREFIX)
+ return pathname.getName().startsWith(ResearchLogger.LOG_FILENAME_PREFIX)
&& !pathname.canWrite();
}
});
@@ -141,7 +147,9 @@ public final class UploaderService extends IntentService {
}
private boolean uploadFile(File file) {
- Log.d(TAG, "attempting upload of " + file.getAbsolutePath());
+ if (DEBUG) {
+ Log.d(TAG, "attempting upload of " + file.getAbsolutePath());
+ }
boolean success = false;
final int contentLength = (int) file.length();
HttpURLConnection connection = null;
@@ -157,6 +165,9 @@ public final class UploaderService extends IntentService {
int numBytesRead;
while ((numBytesRead = fileInputStream.read(buf)) != -1) {
os.write(buf, 0, numBytesRead);
+ if (DEBUG) {
+ Log.d(TAG, new String(buf));
+ }
}
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "upload failed: " + connection.getResponseCode());
@@ -171,7 +182,9 @@ public final class UploaderService extends IntentService {
}
file.delete();
success = true;
- Log.d(TAG, "upload successful");
+ if (DEBUG) {
+ Log.d(TAG, "upload successful");
+ }
} catch (Exception e) {
e.printStackTrace();
} finally {