diff options
Diffstat (limited to 'java/src')
26 files changed, 233 insertions, 235 deletions
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java b/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java index c76acd126..60d09d6fd 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardActionListener.java @@ -94,6 +94,8 @@ public interface KeyboardActionListener { public boolean onCustomRequest(int requestCode); public static class Adapter implements KeyboardActionListener { + public static final Adapter EMPTY_LISTENER = new Adapter(); + @Override public void onPressKey(int primaryCode) {} @Override diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardId.java b/java/src/com/android/inputmethod/keyboard/KeyboardId.java index ee8ee9a4f..aa27067bc 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardId.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardId.java @@ -56,13 +56,8 @@ public final class KeyboardId { public static final int ELEMENT_PHONE_SYMBOLS = 8; public static final int ELEMENT_NUMBER = 9; - public static final int FORM_FACTOR_PHONE = 0; - public static final int FORM_FACTOR_TABLET7 = 1; - public static final int FORM_FACTOR_TABLET10 = 2; - 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; @@ -82,7 +77,6 @@ public final class KeyboardId { 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; @@ -107,7 +101,6 @@ public final class KeyboardId { private static int computeHashCode(final KeyboardId id) { return Arrays.hashCode(new Object[] { - id.mDeviceFormFactor, id.mOrientation, id.mElementId, id.mMode, @@ -130,8 +123,7 @@ public final class KeyboardId { private boolean equals(final KeyboardId other) { if (other == this) return true; - return other.mDeviceFormFactor == mDeviceFormFactor - && other.mOrientation == mOrientation + return other.mOrientation == mOrientation && other.mElementId == mElementId && other.mMode == mMode && other.mWidth == mWidth @@ -195,11 +187,11 @@ public final class KeyboardId { public String toString() { 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]", + return String.format("[%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), orientation, mWidth, mHeight, + orientation, mWidth, mHeight, modeName(mMode), imeAction(), (navigateNext() ? "navigateNext" : ""), @@ -238,15 +230,6 @@ public final class KeyboardId { } } - 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"; - default: return null; - } - } - public static String modeName(final int mode) { switch (mode) { case MODE_TEXT: return "text"; diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java b/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java index 5e68c7067..bc9e8cdd4 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardLayoutSet.java @@ -106,7 +106,6 @@ public final class KeyboardLayoutSet { boolean mNoSettingsKey; boolean mLanguageSwitchKeyEnabled; InputMethodSubtype mSubtype; - int mDeviceFormFactor; int mOrientation; int mKeyboardWidth; int mKeyboardHeight; @@ -217,10 +216,8 @@ public final class KeyboardLayoutSet { mPackageName, NO_SETTINGS_KEY, mEditorInfo); } - public Builder setScreenGeometry(final int deviceFormFactor, final int widthPixels, - final int heightPixels) { + public Builder setScreenGeometry(final int widthPixels, final int heightPixels) { final Params params = mParams; - params.mDeviceFormFactor = deviceFormFactor; params.mOrientation = (heightPixels > widthPixels) ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE; setDefaultKeyboardSize(widthPixels, heightPixels); diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java index 4e41b77ce..39afe9072 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java @@ -142,8 +142,7 @@ public final class KeyboardSwitcher implements KeyboardState.SwitchActions { mThemeContext, editorInfo); final Resources res = mThemeContext.getResources(); final DisplayMetrics dm = res.getDisplayMetrics(); - builder.setScreenGeometry(res.getInteger(R.integer.config_device_form_factor), - dm.widthPixels, dm.heightPixels); + builder.setScreenGeometry(dm.widthPixels, dm.heightPixels); builder.setSubtype(mSubtypeSwitcher.getCurrentSubtype()); builder.setOptions( settingsValues.isVoiceKeyEnabled(editorInfo), diff --git a/java/src/com/android/inputmethod/keyboard/PointerTracker.java b/java/src/com/android/inputmethod/keyboard/PointerTracker.java index c1b148dbf..0556fddd3 100644 --- a/java/src/com/android/inputmethod/keyboard/PointerTracker.java +++ b/java/src/com/android/inputmethod/keyboard/PointerTracker.java @@ -176,7 +176,7 @@ public final class PointerTracker implements PointerTrackerQueue.Element { private DrawingProxy mDrawingProxy; private TimerProxy mTimerProxy; private KeyDetector mKeyDetector; - private KeyboardActionListener mListener = EMPTY_LISTENER; + private KeyboardActionListener mListener = KeyboardActionListener.Adapter.EMPTY_LISTENER; private Keyboard mKeyboard; private int mPhantonSuddenMoveThreshold; @@ -333,10 +333,6 @@ public final class PointerTracker implements PointerTrackerQueue.Element { // true if a sliding key input is allowed. private boolean mIsAllowedSlidingKeyInput; - // Empty {@link KeyboardActionListener} - private static final KeyboardActionListener EMPTY_LISTENER = - new KeyboardActionListener.Adapter(); - private final GestureStrokeWithPreviewPoints mGestureStrokeWithPreviewPoints; public static void init(final boolean needsPhantomSuddenMoveEventHack) { diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java b/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java index 53da47c52..93ff26466 100644 --- a/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java +++ b/java/src/com/android/inputmethod/keyboard/internal/GestureStroke.java @@ -83,9 +83,8 @@ public class GestureStroke { public final int mRecognitionMinimumTime; // msec public final float mRecognitionSpeedThreshold; // keyWidth/sec - // Default GestureStroke parameters for test. - public static final GestureStrokeParams FOR_TEST = new GestureStrokeParams(); - public static final GestureStrokeParams DEFAULT = FOR_TEST; + // Default GestureStroke parameters. + public static final GestureStrokeParams DEFAULT = new GestureStrokeParams(); private GestureStrokeParams() { // These parameter values are default and intended for testing. diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java b/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java index 3315954c1..7a51e2568 100644 --- a/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java +++ b/java/src/com/android/inputmethod/keyboard/internal/GestureStrokeWithPreviewPoints.java @@ -21,8 +21,6 @@ import com.android.inputmethod.latin.ResizableIntArray; public final class GestureStrokeWithPreviewPoints extends GestureStroke { public static final int PREVIEW_CAPACITY = 256; - private static final boolean ENABLE_INTERPOLATION = true; - private final ResizableIntArray mPreviewEventTimes = new ResizableIntArray(PREVIEW_CAPACITY); private final ResizableIntArray mPreviewXCoordinates = new ResizableIntArray(PREVIEW_CAPACITY); private final ResizableIntArray mPreviewYCoordinates = new ResizableIntArray(PREVIEW_CAPACITY); @@ -32,21 +30,22 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke { private final HermiteInterpolator mInterpolator = new HermiteInterpolator(); private int mLastInterpolatedPreviewIndex; - private int mMinPreviewSamplingDistanceSquared; private int mLastX; private int mLastY; private double mMinPreviewSamplingDistance; private double mDistanceFromLastSample; + private double mInterpolationDistanceThreshold; // TODO: Move these constants to resource. - // The minimum linear distance between sample points for preview in keyWidth unit. - private static final float MIN_PREVIEW_SAMPLING_RATIO_TO_KEY_WIDTH = 0.1f; + // TODO: Use "dp" instead of ratio to the keyWidth because table has rather large keys. // The minimum trail distance between sample points for preview in keyWidth unit when using // interpolation. - private static final float MIN_PREVIEW_SAMPLING_RATIO_TO_KEY_WIDTH_WITH_INTERPOLATION = 0.2f; + private static final float MIN_PREVIEW_SAMPLING_RATIO_TO_KEY_WIDTH = 0.2f; // The angular threshold to use interpolation in radian. PI/12 is 15 degree. private static final double INTERPOLATION_ANGULAR_THRESHOLD = Math.PI / 12.0d; - private static final int MAX_INTERPOLATION_PARTITION = 4; + // The distance threshold to use interpolation in keyWidth unit. + private static final float INTERPOLATION_DISTANCE_THRESHOLD_TO_KEY_WIDTH = 0.5f; + private static final int MAX_INTERPOLATION_PARTITIONS = 6; public GestureStrokeWithPreviewPoints(final int pointerId, final GestureStrokeParams params) { super(pointerId, params); @@ -70,31 +69,17 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke { @Override public void setKeyboardGeometry(final int keyWidth, final int keyboardHeight) { super.setKeyboardGeometry(keyWidth, keyboardHeight); - final float samplingRatioToKeyWidth = ENABLE_INTERPOLATION - ? MIN_PREVIEW_SAMPLING_RATIO_TO_KEY_WIDTH_WITH_INTERPOLATION - : MIN_PREVIEW_SAMPLING_RATIO_TO_KEY_WIDTH; - mMinPreviewSamplingDistance = keyWidth * samplingRatioToKeyWidth; - mMinPreviewSamplingDistanceSquared = (int)( - mMinPreviewSamplingDistance * mMinPreviewSamplingDistance); + mMinPreviewSamplingDistance = keyWidth * MIN_PREVIEW_SAMPLING_RATIO_TO_KEY_WIDTH; + mInterpolationDistanceThreshold = keyWidth * INTERPOLATION_DISTANCE_THRESHOLD_TO_KEY_WIDTH; } - private boolean needsSampling(final int x, final int y, final boolean isMajorEvent) { - if (ENABLE_INTERPOLATION) { - mDistanceFromLastSample += Math.hypot(x - mLastX, y - mLastY); - mLastX = x; - mLastY = y; - if (mDistanceFromLastSample >= mMinPreviewSamplingDistance) { - mDistanceFromLastSample = 0.0d; - return true; - } - return false; - } - - final int dx = x - mLastX; - final int dy = y - mLastY; - if (isMajorEvent || dx * dx + dy * dy >= mMinPreviewSamplingDistanceSquared) { - mLastX = x; - mLastY = y; + private boolean needsSampling(final int x, final int y) { + mDistanceFromLastSample += Math.hypot(x - mLastX, y - mLastY); + mLastX = x; + mLastY = y; + final boolean isDownEvent = (mPreviewEventTimes.getLength() == 0); + if (mDistanceFromLastSample >= mMinPreviewSamplingDistance || isDownEvent) { + mDistanceFromLastSample = 0.0d; return true; } return false; @@ -103,7 +88,7 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke { @Override public boolean addPointOnKeyboard(final int x, final int y, final int time, final boolean isMajorEvent) { - if (needsSampling(x, y, isMajorEvent)) { + if (needsSampling(x, y)) { mPreviewEventTimes.add(time); mPreviewXCoordinates.add(x); mPreviewYCoordinates.add(y); @@ -140,9 +125,6 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke { public int interpolateStrokeAndReturnStartIndexOfLastSegment(final int lastInterpolatedIndex, final ResizableIntArray eventTimes, final ResizableIntArray xCoords, final ResizableIntArray yCoords) { - if (!ENABLE_INTERPOLATION) { - return lastInterpolatedIndex; - } final int size = mPreviewEventTimes.getLength(); final int[] pt = mPreviewEventTimes.getPrimitiveArray(); final int[] px = mPreviewXCoordinates.getPrimitiveArray(); @@ -161,14 +143,20 @@ public final class GestureStrokeWithPreviewPoints extends GestureStroke { mInterpolator.setInterval(p0, p1, p2, p3); final double m1 = Math.atan2(mInterpolator.mSlope1Y, mInterpolator.mSlope1X); final double m2 = Math.atan2(mInterpolator.mSlope2Y, mInterpolator.mSlope2X); - final double dm = Math.abs(angularDiff(m2, m1)); - final int partition = Math.min((int)Math.ceil(dm / INTERPOLATION_ANGULAR_THRESHOLD), - MAX_INTERPOLATION_PARTITION); + final double deltaAngle = Math.abs(angularDiff(m2, m1)); + final int partitionsByAngle = (int)Math.ceil( + deltaAngle / INTERPOLATION_ANGULAR_THRESHOLD); + final double deltaDistance = Math.hypot(mInterpolator.mP1X - mInterpolator.mP2X, + mInterpolator.mP1Y - mInterpolator.mP2Y); + final int partitionsByDistance = (int)Math.ceil(deltaDistance + / mInterpolationDistanceThreshold); + final int partitions = Math.min(MAX_INTERPOLATION_PARTITIONS, + Math.max(partitionsByAngle, partitionsByDistance)); final int t1 = eventTimes.get(d1); final int dt = pt[p2] - pt[p1]; d1++; - for (int i = 1; i < partition; i++) { - final float t = i / (float)partition; + for (int i = 1; i < partitions; i++) { + final float t = i / (float)partitions; mInterpolator.interpolate(t); eventTimes.add(d1, (int)(dt * t) + t1); xCoords.add(d1, (int)mInterpolator.mInterpolatedX); diff --git a/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java b/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java index b1d499702..962bde91e 100644 --- a/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java +++ b/java/src/com/android/inputmethod/keyboard/internal/KeyboardState.java @@ -96,16 +96,16 @@ public final class KeyboardState { public boolean mIsValid; public boolean mIsAlphabetMode; public boolean mIsAlphabetShiftLocked; - public boolean mIsShifted; + public int mShiftMode; @Override public String toString() { if (!mIsValid) return "INVALID"; if (mIsAlphabetMode) { if (mIsAlphabetShiftLocked) return "ALPHABET_SHIFT_LOCKED"; - return mIsShifted ? "ALPHABET_SHIFTED" : "ALPHABET"; + return "ALPHABET_" + shiftModeToString(mShiftMode); } else { - return mIsShifted ? "SYMBOLS_SHIFTED" : "SYMBOLS"; + return "SYMBOLS_" + shiftModeToString(mShiftMode); } } } @@ -128,16 +128,21 @@ public final class KeyboardState { onRestoreKeyboardState(); } + private static final int UNSHIFT = 0; + private static final int MANUAL_SHIFT = 1; + private static final int AUTOMATIC_SHIFT = 2; + private static final int SHIFT_LOCK_SHIFTED = 3; + public void onSaveKeyboardState() { final SavedKeyboardState state = mSavedKeyboardState; state.mIsAlphabetMode = mIsAlphabetMode; if (mIsAlphabetMode) { state.mIsAlphabetShiftLocked = mAlphabetShiftState.isShiftLocked(); - state.mIsShifted = !state.mIsAlphabetShiftLocked - && mAlphabetShiftState.isShiftedOrShiftLocked(); + state.mShiftMode = mAlphabetShiftState.isAutomaticShifted() ? AUTOMATIC_SHIFT + : (mAlphabetShiftState.isShiftedOrShiftLocked() ? MANUAL_SHIFT : UNSHIFT); } else { state.mIsAlphabetShiftLocked = mPrevMainKeyboardWasShiftLocked; - state.mIsShifted = mIsSymbolShifted; + state.mShiftMode = mIsSymbolShifted ? MANUAL_SHIFT : UNSHIFT; } state.mIsValid = true; if (DEBUG_EVENT) { @@ -153,7 +158,7 @@ public final class KeyboardState { if (!state.mIsValid || state.mIsAlphabetMode) { setAlphabetKeyboard(); } else { - if (state.mIsShifted) { + if (state.mShiftMode == MANUAL_SHIFT) { setSymbolsShiftedKeyboard(); } else { setSymbolsKeyboard(); @@ -166,18 +171,13 @@ public final class KeyboardState { if (state.mIsAlphabetMode) { setShiftLocked(state.mIsAlphabetShiftLocked); if (!state.mIsAlphabetShiftLocked) { - setShifted(state.mIsShifted ? MANUAL_SHIFT : UNSHIFT); + setShifted(state.mShiftMode); } } else { mPrevMainKeyboardWasShiftLocked = state.mIsAlphabetShiftLocked; } } - private static final int UNSHIFT = 0; - private static final int MANUAL_SHIFT = 1; - private static final int AUTOMATIC_SHIFT = 2; - private static final int SHIFT_LOCK_SHIFTED = 3; - private void setShifted(final int shiftMode) { if (DEBUG_ACTION) { Log.d(TAG, "setShifted: shiftMode=" + shiftModeToString(shiftMode) + " " + this); @@ -634,7 +634,7 @@ public final class KeyboardState { } } - private static String shiftModeToString(final int shiftMode) { + static String shiftModeToString(final int shiftMode) { switch (shiftMode) { case UNSHIFT: return "UNSHIFT"; case MANUAL_SHIFT: return "MANUAL"; diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java index c8c7bb456..4fc1919dc 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java @@ -107,13 +107,16 @@ public final class BinaryDictionary extends Dictionary { @Override public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, - final String prevWord, final ProximityInfo proximityInfo) { - return getSuggestionsWithSessionId(composer, prevWord, proximityInfo, 0); + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { + return getSuggestionsWithSessionId(composer, prevWord, proximityInfo, blockOffensiveWords, + 0 /* sessionId */); } @Override public ArrayList<SuggestedWordInfo> getSuggestionsWithSessionId(final WordComposer composer, - final String prevWord, final ProximityInfo proximityInfo, int sessionId) { + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords, final int sessionId) { if (!isValidDictionary()) return null; Arrays.fill(mInputCodePoints, Constants.NOT_A_CODE); @@ -139,8 +142,6 @@ public final class BinaryDictionary extends Dictionary { inputSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray, mUseFullEditDistance, mOutputCodePoints, mOutputScores, mSpaceIndices, mOutputTypes); - final boolean blockPotentiallyOffensive = - Settings.getInstance().getBlockPotentiallyOffensive(); final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList(); for (int j = 0; j < count; ++j) { final int start = j * MAX_WORD_LENGTH; @@ -150,7 +151,7 @@ public final class BinaryDictionary extends Dictionary { } if (len > 0) { final int flags = mOutputTypes[j] & SuggestedWordInfo.KIND_MASK_FLAGS; - if (blockPotentiallyOffensive + if (blockOffensiveWords && 0 != (flags & SuggestedWordInfo.KIND_FLAG_POSSIBLY_OFFENSIVE) && 0 == (flags & SuggestedWordInfo.KIND_FLAG_EXACT_MATCH)) { // If we block potentially offensive words, and if the word is possibly diff --git a/java/src/com/android/inputmethod/latin/Dictionary.java b/java/src/com/android/inputmethod/latin/Dictionary.java index 9691fa231..acd7c2aa1 100644 --- a/java/src/com/android/inputmethod/latin/Dictionary.java +++ b/java/src/com/android/inputmethod/latin/Dictionary.java @@ -51,18 +51,21 @@ public abstract class Dictionary { * @param composer the key sequence to match with coordinate info, as a WordComposer * @param prevWord the previous word, or null if none * @param proximityInfo the object for key proximity. May be ignored by some implementations. + * @param blockOffensiveWords whether to block potentially offensive words * @return the list of suggestions (possibly null if none) */ // 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 String prevWord, final ProximityInfo proximityInfo); + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords); // 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 String prevWord, final ProximityInfo proximityInfo, final int sessionId) { - return getSuggestions(composer, prevWord, proximityInfo); + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords, final int sessionId) { + return getSuggestions(composer, prevWord, proximityInfo, blockOffensiveWords); } /** diff --git a/java/src/com/android/inputmethod/latin/DictionaryCollection.java b/java/src/com/android/inputmethod/latin/DictionaryCollection.java index 2832ad43c..ed2b44223 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryCollection.java +++ b/java/src/com/android/inputmethod/latin/DictionaryCollection.java @@ -56,18 +56,19 @@ public final class DictionaryCollection extends Dictionary { @Override public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, - final String prevWord, final ProximityInfo proximityInfo) { + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { final CopyOnWriteArrayList<Dictionary> dictionaries = mDictionaries; if (dictionaries.isEmpty()) return null; // To avoid creating unnecessary objects, we get the list out of the first // dictionary and add the rest to it if not null, hence the get(0) ArrayList<SuggestedWordInfo> suggestions = dictionaries.get(0).getSuggestions(composer, - prevWord, proximityInfo); + prevWord, proximityInfo, blockOffensiveWords); if (null == suggestions) suggestions = CollectionUtils.newArrayList(); final int length = dictionaries.size(); for (int i = 1; i < length; ++ i) { final ArrayList<SuggestedWordInfo> sugg = dictionaries.get(i).getSuggestions(composer, - prevWord, proximityInfo); + prevWord, proximityInfo, blockOffensiveWords); if (null != sugg) suggestions.addAll(sugg); } return suggestions; diff --git a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java index 4b1975a00..887d657e9 100644 --- a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java @@ -200,12 +200,14 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { @Override public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, - final String prevWord, final ProximityInfo proximityInfo) { + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { asyncReloadDictionaryIfRequired(); if (mLocalDictionaryController.tryLock()) { try { if (mBinaryDictionary != null) { - return mBinaryDictionary.getSuggestions(composer, prevWord, proximityInfo); + return mBinaryDictionary.getSuggestions(composer, prevWord, proximityInfo, + blockOffensiveWords); } } finally { mLocalDictionaryController.unlock(); diff --git a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java index fd81d13ca..0dabdb835 100644 --- a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java +++ b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java @@ -253,7 +253,8 @@ public class ExpandableDictionary extends Dictionary { @Override public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, - final String prevWord, final ProximityInfo proximityInfo) { + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { if (reloadDictionaryIfRequired()) return null; if (composer.size() > 1) { if (composer.size() >= Constants.Dictionary.MAX_WORD_LENGTH) { diff --git a/java/src/com/android/inputmethod/latin/JniUtils.java b/java/src/com/android/inputmethod/latin/JniUtils.java index f9305991a..8aedee576 100644 --- a/java/src/com/android/inputmethod/latin/JniUtils.java +++ b/java/src/com/android/inputmethod/latin/JniUtils.java @@ -23,15 +23,19 @@ import com.android.inputmethod.latin.define.JniLibName; public final class JniUtils { private static final String TAG = JniUtils.class.getSimpleName(); - private JniUtils() { - // This utility class is not publicly instantiable. - } - - public static void loadNativeLibrary() { + static { try { System.loadLibrary(JniLibName.JNI_LIB_NAME); } catch (UnsatisfiedLinkError ule) { Log.e(TAG, "Could not load native library " + JniLibName.JNI_LIB_NAME, ule); } } + + private JniUtils() { + // This utility class is not publicly instantiable. + } + + public static void loadNativeLibrary() { + // Ensures the static initializer is called + } } diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 16eab4bc4..84c752934 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -929,8 +929,11 @@ public final class LatinIME extends InputMethodService implements KeyboardAction resetEntireInputState(newSelStart); } - // We moved the cursor. If we are touching a word, we need to resume suggestion. - mHandler.postResumeSuggestions(); + // We moved the cursor. If we are touching a word, we need to resume suggestion, + // unless suggestions are off. + if (isSuggestionsStripVisible()) { + mHandler.postResumeSuggestions(); + } // Reset the last recapitalization. mRecapitalizeStatus.deactivate(); mKeyboardSwitcher.updateShiftState(); @@ -1574,21 +1577,11 @@ public final class LatinIME extends InputMethodService implements KeyboardAction commitTyped(LastComposedWord.NOT_A_SEPARATOR); } 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: 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(); - if (Character.isLetter(codePointBeforeCursor) - || mSettings.getCurrent().isUsuallyFollowedBySpace(codePointBeforeCursor)) { - mSpaceState = SPACE_STATE_PHANTOM; - } + } + final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); + if (Character.isLetterOrDigit(codePointBeforeCursor) + || mSettings.getCurrent().isUsuallyFollowedBySpace(codePointBeforeCursor)) { + mSpaceState = SPACE_STATE_PHANTOM; } mConnection.endBatchEdit(); mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode()); @@ -1902,6 +1895,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction final int y, final int spaceState) { boolean isComposingWord = mWordComposer.isComposingWord(); + // TODO: remove isWordConnector() and use isUsuallyFollowedBySpace() instead. + // See onStartBatchInput() to see how to do it. if (SPACE_STATE_PHANTOM == spaceState && !mSettings.getCurrent().isWordConnector(primaryCode)) { if (isComposingWord) { @@ -2108,6 +2103,8 @@ public final class LatinIME extends InputMethodService implements KeyboardAction return false; if (mSuggestionStripView.isShowingAddToDictionaryHint()) return true; + if (null == mSettings.getCurrent()) + return false; if (!mSettings.getCurrent().isSuggestionStripVisibleInOrientation(mDisplayOrientation)) return false; if (mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) @@ -2180,6 +2177,7 @@ public final class LatinIME extends InputMethodService implements KeyboardAction mConnection.getNthPreviousWord(mSettings.getCurrent().mWordSeparators, mWordComposer.isComposingWord() ? 2 : 1); return mSuggest.getSuggestedWords(mWordComposer, prevWord, keyboard.getProximityInfo(), + mSettings.getBlockPotentiallyOffensive(), mSettings.getCurrent().mCorrectionEnabled, sessionId); } diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java index 59d0207f6..dc9bef22a 100644 --- a/java/src/com/android/inputmethod/latin/Suggest.java +++ b/java/src/com/android/inputmethod/latin/Suggest.java @@ -174,21 +174,22 @@ public final class Suggest { public SuggestedWords getSuggestedWords(final WordComposer wordComposer, final String prevWordForBigram, final ProximityInfo proximityInfo, - final boolean isCorrectionEnabled, final int sessionId) { + final boolean blockOffensiveWords, final boolean isCorrectionEnabled, + final int sessionId) { LatinImeLogger.onStartSuggestion(prevWordForBigram); if (wordComposer.isBatchMode()) { return getSuggestedWordsForBatchInput( - wordComposer, prevWordForBigram, proximityInfo, sessionId); + wordComposer, prevWordForBigram, proximityInfo, blockOffensiveWords, sessionId); } else { return getSuggestedWordsForTypingInput(wordComposer, prevWordForBigram, proximityInfo, - isCorrectionEnabled); + blockOffensiveWords, isCorrectionEnabled); } } // Retrieves suggestions for the typing input. private SuggestedWords getSuggestedWordsForTypingInput(final WordComposer wordComposer, final String prevWordForBigram, final ProximityInfo proximityInfo, - final boolean isCorrectionEnabled) { + final boolean blockOffensiveWords, final boolean isCorrectionEnabled) { final int trailingSingleQuotesCount = wordComposer.trailingSingleQuotesCount(); final BoundedTreeSet suggestionsSet = new BoundedTreeSet(sSuggestedWordInfoComparator, MAX_SUGGESTIONS); @@ -212,7 +213,7 @@ public final class Suggest { for (final String key : mDictionaries.keySet()) { final Dictionary dictionary = mDictionaries.get(key); suggestionsSet.addAll(dictionary.getSuggestions( - wordComposerForLookup, prevWordForBigram, proximityInfo)); + wordComposerForLookup, prevWordForBigram, proximityInfo, blockOffensiveWords)); } final String whitelistedWord; @@ -301,7 +302,7 @@ public final class Suggest { // Retrieves suggestions for the batch input. private SuggestedWords getSuggestedWordsForBatchInput(final WordComposer wordComposer, final String prevWordForBigram, final ProximityInfo proximityInfo, - final int sessionId) { + final boolean blockOffensiveWords, final int sessionId) { final BoundedTreeSet suggestionsSet = new BoundedTreeSet(sSuggestedWordInfoComparator, MAX_SUGGESTIONS); @@ -314,8 +315,8 @@ public final class Suggest { continue; } final Dictionary dictionary = mDictionaries.get(key); - suggestionsSet.addAll(dictionary.getSuggestionsWithSessionId( - wordComposer, prevWordForBigram, proximityInfo, sessionId)); + suggestionsSet.addAll(dictionary.getSuggestionsWithSessionId(wordComposer, + prevWordForBigram, proximityInfo, blockOffensiveWords, sessionId)); } for (SuggestedWordInfo wordInfo : suggestionsSet) { diff --git a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java index ec4dc1436..92f96c027 100644 --- a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedContactsBinaryDictionary.java @@ -33,9 +33,10 @@ public final class SynchronouslyLoadedContactsBinaryDictionary extends ContactsB @Override public synchronized ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer codes, - final String prevWordForBigrams, final ProximityInfo proximityInfo) { + final String prevWordForBigrams, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { syncReloadDictionaryIfRequired(); - return super.getSuggestions(codes, prevWordForBigrams, proximityInfo); + return super.getSuggestions(codes, prevWordForBigrams, proximityInfo, blockOffensiveWords); } @Override diff --git a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java index 4bdaf2039..33fe89611 100644 --- a/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/SynchronouslyLoadedUserBinaryDictionary.java @@ -36,9 +36,10 @@ public final class SynchronouslyLoadedUserBinaryDictionary extends UserBinaryDic @Override public synchronized ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer codes, - final String prevWordForBigrams, final ProximityInfo proximityInfo) { + final String prevWordForBigrams, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { syncReloadDictionaryIfRequired(); - return super.getSuggestions(codes, prevWordForBigrams, proximityInfo); + return super.getSuggestions(codes, prevWordForBigrams, proximityInfo, blockOffensiveWords); } @Override diff --git a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java index 044180bd6..affe3a348 100644 --- a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java +++ b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java @@ -30,6 +30,7 @@ import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; +import android.widget.ImageView; import android.widget.TextView; import android.widget.VideoView; @@ -58,7 +59,7 @@ public final class SetupActivity extends Activity implements View.OnClickListene private SetupStepGroup mSetupStepGroup; private static final String STATE_STEP = "step"; private int mStepNumber; - private static final int STEP_0 = 0; + private static final int STEP_WELCOME = 0; private static final int STEP_1 = 1; private static final int STEP_2 = 2; private static final int STEP_3 = 3; @@ -112,18 +113,20 @@ public final class SetupActivity extends Activity implements View.OnClickListene if (savedInstanceState == null) { mStepNumber = determineSetupStepNumber(); + if (mStepNumber == STEP_1 && !mWasLanguageAndInputSettingsInvoked) { + mStepNumber = STEP_WELCOME; + } + if (mStepNumber == STEP_3) { + // This IME already has been enabled and set as current IME. + // TODO: Implement tutorial. + invokeSettingsOfThisIme(); + finish(); + return; + } } 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; - } - final String applicationName = getResources().getString(getApplicationInfo().labelRes); mWelcomeScreen = findViewById(R.id.setup_welcome_screen); final TextView welcomeTitle = (TextView)findViewById(R.id.setup_welcome_title); @@ -201,11 +204,14 @@ public final class SetupActivity extends Activity implements View.OnClickListene mWelcomeVideoView.setBackgroundResource(0); } }); + final ImageView welcomeImageView = (ImageView)findViewById(R.id.setup_welcome_image); mWelcomeVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(final MediaPlayer mp, final int what, final int extra) { Log.e(TAG, "Playing welcome video causes error: what=" + what + " extra=" + extra); mWelcomeVideoView.setVisibility(View.GONE); + welcomeImageView.setImageResource(R.raw.setup_welcome_image); + welcomeImageView.setVisibility(View.VISIBLE); return true; } }); @@ -226,13 +232,13 @@ public final class SetupActivity extends Activity implements View.OnClickListene finish(); return; } - final int stepState = determineSetupState(); + final int currentStep = determineSetupStepNumber(); final int nextStep; if (v == mActionStart) { nextStep = STEP_1; } else if (v == mActionNext) { nextStep = mStepNumber + 1; - } else if (v == mStep1Bullet && stepState == STEP_2) { + } else if (v == mStep1Bullet && currentStep == STEP_2) { nextStep = STEP_1; } else { nextStep = mStepNumber; @@ -312,7 +318,7 @@ public final class SetupActivity extends Activity implements View.OnClickListene return myImi.getId().equals(currentImeId); } - private int determineSetupState() { + private int determineSetupStepNumber() { mHandler.cancelPollingImeSettings(); if (!isThisImeEnabled(this)) { return STEP_1; @@ -323,14 +329,6 @@ public final class SetupActivity extends Activity implements View.OnClickListene return STEP_3; } - private int determineSetupStepNumber() { - final int stepState = determineSetupState(); - if (stepState == STEP_1) { - return mWasLanguageAndInputSettingsInvoked ? STEP_1 : STEP_0; - } - return stepState; - } - @Override protected void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); @@ -344,15 +342,11 @@ public final class SetupActivity extends Activity implements View.OnClickListene } @Override - protected void onStart() { - super.onStart(); - mStepNumber = determineSetupStepNumber(); - } - - @Override protected void onRestart() { super.onRestart(); - mStepNumber = determineSetupStepNumber(); + if (mStepNumber != STEP_WELCOME) { + mStepNumber = determineSetupStepNumber(); + } } @Override @@ -364,7 +358,7 @@ public final class SetupActivity extends Activity implements View.OnClickListene @Override public void onBackPressed() { if (mStepNumber == STEP_1) { - mStepNumber = STEP_0; + mStepNumber = STEP_WELCOME; updateSetupStepView(); return; } @@ -380,15 +374,14 @@ public final class SetupActivity extends Activity implements View.OnClickListene @Override public void onWindowFocusChanged(final boolean hasFocus) { super.onWindowFocusChanged(hasFocus); - if (!hasFocus) { - return; + if (hasFocus && mStepNumber != STEP_WELCOME) { + mStepNumber = determineSetupStepNumber(); + updateSetupStepView(); } - mStepNumber = determineSetupStepNumber(); - updateSetupStepView(); } private void updateSetupStepView() { - final boolean welcomeScreen = (mStepNumber == STEP_0); + final boolean welcomeScreen = (mStepNumber == STEP_WELCOME); mWelcomeScreen.setVisibility(welcomeScreen ? View.VISIBLE : View.GONE); mSetupScreen.setVisibility(welcomeScreen ? View.GONE: View.VISIBLE); if (welcomeScreen) { @@ -397,7 +390,7 @@ public final class SetupActivity extends Activity implements View.OnClickListene return; } mWelcomeVideoView.stopPlayback(); - final boolean isStepActionAlreadyDone = mStepNumber < determineSetupState(); + final boolean isStepActionAlreadyDone = mStepNumber < determineSetupStepNumber(); mSetupStepGroup.enableStep(mStepNumber, isStepActionAlreadyDone); mActionNext.setVisibility(isStepActionAlreadyDone ? View.VISIBLE : View.GONE); mActionFinish.setVisibility((mStepNumber == STEP_3) ? View.VISIBLE : View.GONE); diff --git a/java/src/com/android/inputmethod/latin/setup/SetupStartIndicatorView.java b/java/src/com/android/inputmethod/latin/setup/SetupStartIndicatorView.java index ca974f6b8..974dfddd3 100644 --- a/java/src/com/android/inputmethod/latin/setup/SetupStartIndicatorView.java +++ b/java/src/com/android/inputmethod/latin/setup/SetupStartIndicatorView.java @@ -51,11 +51,32 @@ public final class SetupStartIndicatorView extends LinearLayout { mIndicatorView = indicatorView; } + // TODO: Once we stop supporting ICS, uncomment {@link #setPressed(boolean)} method and + // remove this method. @Override - public void setPressed(final boolean pressed) { - super.setPressed(pressed); + protected void drawableStateChanged() { + super.drawableStateChanged(); + for (final int state : getDrawableState()) { + if (state == android.R.attr.state_pressed) { + updateIndicatorView(true /* pressed */); + return; + } + } + updateIndicatorView(false /* pressed */); + } + + // TODO: Once we stop supporting ICS, uncomment this method and remove + // {@link #drawableStateChanged()} method. +// @Override +// public void setPressed(final boolean pressed) { +// super.setPressed(pressed); +// updateIndicatorView(pressed); +// } + + private void updateIndicatorView(final boolean pressed) { if (mIndicatorView != null) { mIndicatorView.setPressed(pressed); + mIndicatorView.invalidate(); } } } @@ -73,12 +94,6 @@ public final class SetupStartIndicatorView extends LinearLayout { } @Override - public void setPressed(final boolean pressed) { - super.setPressed(pressed); - invalidate(); - } - - @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); final int layoutDirection = ViewCompatUtils.getLayoutDirection(this); diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java index 2d0a89bb3..aa60496ae 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java @@ -64,8 +64,6 @@ public final class AndroidSpellCheckerService extends SpellCheckerService CollectionUtils.newSynchronizedTreeMap(); private ContactsBinaryDictionary mContactsDictionary; - // The threshold for a candidate to be offered as a suggestion. - private float mSuggestionThreshold; // The threshold for a suggestion to be considered "recommended". private float mRecommendedThreshold; // Whether to use the contacts dictionary @@ -112,8 +110,6 @@ public final class AndroidSpellCheckerService extends SpellCheckerService @Override public void onCreate() { super.onCreate(); - mSuggestionThreshold = - Float.parseFloat(getString(R.string.spellchecker_suggestion_threshold_value)); mRecommendedThreshold = Float.parseFloat(getString(R.string.spellchecker_recommended_threshold_value)); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); @@ -198,8 +194,7 @@ public final class AndroidSpellCheckerService extends SpellCheckerService } public SuggestionsGatherer newSuggestionsGatherer(final String text, int maxLength) { - return new SuggestionsGatherer( - text, mSuggestionThreshold, mRecommendedThreshold, maxLength); + return new SuggestionsGatherer(text, mRecommendedThreshold, maxLength); } // TODO: remove this class and replace it by storage local to the session. @@ -217,7 +212,6 @@ public final class AndroidSpellCheckerService extends SpellCheckerService private final ArrayList<String> mSuggestions; private final int[] mScores; private final String mOriginalText; - private final float mSuggestionThreshold; private final float mRecommendedThreshold; private final int mMaxLength; private int mLength = 0; @@ -227,10 +221,9 @@ public final class AndroidSpellCheckerService extends SpellCheckerService private String mBestSuggestion = null; private int mBestScore = Integer.MIN_VALUE; // As small as possible - SuggestionsGatherer(final String originalText, final float suggestionThreshold, - final float recommendedThreshold, final int maxLength) { + SuggestionsGatherer(final String originalText, final float recommendedThreshold, + final int maxLength) { mOriginalText = originalText; - mSuggestionThreshold = suggestionThreshold; mRecommendedThreshold = recommendedThreshold; mMaxLength = maxLength; mSuggestions = CollectionUtils.newArrayList(maxLength + 1); @@ -267,16 +260,7 @@ public final class AndroidSpellCheckerService extends SpellCheckerService return true; } - // Compute the normalized score and skip this word if it's normalized score does not - // make the threshold. final String wordString = new String(word, wordOffset, wordLength); - final float normalizedScore = - BinaryDictionary.calcNormalizedScore(mOriginalText, wordString, score); - if (normalizedScore < mSuggestionThreshold) { - if (DBG) Log.i(TAG, wordString + " does not make the score threshold"); - return true; - } - if (mLength < mMaxLength) { final int copyLen = mLength - insertIndex; ++mLength; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java index da8657201..61850e42e 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java @@ -283,20 +283,6 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session { //suggestionsLimit); final SuggestionsGatherer suggestionsGatherer = mService.newSuggestionsGatherer( text, suggestionsLimit); - final WordComposer composer = new WordComposer(); - final int length = text.length(); - for (int i = 0; i < length; i = text.offsetByCodePoints(i, 1)) { - final int codePoint = text.codePointAt(i); - // The getXYForCodePointAndScript method returns (Y << 16) + X - final int xy = SpellCheckerProximityInfo.getXYForCodePointAndScript( - codePoint, mScript); - if (SpellCheckerProximityInfo.NOT_A_COORDINATE_PAIR == xy) { - composer.add(codePoint, - Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); - } else { - composer.add(codePoint, xy & 0xFFFF, xy >> 16); - } - } final int capitalizeType = StringUtils.getCapitalizationType(text); boolean isInDict = true; @@ -306,9 +292,24 @@ public abstract class AndroidWordLevelSpellCheckerSession extends Session { if (!DictionaryPool.isAValidDictionary(dictInfo)) { return AndroidSpellCheckerService.getNotInDictEmptySuggestions(); } + final WordComposer composer = new WordComposer(); + final int length = text.length(); + for (int i = 0; i < length; i = text.offsetByCodePoints(i, 1)) { + final int codePoint = text.codePointAt(i); + // The getXYForCodePointAndScript method returns (Y << 16) + X + final int xy = SpellCheckerProximityInfo.getXYForCodePointAndScript( + codePoint, mScript); + if (SpellCheckerProximityInfo.NOT_A_COORDINATE_PAIR == xy) { + composer.add(codePoint, + Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); + } else { + composer.add(codePoint, xy & 0xFFFF, xy >> 16); + } + } + // TODO: make a spell checker option to block offensive words or not final ArrayList<SuggestedWordInfo> suggestions = dictInfo.mDictionary.getSuggestions(composer, prevWord, - dictInfo.mProximityInfo); + dictInfo.mProximityInfo, true /* blockOffensiveWords */); for (final SuggestedWordInfo suggestion : suggestions) { final String suggestionStr = suggestion.mWord; suggestionsGatherer.addWord(suggestionStr.toCharArray(), null, 0, diff --git a/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java b/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java index 81dd92d9e..27964b3c6 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java @@ -51,7 +51,8 @@ public final class DictionaryPool extends LinkedBlockingQueue<DictAndProximity> new Dictionary(Dictionary.TYPE_MAIN) { @Override public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, - final String prevWord, final ProximityInfo proximityInfo) { + final String prevWord, final ProximityInfo proximityInfo, + final boolean blockOffensiveWords) { return noSuggestions; } @Override diff --git a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java index 3037669c0..09f81d4c7 100644 --- a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java +++ b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java @@ -23,19 +23,28 @@ import android.graphics.drawable.Drawable; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.Keyboard; +import com.android.inputmethod.keyboard.KeyboardActionListener; import com.android.inputmethod.keyboard.TypefaceUtils; import com.android.inputmethod.keyboard.internal.KeyboardBuilder; import com.android.inputmethod.keyboard.internal.KeyboardIconsSet; import com.android.inputmethod.keyboard.internal.KeyboardParams; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.SuggestedWords; +import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.Utils; public final class MoreSuggestions extends Keyboard { public static final int SUGGESTION_CODE_BASE = 1024; - MoreSuggestions(final MoreSuggestionsParam params) { + public final SuggestedWords mSuggestedWords; + + public static abstract class MoreSuggestionsListener extends KeyboardActionListener.Adapter { + public abstract void onSuggestionSelected(final int index, final SuggestedWordInfo info); + } + + MoreSuggestions(final MoreSuggestionsParam params, final SuggestedWords suggestedWords) { super(params); + mSuggestedWords = suggestedWords; } private static final class MoreSuggestionsParam extends KeyboardParams { @@ -52,8 +61,9 @@ public final class MoreSuggestions extends Keyboard { super(); } - public int layout(final SuggestedWords suggestions, final int fromPos, final int maxWidth, - final int minWidth, final int maxRow, final Paint paint, final Resources res) { + public int layout(final SuggestedWords suggestedWords, final int fromPos, + final int maxWidth, final int minWidth, final int maxRow, final Paint paint, + final Resources res) { clearKeys(); mDivider = res.getDrawable(R.drawable.more_suggestions_divider); mDividerWidth = mDivider.getIntrinsicWidth(); @@ -61,9 +71,9 @@ public final class MoreSuggestions extends Keyboard { int row = 0; int pos = fromPos, rowStartPos = fromPos; - final int size = Math.min(suggestions.size(), SuggestionStripView.MAX_SUGGESTIONS); + final int size = Math.min(suggestedWords.size(), SuggestionStripView.MAX_SUGGESTIONS); while (pos < size) { - final String word = suggestions.getWord(pos); + final String word = suggestedWords.getWord(pos); // TODO: Should take care of text x-scaling. mWidths[pos] = (int)(TypefaceUtils.getLabelWidth(word, paint) + padding); final int numColumn = pos - rowStartPos + 1; @@ -163,7 +173,7 @@ public final class MoreSuggestions extends Keyboard { public static final class Builder extends KeyboardBuilder<MoreSuggestionsParam> { private final MoreSuggestionsView mPaneView; - private SuggestedWords mSuggestions; + private SuggestedWords mSuggestedWords; private int mFromPos; private int mToPos; @@ -172,7 +182,7 @@ public final class MoreSuggestions extends Keyboard { mPaneView = paneView; } - public Builder layout(final SuggestedWords suggestions, final int fromPos, + public Builder layout(final SuggestedWords suggestedWords, final int fromPos, final int maxWidth, final int minWidth, final int maxRow, final Keyboard parentKeyboard) { final int xmlId = R.xml.kbd_suggestions_pane_template; @@ -180,11 +190,11 @@ public final class MoreSuggestions extends Keyboard { mParams.mVerticalGap = mParams.mTopPadding = parentKeyboard.mVerticalGap / 2; mPaneView.updateKeyboardGeometry(mParams.mDefaultRowHeight); - final int count = mParams.layout(suggestions, fromPos, maxWidth, minWidth, maxRow, + final int count = mParams.layout(suggestedWords, fromPos, maxWidth, minWidth, maxRow, mPaneView.newLabelPaint(null /* key */), mResources); mFromPos = fromPos; mToPos = fromPos + count; - mSuggestions = suggestions; + mSuggestedWords = suggestedWords; return this; } @@ -195,8 +205,8 @@ public final class MoreSuggestions extends Keyboard { final int x = params.getX(pos); final int y = params.getY(pos); final int width = params.getWidth(pos); - final String word = mSuggestions.getWord(pos).toString(); - final String info = Utils.getDebugInfo(mSuggestions, pos); + final String word = mSuggestedWords.getWord(pos); + final String info = Utils.getDebugInfo(mSuggestedWords, pos); final int index = pos + SUGGESTION_CODE_BASE; final Key key = new Key( params, word, info, KeyboardIconsSet.ICON_UNDEFINED, index, null, x, y, @@ -211,7 +221,7 @@ public final class MoreSuggestions extends Keyboard { params.onAddKey(divider); } } - return new MoreSuggestions(params); + return new MoreSuggestions(params, mSuggestedWords); } } diff --git a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java index 6509f394b..d585b5c7f 100644 --- a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java +++ b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestionsView.java @@ -18,15 +18,21 @@ package com.android.inputmethod.latin.suggestions; import android.content.Context; import android.util.AttributeSet; +import android.util.Log; +import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.MoreKeysKeyboardView; import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.SuggestedWords; +import com.android.inputmethod.latin.suggestions.MoreSuggestions.MoreSuggestionsListener; /** * 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 MoreKeysKeyboardView { + private static final String TAG = MoreSuggestionsView.class.getSimpleName(); + public MoreSuggestionsView(final Context context, final AttributeSet attrs) { this(context, attrs, R.attr.moreSuggestionsViewStyle); } @@ -54,9 +60,24 @@ public final class MoreSuggestionsView extends MoreKeysKeyboardView { @Override public void onCodeInput(final int code, final int x, final int y) { + final Keyboard keyboard = getKeyboard(); + if (!(keyboard instanceof MoreSuggestions)) { + Log.e(TAG, "Expected keyboard is MoreSuggestions, but found " + + keyboard.getClass().getName()); + return; + } + final SuggestedWords suggestedWords = ((MoreSuggestions)keyboard).mSuggestedWords; final int index = code - MoreSuggestions.SUGGESTION_CODE_BASE; - if (index >= 0 && index < SuggestionStripView.MAX_SUGGESTIONS) { - mListener.onCustomRequest(index); + if (index < 0 || index >= suggestedWords.size()) { + Log.e(TAG, "Selected suggestion has an illegal index: " + index); + return; + } + if (!(mListener instanceof MoreSuggestionsListener)) { + Log.e(TAG, "Expected mListener is MoreSuggestionsListener, but found " + + mListener.getClass().getName()); + return; } + ((MoreSuggestionsListener)mListener).onSuggestionSelected( + index, suggestedWords.getInfo(index)); } } diff --git a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java index 2a21ec2f5..ad350a02f 100644 --- a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java +++ b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java @@ -50,7 +50,6 @@ 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.KeyboardSwitcher; import com.android.inputmethod.keyboard.MainKeyboardView; import com.android.inputmethod.keyboard.MoreKeysPanel; @@ -65,6 +64,7 @@ import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.Utils; import com.android.inputmethod.latin.define.ProductionFlag; +import com.android.inputmethod.latin.suggestions.MoreSuggestions.MoreSuggestionsListener; import com.android.inputmethod.research.ResearchLogger; import java.util.ArrayList; @@ -93,7 +93,7 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick private final ArrayList<View> mDividers = CollectionUtils.newArrayList(); Listener mListener; - SuggestedWords mSuggestedWords = SuggestedWords.EMPTY; + private SuggestedWords mSuggestedWords = SuggestedWords.EMPTY; private final SuggestionStripViewParams mParams; private static final float MIN_TEXT_XSCALE = 0.70f; @@ -652,15 +652,11 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick dismissMoreSuggestions(); } - private final KeyboardActionListener mMoreSuggestionsListener = - new KeyboardActionListener.Adapter() { + private final MoreSuggestionsListener mMoreSuggestionsListener = new MoreSuggestionsListener() { @Override - public boolean onCustomRequest(final int requestCode) { - final int index = requestCode; - final SuggestedWordInfo wordInfo = mSuggestedWords.getInfo(index); + public void onSuggestionSelected(final int index, final SuggestedWordInfo wordInfo) { mListener.pickSuggestionManually(index, wordInfo); dismissMoreSuggestions(); - return true; } @Override |