diff options
author | 2011-05-11 12:18:21 +0900 | |
---|---|---|
committer | 2011-05-11 12:18:21 +0900 | |
commit | 55f38adab99937eef97626136f57520ebe9c04a9 (patch) | |
tree | 8a2c070730fbcbde3bd73640730334250e36f2c3 /java/src | |
parent | 38c984cbcc3e1264ce00483e876093202268ad65 (diff) | |
parent | 9fbfd5877305ed19a20663630b498b6b3fdae942 (diff) | |
download | latinime-55f38adab99937eef97626136f57520ebe9c04a9.tar.gz latinime-55f38adab99937eef97626136f57520ebe9c04a9.tar.xz latinime-55f38adab99937eef97626136f57520ebe9c04a9.zip |
Merge remote-tracking branch 'goog/master' into merge
Conflicts:
java/res/xml/method.xml
Change-Id: I04a476465593d25105545b98607425d2978ff872
Diffstat (limited to 'java/src')
13 files changed, 744 insertions, 503 deletions
diff --git a/java/src/com/android/inputmethod/keyboard/Keyboard.java b/java/src/com/android/inputmethod/keyboard/Keyboard.java index 21a4a081c..492883caf 100644 --- a/java/src/com/android/inputmethod/keyboard/Keyboard.java +++ b/java/src/com/android/inputmethod/keyboard/Keyboard.java @@ -63,6 +63,9 @@ public class Keyboard { public static final int CODE_TAB = '\t'; public static final int CODE_SPACE = ' '; public static final int CODE_PERIOD = '.'; + public static final int CODE_DASH = '-'; + public static final int CODE_SINGLE_QUOTE = '\''; + public static final int CODE_DOUBLE_QUOTE = '"'; /** Special keys code. These should be aligned with values/keycodes.xml */ public static final int CODE_DUMMY = 0; diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java index fbfde97ef..4f1ad576d 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java @@ -626,7 +626,7 @@ public class KeyboardSwitcher implements SharedPreferences.OnSharedPreferenceCha private static boolean isQuoteCharacter(int c) { // Apostrophe, quotation mark. - if (c == '\'' || c == '"') + if (c == Keyboard.CODE_SINGLE_QUOTE || c == Keyboard.CODE_DOUBLE_QUOTE) return true; // \u2018: Left single quotation mark // \u2019: Right single quotation mark diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardView.java b/java/src/com/android/inputmethod/keyboard/KeyboardView.java index 11476e069..08e739d5a 100644 --- a/java/src/com/android/inputmethod/keyboard/KeyboardView.java +++ b/java/src/com/android/inputmethod/keyboard/KeyboardView.java @@ -35,17 +35,16 @@ import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; -import android.os.SystemClock; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; -import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; +import android.view.ViewGroup.MarginLayoutParams; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.PopupWindow; @@ -53,7 +52,6 @@ import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.WeakHashMap; /** @@ -111,24 +109,18 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { private boolean mInForeground; private TextView mPreviewText; private int mPreviewTextSizeLarge; - private final int[] mOffsetInWindow = new int[2]; private boolean mShowKeyPreview = true; private int mKeyPreviewDisplayedY; private final int mDelayBeforePreview; private final int mDelayAfterPreview; private ViewGroup mPreviewPlacer; + private final int[] mCoordinates = new int[2]; // Mini keyboard - private PopupWindow mMiniKeyboardWindow; - private KeyboardView mMiniKeyboardView; - private final WeakHashMap<Key, View> mMiniKeyboardCache = new WeakHashMap<Key, View>(); - private int mMiniKeyboardOriginX; - private int mMiniKeyboardOriginY; - private long mMiniKeyboardDisplayedTime; - private int[] mWindowOffset; - private final float mMiniKeyboardSlideAllowance; - private int mMiniKeyboardTrackerId; - private final boolean mConfigShowMiniKeyboardAtTouchedPoint; + private PopupWindow mPopupWindow; + private PopupPanel mPopupMiniKeyboardPanel; + private final WeakHashMap<Key, PopupPanel> mPopupPanelCache = + new WeakHashMap<Key, PopupPanel>(); /** Listener for {@link KeyboardActionListener}. */ private KeyboardActionListener mKeyboardActionListener; @@ -148,7 +140,7 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { protected KeyDetector mKeyDetector = new KeyDetector(); // Swipe gesture detector - private GestureDetector mGestureDetector; + protected GestureDetector mGestureDetector; private final SwipeTracker mSwipeTracker = new SwipeTracker(); private final int mSwipeThreshold; private final boolean mDisambiguateSwipe; @@ -196,29 +188,24 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { @Override public void handleMessage(Message msg) { + final PointerTracker tracker = (PointerTracker) msg.obj; switch (msg.what) { - case MSG_SHOW_KEY_PREVIEW: - showKey(msg.arg1, (PointerTracker)msg.obj); - break; - case MSG_DISMISS_KEY_PREVIEW: - mPreviewText.setVisibility(View.INVISIBLE); - break; - case MSG_REPEAT_KEY: { - final PointerTracker tracker = (PointerTracker)msg.obj; - tracker.onRepeatKey(msg.arg1); - startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker); - break; - } - case MSG_LONGPRESS_KEY: { - final PointerTracker tracker = (PointerTracker)msg.obj; - openMiniKeyboardIfRequired(msg.arg1, tracker); - break; - } - case MSG_LONGPRESS_SHIFT_KEY: { - final PointerTracker tracker = (PointerTracker)msg.obj; - onLongPressShiftKey(tracker); - break; - } + case MSG_SHOW_KEY_PREVIEW: + showKey(msg.arg1, tracker); + break; + case MSG_DISMISS_KEY_PREVIEW: + mPreviewText.setVisibility(View.INVISIBLE); + break; + case MSG_REPEAT_KEY: + tracker.onRepeatKey(msg.arg1); + startKeyRepeatTimer(mKeyRepeatInterval, msg.arg1, tracker); + break; + case MSG_LONGPRESS_KEY: + openMiniKeyboardIfRequired(msg.arg1, tracker); + break; + case MSG_LONGPRESS_SHIFT_KEY: + onLongPressShiftKey(tracker); + break; } } @@ -390,12 +377,6 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { mKeyLabelHorizontalPadding = (int)res.getDimension( R.dimen.key_label_horizontal_alignment_padding); - mMiniKeyboardWindow = new PopupWindow(context); - mMiniKeyboardWindow.setBackgroundDrawable(null); - mMiniKeyboardWindow.setAnimationStyle(R.style.MiniKeyboardAnimation); - // Allow popup window to be drawn off the screen. - mMiniKeyboardWindow.setClippingEnabled(false); - mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(keyTextSize); @@ -406,11 +387,8 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { mKeyBackground.getPadding(mPadding); mSwipeThreshold = (int) (500 * res.getDisplayMetrics().density); - // TODO: Refer frameworks/base/core/res/res/values/config.xml + // TODO: Refer to frameworks/base/core/res/res/values/config.xml mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation); - mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance); - mConfigShowMiniKeyboardAtTouchedPoint = res.getBoolean( - R.bool.config_show_mini_keyboard_at_touched_point); GestureDetector.SimpleOnGestureListener listener = new GestureDetector.SimpleOnGestureListener() { @@ -530,7 +508,7 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { mKeyboardChanged = true; invalidateAllKeys(); mKeyDetector.setProximityThreshold(keyboard.getMostCommonKeyWidth()); - mMiniKeyboardCache.clear(); + mPopupPanelCache.clear(); } /** @@ -694,7 +672,7 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { } // Overlay a dark rectangle to dim the keyboard - if (mMiniKeyboardView != null) { + if (mPopupMiniKeyboardPanel != null) { mPaint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, width, height, mPaint); } @@ -947,8 +925,10 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { mPreviewPlacer = placer; } if (placer instanceof FrameLayout) { + // Honeycomb or later. placer.addView(keyPreview, new FrameLayout.LayoutParams(0, 0)); } else { + // Gingerbread or ealier. placer.addView(keyPreview, new LinearLayout.LayoutParams(0, 0)); } } @@ -956,10 +936,11 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { // TODO: Introduce minimum duration for displaying key previews // TODO: Display up to two key previews when the user presses two keys at the same time private void showKey(final int keyIndex, PointerTracker tracker) { + final TextView previewText = mPreviewText; // If the key preview has no parent view yet, add it to the ViewGroup which can place // key preview absolutely in SoftInputWindow. - if (mPreviewText.getParent() == null) { - addKeyPreview(mPreviewText); + if (previewText.getParent() == null) { + addKeyPreview(previewText); } final Key key = tracker.getKey(keyIndex); @@ -968,56 +949,51 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { // WindowManager.BadTokenException. if (key == null || !mInForeground) return; + + mHandler.cancelAllDismissKeyPreviews(); + final int keyDrawX = key.mX + key.mVisualInsetsLeft; final int keyDrawWidth = key.mWidth - key.mVisualInsetsLeft - key.mVisualInsetsRight; // What we show as preview should match what we show on key top in onBufferDraw(). if (key.mLabel != null) { // TODO Should take care of temporaryShiftLabel here. - mPreviewText.setCompoundDrawables(null, null, null, null); - mPreviewText.setText(adjustCase(tracker.getPreviewText(key))); + previewText.setCompoundDrawables(null, null, null, null); + previewText.setText(adjustCase(tracker.getPreviewText(key))); if (key.mLabel.length() > 1) { - mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyLetterSize); - mPreviewText.setTypeface(Typeface.DEFAULT_BOLD); + previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyLetterSize); + previewText.setTypeface(Typeface.DEFAULT_BOLD); } else { - mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge); - mPreviewText.setTypeface(mKeyLetterStyle); + previewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge); + previewText.setTypeface(mKeyLetterStyle); } } else { final Drawable previewIcon = key.getPreviewIcon(); - mPreviewText.setCompoundDrawables(null, null, null, + previewText.setCompoundDrawables(null, null, null, previewIcon != null ? previewIcon : key.getIcon()); - mPreviewText.setText(null); + previewText.setText(null); } // Set the preview background state - mPreviewText.getBackground().setState( + previewText.getBackground().setState( key.mPopupCharacters != null ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET); - mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), + previewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); - int previewWidth = Math.max(mPreviewText.getMeasuredWidth(), keyDrawWidth - + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight()); + final int previewWidth = Math.max(previewText.getMeasuredWidth(), keyDrawWidth + + previewText.getPaddingLeft() + previewText.getPaddingRight()); final int previewHeight = mPreviewHeight; - final ViewGroup.LayoutParams lp = mPreviewText.getLayoutParams(); - lp.width = previewWidth; - lp.height = previewHeight; - - int previewX = keyDrawX - (previewWidth - keyDrawWidth) / 2; - int previewY = key.mY - previewHeight + mPreviewOffset; - - mHandler.cancelAllDismissKeyPreviews(); - getLocationInWindow(mOffsetInWindow); - previewX += mOffsetInWindow[0]; - previewY += mOffsetInWindow[1]; + getLocationInWindow(mCoordinates); + final int previewX = keyDrawX - (previewWidth - keyDrawWidth) / 2 + mCoordinates[0]; + final int previewY = key.mY - previewHeight + mCoordinates[1] + mPreviewOffset; + // Record key preview position to display mini-keyboard later at the same position + mKeyPreviewDisplayedY = previewY; // Place the key preview. // TODO: Adjust position of key previews which touch screen edges - if (lp instanceof ViewGroup.MarginLayoutParams) { - ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams)lp; - mlp.setMargins(previewX, previewY, 0, 0); - } - // Record key preview position to display mini-keyboard later at the same position - mKeyPreviewDisplayedY = previewY; - mPreviewText.setVisibility(VISIBLE); + final MarginLayoutParams lp = (MarginLayoutParams)previewText.getLayoutParams(); + lp.width = previewWidth; + lp.height = previewHeight; + lp.setMargins(previewX, previewY, 0, 0); + previewText.setVisibility(VISIBLE); } /** @@ -1044,8 +1020,9 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { if (key == null) return; mInvalidatedKey = key; - mInvalidatedKeyRect.set(0, 0, key.mWidth, key.mHeight); - mInvalidatedKeyRect.offset(key.mX + getPaddingLeft(), key.mY + getPaddingTop()); + final int x = key.mX + getPaddingLeft(); + final int y = key.mY + getPaddingTop(); + mInvalidatedKeyRect.set(x, y, x + key.mWidth, y + key.mHeight); mDirtyRect.union(mInvalidatedKeyRect); onBufferDraw(); invalidate(mInvalidatedKeyRect); @@ -1057,13 +1034,12 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { return false; } - Key parentKey = tracker.getKey(keyIndex); + final Key parentKey = tracker.getKey(keyIndex); if (parentKey == null) return false; boolean result = onLongPress(parentKey, tracker); if (result) { dismissAllKeyPreviews(); - mMiniKeyboardTrackerId = tracker.mPointerId; tracker.onLongPressed(mPointerQueue); } return result; @@ -1081,13 +1057,18 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { mKeyboardActionListener.onCodeInput(Keyboard.CODE_CAPSLOCK, null, 0, 0); } - private View inflateMiniKeyboardContainer(Key parentKey) { + // This default implementation returns a popup mini keyboard panel. + // A derived class may return a language switcher popup panel, for instance. + protected PopupPanel onCreatePopupPanel(Key parentKey) { + if (parentKey.mPopupCharacters == null) + return null; + final View container = LayoutInflater.from(getContext()).inflate(mPopupLayout, null); if (container == null) throw new NullPointerException(); - final KeyboardView miniKeyboardView = - (KeyboardView)container.findViewById(R.id.KeyboardView); + final PopupMiniKeyboardView miniKeyboardView = + (PopupMiniKeyboardView)container.findViewById(R.id.mini_keyboard_view); miniKeyboardView.setOnKeyboardActionListener(new KeyboardActionListener() { @Override public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) { @@ -1120,10 +1101,6 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { mKeyboardActionListener.onRelease(primaryCode, withSliding); } }); - // Override default ProximityKeyDetector. - miniKeyboardView.mKeyDetector = new MiniKeyboardKeyDetector(mMiniKeyboardSlideAllowance); - // Remove gesture detector on mini-keyboard - miniKeyboardView.mGestureDetector = null; final Keyboard keyboard = new MiniKeyboardBuilder(this, mKeyboard.getPopupKeyboardResId(), parentKey).build(); @@ -1132,87 +1109,39 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { container.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST)); - return container; - } - - private static boolean isOneRowKeys(List<Key> keys) { - if (keys.size() == 0) return false; - final int edgeFlags = keys.get(0).mEdgeFlags; - // HACK: The first key of mini keyboard which was inflated from xml and has multiple rows, - // does not have both top and bottom edge flags on at the same time. On the other hand, - // the first key of mini keyboard that was created with popupCharacters must have both top - // and bottom edge flags on. - // When you want to use one row mini-keyboard from xml file, make sure that the row has - // both top and bottom edge flags set. - return (edgeFlags & Keyboard.EDGE_TOP) != 0 - && (edgeFlags & Keyboard.EDGE_BOTTOM) != 0; + return miniKeyboardView; } /** - * Called when a key is long pressed. By default this will open any mini keyboard associated - * with this key through the attributes popupLayout and popupCharacters. + * Called when a key is long pressed. By default this will open mini keyboard associated + * with this key. * @param parentKey the key that was long pressed + * @param tracker the pointer tracker which pressed the parent key * @return true if the long press is handled, false otherwise. Subclasses should call the * method on the base class if the subclass doesn't wish to handle the call. */ protected boolean onLongPress(Key parentKey, PointerTracker tracker) { - if (parentKey.mPopupCharacters == null) - return false; - - View container = mMiniKeyboardCache.get(parentKey); - if (container == null) { - container = inflateMiniKeyboardContainer(parentKey); - mMiniKeyboardCache.put(parentKey, container); - } - mMiniKeyboardView = (KeyboardView)container.findViewById(R.id.KeyboardView); - final MiniKeyboard miniKeyboard = (MiniKeyboard)mMiniKeyboardView.getKeyboard(); - - if (mWindowOffset == null) { - mWindowOffset = new int[2]; - getLocationInWindow(mWindowOffset); + PopupPanel popupPanel = mPopupPanelCache.get(parentKey); + if (popupPanel == null) { + popupPanel = onCreatePopupPanel(parentKey); + if (popupPanel == null) + return false; + mPopupPanelCache.put(parentKey, popupPanel); } - final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX() - : parentKey.mX + parentKey.mWidth / 2; - final int miniKeyboardX = pointX - miniKeyboard.getDefaultCoordX() - - container.getPaddingLeft() - + getPaddingLeft() + mWindowOffset[0]; - final int miniKeyboardY = parentKey.mY - mKeyboard.getVerticalGap() - - (container.getMeasuredHeight() - container.getPaddingBottom()) - + getPaddingTop() + mWindowOffset[1]; - final int x = miniKeyboardX; - final int y = mShowKeyPreview && isOneRowKeys(miniKeyboard.getKeys()) - ? mKeyPreviewDisplayedY : miniKeyboardY; - - mMiniKeyboardOriginX = x + container.getPaddingLeft() - mWindowOffset[0]; - mMiniKeyboardOriginY = y + container.getPaddingTop() - mWindowOffset[1]; - if (miniKeyboard.setShifted( - mKeyboard == null ? false : mKeyboard.isShiftedOrShiftLocked())) { - mMiniKeyboardView.invalidateAllKeys(); + if (mPopupWindow == null) { + mPopupWindow = new PopupWindow(getContext()); + mPopupWindow.setBackgroundDrawable(null); + mPopupWindow.setAnimationStyle(R.style.PopupMiniKeyboardAnimation); + // Allow popup window to be drawn off the screen. + mPopupWindow.setClippingEnabled(false); } - // Mini keyboard needs no pop-up key preview displayed. - mMiniKeyboardView.setKeyPreviewEnabled(false); - mMiniKeyboardWindow.setContentView(container); - mMiniKeyboardWindow.setWidth(container.getMeasuredWidth()); - mMiniKeyboardWindow.setHeight(container.getMeasuredHeight()); - mMiniKeyboardWindow.showAtLocation(this, Gravity.NO_GRAVITY, x, y); - - // Inject down event on the key to mini keyboard. - final long eventTime = SystemClock.uptimeMillis(); - mMiniKeyboardDisplayedTime = eventTime; - final MotionEvent downEvent = generateMiniKeyboardMotionEvent(MotionEvent.ACTION_DOWN, - pointX, parentKey.mY + parentKey.mHeight / 2, eventTime); - mMiniKeyboardView.onTouchEvent(downEvent); - downEvent.recycle(); + mPopupMiniKeyboardPanel = popupPanel; + popupPanel.showPanel(this, parentKey, tracker, mKeyPreviewDisplayedY, mPopupWindow); invalidateAllKeys(); return true; } - private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) { - return MotionEvent.obtain(mMiniKeyboardDisplayedTime, eventTime, action, - x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0); - } - private PointerTracker getPointerTracker(final int id) { final ArrayList<PointerTracker> pointers = mPointerTrackers; final KeyboardActionListener listener = mKeyboardActionListener; @@ -1232,8 +1161,8 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { } public boolean isInSlidingKeyInput() { - if (mMiniKeyboardView != null) { - return mMiniKeyboardView.isInSlidingKeyInput(); + if (mPopupMiniKeyboardPanel != null) { + return mPopupMiniKeyboardPanel.isInSlidingKeyInput(); } else { return mPointerQueue.isInSlidingKeyInput(); } @@ -1264,7 +1193,7 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { // Gesture detector must be enabled only when mini-keyboard is not on the screen and // accessibility is not enabled. // TODO: Reconcile gesture detection and accessibility features. - if (mMiniKeyboardView == null && !mIsAccessibilityEnabled + if (mPopupMiniKeyboardPanel == null && !mIsAccessibilityEnabled && mGestureDetector != null && mGestureDetector.onTouchEvent(me)) { dismissAllKeyPreviews(); mHandler.cancelKeyTimers(); @@ -1277,19 +1206,10 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { final int x = (int)me.getX(index); final int y = (int)me.getY(index); - // Needs to be called after the gesture detector gets a turn, as it may have - // displayed the mini keyboard - if (mMiniKeyboardView != null) { - final int miniKeyboardPointerIndex = me.findPointerIndex(mMiniKeyboardTrackerId); - if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) { - final int miniKeyboardX = (int)me.getX(miniKeyboardPointerIndex); - final int miniKeyboardY = (int)me.getY(miniKeyboardPointerIndex); - MotionEvent translated = generateMiniKeyboardMotionEvent(action, - miniKeyboardX, miniKeyboardY, eventTime); - mMiniKeyboardView.onTouchEvent(translated); - translated.recycle(); - } - return true; + // Needs to be called after the gesture detector gets a turn, as it may have displayed the + // mini keyboard + if (mPopupMiniKeyboardPanel != null) { + return mPopupMiniKeyboardPanel.onTouchEvent(me); } if (mHandler.isInKeyRepeat()) { @@ -1370,7 +1290,7 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { dismissMiniKeyboard(); mDirtyRect.union(0, 0, getWidth(), getHeight()); - mMiniKeyboardCache.clear(); + mPopupPanelCache.clear(); requestLayout(); } @@ -1385,21 +1305,17 @@ public class KeyboardView extends View implements PointerTracker.UIProxy { closing(); } - private void dismissMiniKeyboard() { - if (mMiniKeyboardWindow.isShowing()) { - mMiniKeyboardWindow.dismiss(); - mMiniKeyboardView = null; - mMiniKeyboardOriginX = 0; - mMiniKeyboardOriginY = 0; + private boolean dismissMiniKeyboard() { + if (mPopupWindow != null && mPopupWindow.isShowing()) { + mPopupWindow.dismiss(); + mPopupMiniKeyboardPanel = null; invalidateAllKeys(); + return true; } + return false; } public boolean handleBack() { - if (mMiniKeyboardWindow.isShowing()) { - dismissMiniKeyboard(); - return true; - } - return false; + return dismissMiniKeyboard(); } } diff --git a/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java b/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java index 3b1408ccf..5dde15e94 100644 --- a/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java +++ b/java/src/com/android/inputmethod/keyboard/MiniKeyboard.java @@ -18,6 +18,8 @@ package com.android.inputmethod.keyboard; import android.content.Context; +import java.util.List; + public class MiniKeyboard extends Keyboard { private int mDefaultKeyCoordX; @@ -32,4 +34,19 @@ public class MiniKeyboard extends Keyboard { public int getDefaultCoordX() { return mDefaultKeyCoordX; } + + public boolean isOneRowKeyboard() { + final List<Key> keys = getKeys(); + if (keys.size() == 0) return false; + final int edgeFlags = keys.get(0).mEdgeFlags; + // HACK: The first key of mini keyboard which was inflated from xml and has multiple rows, + // does not have both top and bottom edge flags on at the same time. On the other hand, + // the first key of mini keyboard that was created with popupCharacters must have both top + // and bottom edge flags on. + // When you want to use one row mini-keyboard from xml file, make sure that the row has + // both top and bottom edge flags set. + return (edgeFlags & Keyboard.EDGE_TOP) != 0 + && (edgeFlags & Keyboard.EDGE_BOTTOM) != 0; + + } } diff --git a/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java b/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java new file mode 100644 index 000000000..12031f1ea --- /dev/null +++ b/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.keyboard; + +import com.android.inputmethod.latin.R; + +import android.content.Context; +import android.content.res.Resources; +import android.os.SystemClock; +import android.util.AttributeSet; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.widget.PopupWindow; + +/** + * A view that renders a virtual {@link MiniKeyboard}. It handles rendering of keys and detecting + * key presses and touch movements. + */ +public class PopupMiniKeyboardView extends KeyboardView implements PopupPanel { + private final int[] mCoordinates = new int[2]; + private final boolean mConfigShowMiniKeyboardAtTouchedPoint; + + private int mOriginX; + private int mOriginY; + private int mTrackerId; + private long mDownTime; + + public PopupMiniKeyboardView(Context context, AttributeSet attrs) { + this(context, attrs, R.attr.keyboardViewStyle); + } + + public PopupMiniKeyboardView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + + final Resources res = context.getResources(); + mConfigShowMiniKeyboardAtTouchedPoint = res.getBoolean( + R.bool.config_show_mini_keyboard_at_touched_point); + // Override default ProximityKeyDetector. + mKeyDetector = new MiniKeyboardKeyDetector(res.getDimension( + R.dimen.mini_keyboard_slide_allowance)); + // Remove gesture detector on mini-keyboard + mGestureDetector = null; + setKeyPreviewEnabled(false); + } + + @Override + public void setKeyPreviewEnabled(boolean previewEnabled) { + // Mini keyboard needs no pop-up key preview displayed. + super.setKeyPreviewEnabled(false); + } + + @Override + public void showPanel(KeyboardView parentKeyboardView, Key parentKey, + PointerTracker tracker, int keyPreviewY, PopupWindow window) { + final View container = (View)getParent(); + final MiniKeyboard miniKeyboard = (MiniKeyboard)getKeyboard(); + final Keyboard parentKeyboard = parentKeyboardView.getKeyboard(); + + parentKeyboardView.getLocationInWindow(mCoordinates); + final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX() + : parentKey.mX + parentKey.mWidth / 2; + final int pointY = parentKey.mY; + final int miniKeyboardX = pointX - miniKeyboard.getDefaultCoordX() + - container.getPaddingLeft() + + parentKeyboardView.getPaddingLeft() + mCoordinates[0]; + final int miniKeyboardY = pointY - parentKeyboard.getVerticalGap() + - (container.getMeasuredHeight() - container.getPaddingBottom()) + + parentKeyboardView.getPaddingTop() + mCoordinates[1]; + final int x = miniKeyboardX; + final int y = parentKeyboardView.isKeyPreviewEnabled() && miniKeyboard.isOneRowKeyboard() + ? keyPreviewY : miniKeyboardY; + + if (miniKeyboard.setShifted(parentKeyboard.isShiftedOrShiftLocked())) { + invalidateAllKeys(); + } + window.setContentView(container); + window.setWidth(container.getMeasuredWidth()); + window.setHeight(container.getMeasuredHeight()); + window.showAtLocation(parentKeyboardView, Gravity.NO_GRAVITY, x, y); + + mOriginX = x + container.getPaddingLeft() - mCoordinates[0]; + mOriginY = y + container.getPaddingTop() - mCoordinates[1]; + mTrackerId = tracker.mPointerId; + mDownTime = SystemClock.uptimeMillis(); + + // Inject down event on the key to mini keyboard. + final MotionEvent downEvent = translateMotionEvent(MotionEvent.ACTION_DOWN, pointX, + pointY + parentKey.mHeight / 2, mDownTime); + onTouchEvent(downEvent); + downEvent.recycle(); + } + + private MotionEvent translateMotionEvent(int action, float x, float y, long eventTime) { + return MotionEvent.obtain(mDownTime, eventTime, action, x - mOriginX, y - mOriginY, 0); + } + + @Override + public boolean onTouchEvent(MotionEvent me) { + final int index = me.getActionIndex(); + final int id = me.getPointerId(index); + if (id == mTrackerId) { + final MotionEvent translated = translateMotionEvent(me.getAction(), me.getX(index), + me.getY(index), me.getEventTime()); + super.onTouchEvent(translated); + translated.recycle(); + } + return true; + } +} diff --git a/java/src/com/android/inputmethod/keyboard/PopupPanel.java b/java/src/com/android/inputmethod/keyboard/PopupPanel.java new file mode 100644 index 000000000..6f2b16148 --- /dev/null +++ b/java/src/com/android/inputmethod/keyboard/PopupPanel.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.keyboard; + +import android.view.MotionEvent; +import android.widget.PopupWindow; + +public interface PopupPanel { + /** + * Show popup panel. + * @param parentKeyboardView the parent KeyboardView that has the parent key. + * @param parentKey the parent key that is the source of this popup panel + * @param tracker the pointer tracker that pressesd the parent key + * @param keyPreviewY the Y-coordinate of key preview + * @param window PopupWindow to be used to show this popup panel + */ + public void showPanel(KeyboardView parentKeyboardView, Key parentKey, + PointerTracker tracker, int keyPreviewY, PopupWindow window); + + /** + * Check if the pointer is in siding key input mode. + * @return true if the pointer is sliding key input mode. + */ + public boolean isInSlidingKeyInput(); + + /** + * The motion event handler. + * @param me the MotionEvent to be processed. + * @return true if the motion event is processed and should be consumed. + */ + public boolean onTouchEvent(MotionEvent me); +} diff --git a/java/src/com/android/inputmethod/latin/CandidateView.java b/java/src/com/android/inputmethod/latin/CandidateView.java index 6fb80adf0..abdf30e6b 100644 --- a/java/src/com/android/inputmethod/latin/CandidateView.java +++ b/java/src/com/android/inputmethod/latin/CandidateView.java @@ -150,7 +150,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo tv.setOnLongClickListener(this); ImageView divider = (ImageView)v.findViewById(R.id.candidate_divider); // Do not display divider of first candidate. - divider.setVisibility(i == 0 ? GONE : VISIBLE); + divider.setVisibility(i == 0 ? INVISIBLE : VISIBLE); mWords.add(v); } @@ -179,7 +179,7 @@ public class CandidateView extends LinearLayout implements OnClickListener, OnLo private void updateSuggestions() { final SuggestedWords suggestions = mSuggestions; clear(); - final int count = suggestions.size(); + final int count = Math.min(mWords.size(), suggestions.size()); for (int i = 0; i < count; i++) { CharSequence word = suggestions.getWord(i); if (word == null) continue; diff --git a/java/src/com/android/inputmethod/latin/ContactsDictionary.java b/java/src/com/android/inputmethod/latin/ContactsDictionary.java index bdb68cac7..b057cf4e3 100644 --- a/java/src/com/android/inputmethod/latin/ContactsDictionary.java +++ b/java/src/com/android/inputmethod/latin/ContactsDictionary.java @@ -26,6 +26,8 @@ import android.provider.ContactsContract.Contacts; import android.text.TextUtils; import android.util.Log; +import com.android.inputmethod.keyboard.Keyboard; + public class ContactsDictionary extends ExpandableDictionary { private static final String[] PROJECTION = { @@ -123,8 +125,9 @@ public class ContactsDictionary extends ExpandableDictionary { for (j = i + 1; j < len; j++) { char c = name.charAt(j); - if (!(c == '-' || c == '\'' || - Character.isLetter(c))) { + if (!(c == Keyboard.CODE_DASH + || c == Keyboard.CODE_SINGLE_QUOTE + || Character.isLetter(c))) { break; } } diff --git a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java index be2c6b21b..26391fe46 100644 --- a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java +++ b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java @@ -19,6 +19,8 @@ package com.android.inputmethod.latin; import android.content.Context; import android.os.AsyncTask; +import com.android.inputmethod.keyboard.Keyboard; + import java.util.LinkedList; /** @@ -41,8 +43,6 @@ public class ExpandableDictionary extends Dictionary { private int mMaxDepth; private int mInputLength; - private static final char QUOTE = '\''; - private boolean mRequiresReload; private boolean mUpdatingDictionary; @@ -304,7 +304,8 @@ public class ExpandableDictionary extends Dictionary { getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex, skipPos, callback); } - } else if ((c == QUOTE && currentChars[0] != QUOTE) || depth == skipPos) { + } else if ((c == Keyboard.CODE_SINGLE_QUOTE + && currentChars[0] != Keyboard.CODE_SINGLE_QUOTE) || depth == skipPos) { // Skip the ' and continue deeper word[depth] = c; if (children != null) { diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 105ec5a62..375529f25 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -68,13 +68,11 @@ import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; -import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import android.widget.LinearLayout; import java.io.FileDescriptor; import java.io.PrintWriter; -import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; @@ -110,9 +108,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar */ public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey"; - private static final int DELAY_UPDATE_SUGGESTIONS = 180; - private static final int DELAY_UPDATE_OLD_SUGGESTIONS = 300; - private static final int DELAY_UPDATE_SHIFT_STATE = 100; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; // How many continuous deletes at which to start deleting at a higher speed. @@ -155,14 +150,16 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar private KeyboardSwitcher mKeyboardSwitcher; private SubtypeSwitcher mSubtypeSwitcher; private VoiceProxy mVoiceProxy; + private Recorrection mRecorrection; private UserDictionary mUserDictionary; private UserBigramDictionary mUserBigramDictionary; private ContactsDictionary mContactsDictionary; private AutoDictionary mAutoDictionary; + // TODO: Create an inner class to group options and pseudo-options to improve readability. // These variables are initialized according to the {@link EditorInfo#inputType}. - private boolean mAutoSpace; + private boolean mShouldInsertMagicSpace; private boolean mInputTypeNoAutoCorrect; private boolean mIsSettingsSuggestionStripOn; private boolean mApplicationSpecifiedCompletionOn; @@ -174,9 +171,10 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar private CharSequence mBestWord; private boolean mHasUncommittedTypedChars; private boolean mHasDictionary; - private boolean mJustAddedAutoSpace; + // Magic space: a space that should disappear on space/apostrophe insertion, move after the + // punctuation on punctuation insertion, and become a real space on alpha char insertion. + private boolean mJustAddedMagicSpace; // This indicates whether the last char is a magic space. private boolean mAutoCorrectEnabled; - private boolean mRecorrectionEnabled; // Suggestion: use bigrams to adjust scores of suggestions obtained from unigram dictionary private boolean mBigramSuggestionEnabled; // Prediction: use bigrams to predict the next word when there is no input for it yet @@ -190,6 +188,9 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar private boolean mConfigEnableShowSubtypeSettings; private boolean mConfigSwipeDownDismissKeyboardEnabled; private int mConfigDelayBeforeFadeoutLanguageOnSpacebar; + private int mConfigDelayUpdateSuggestions; + private int mConfigDelayUpdateOldSuggestions; + private int mConfigDelayUpdateShiftState; private int mConfigDurationOfFadeoutLanguageOnSpacebar; private float mConfigFinalFadeoutFactorOfLanguageOnSpacebar; private long mConfigDoubleSpacesTurnIntoPeriodTimeout; @@ -213,7 +214,8 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar private boolean mSilentMode; /* package */ String mWordSeparators; - private String mSentenceSeparators; + private String mMagicSpaceStrippers; + private String mMagicSpaceSwappers; private String mSuggestPuncs; // TODO: Move this flag to VoiceProxy private boolean mConfigurationChanging; @@ -225,39 +227,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar // Keeps track of most recently inserted text (multi-character key) for reverting private CharSequence mEnteredText; - private final ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>(); - - public class WordAlternatives { - private final CharSequence mChosenWord; - private final WordComposer mWordComposer; - - public WordAlternatives(CharSequence chosenWord, WordComposer wordComposer) { - mChosenWord = chosenWord; - mWordComposer = wordComposer; - } - - public CharSequence getChosenWord() { - return mChosenWord; - } - - public CharSequence getOriginalWord() { - return mWordComposer.getTypedWord(); - } - - public SuggestedWords.Builder getAlternatives() { - return getTypedSuggestions(mWordComposer); - } - - @Override - public int hashCode() { - return mChosenWord.hashCode(); - } - - @Override - public boolean equals(Object o) { - return o instanceof CharSequence && TextUtils.equals(mChosenWord, (CharSequence)o); - } - } public final UIHandler mHandler = new UIHandler(); @@ -280,7 +249,9 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar updateSuggestions(); break; case MSG_UPDATE_OLD_SUGGESTIONS: - setOldSuggestions(); + mRecorrection.setRecorrectionSuggestions(mVoiceProxy, mCandidateView, mSuggest, + mKeyboardSwitcher, mWord, mHasUncommittedTypedChars, mLastSelectionStart, + mLastSelectionEnd, mWordSeparators); break; case MSG_UPDATE_SHIFT_STATE: switcher.updateShiftState(); @@ -310,7 +281,8 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar public void postUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); - sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS), DELAY_UPDATE_SUGGESTIONS); + sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS), + mConfigDelayUpdateSuggestions); } public void cancelUpdateSuggestions() { @@ -324,7 +296,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar public void postUpdateOldSuggestions() { removeMessages(MSG_UPDATE_OLD_SUGGESTIONS); sendMessageDelayed(obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), - DELAY_UPDATE_OLD_SUGGESTIONS); + mConfigDelayUpdateOldSuggestions); } public void cancelUpdateOldSuggestions() { @@ -333,7 +305,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar public void postUpdateShiftKeyState() { removeMessages(MSG_UPDATE_SHIFT_STATE); - sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), DELAY_UPDATE_SHIFT_STATE); + sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mConfigDelayUpdateShiftState); } public void cancelUpdateShiftState() { @@ -342,7 +314,8 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar public void postUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); - sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS), DELAY_UPDATE_SUGGESTIONS); + sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS), + mConfigDelayUpdateSuggestions); } public void cancelUpdateBigramPredictions() { @@ -398,6 +371,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar SubtypeSwitcher.init(this, prefs); KeyboardSwitcher.init(this, prefs); AccessibilityUtils.init(this, prefs); + Recorrection.init(this, prefs); super.onCreate(); @@ -406,25 +380,21 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mAccessibilityUtils = AccessibilityUtils.getInstance(); + mRecorrection = Recorrection.getInstance(); final Resources res = getResources(); mResources = res; - // If the option should not be shown, do not read the recorrection preference - // but always use the default setting defined in the resources. - if (res.getBoolean(R.bool.config_enable_show_recorrection_option)) { - mRecorrectionEnabled = prefs.getBoolean(Settings.PREF_RECORRECTION_ENABLED, - res.getBoolean(R.bool.config_default_recorrection_enabled)); - } else { - mRecorrectionEnabled = res.getBoolean(R.bool.config_default_recorrection_enabled); - } - mConfigEnableShowSubtypeSettings = res.getBoolean( R.bool.config_enable_show_subtype_settings); mConfigSwipeDownDismissKeyboardEnabled = res.getBoolean( R.bool.config_swipe_down_dismiss_keyboard_enabled); mConfigDelayBeforeFadeoutLanguageOnSpacebar = res.getInteger( R.integer.config_delay_before_fadeout_language_on_spacebar); + mConfigDelayUpdateSuggestions = res.getInteger(R.integer.config_delay_update_suggestions); + mConfigDelayUpdateOldSuggestions = res.getInteger( + R.integer.config_delay_update_old_suggestions); + mConfigDelayUpdateShiftState = res.getInteger(R.integer.config_delay_update_shift_state); mConfigDurationOfFadeoutLanguageOnSpacebar = res.getInteger( R.integer.config_duration_of_fadeout_language_on_spacebar); mConfigFinalFadeoutFactorOfLanguageOnSpacebar = res.getInteger( @@ -496,8 +466,14 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mSuggest.setUserBigramDictionary(mUserBigramDictionary); updateCorrectionMode(); - mWordSeparators = res.getString(R.string.word_separators); - mSentenceSeparators = res.getString(R.string.sentence_separators); + mMagicSpaceStrippers = res.getString(R.string.magic_space_stripping_symbols); + mMagicSpaceSwappers = res.getString(R.string.magic_space_swapping_symbols); + String wordSeparators = mMagicSpaceStrippers + mMagicSpaceSwappers + + res.getString(R.string.magic_space_promoting_symbols); + final String notWordSeparators = res.getString(R.string.non_word_separator_symbols); + for (int i = notWordSeparators.length() - 1; i >= 0; --i) + wordSeparators = wordSeparators.replace(notWordSeparators.substring(i, i + 1), ""); + mWordSeparators = wordSeparators; Utils.setSystemLocale(res, savedLocale); } @@ -593,7 +569,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mComposing.setLength(0); mHasUncommittedTypedChars = false; mDeleteCount = 0; - mJustAddedAutoSpace = false; + mJustAddedMagicSpace = false; loadSettings(attribute); if (mSubtypeSwitcher.isKeyboardMode()) { @@ -615,7 +591,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar inputView.setProximityCorrectionEnabled(true); inputView.setAccessibilityEnabled(accessibilityEnabled); // If we just entered a text field, maybe it has some old text that requires correction - checkRecorrectionOnStart(); + mRecorrection.checkRecorrectionOnStart(); inputView.setForeground(true); voiceIme.onStartInputView(inputView.getWindowToken()); @@ -628,7 +604,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar return; final int inputType = attribute.inputType; final int variation = inputType & InputType.TYPE_MASK_VARIATION; - mAutoSpace = false; + mShouldInsertMagicSpace = false; mInputTypeNoAutoCorrect = false; mIsSettingsSuggestionStripOn = false; mApplicationSpecifiedCompletionOn = false; @@ -643,9 +619,9 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar } if (InputTypeCompatUtils.isEmailVariation(variation) || variation == InputType.TYPE_TEXT_VARIATION_PERSON_NAME) { - mAutoSpace = false; + mShouldInsertMagicSpace = false; } else { - mAutoSpace = true; + mShouldInsertMagicSpace = true; } if (InputTypeCompatUtils.isEmailVariation(variation)) { mIsSettingsSuggestionStripOn = false; @@ -678,34 +654,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar } } - private void checkRecorrectionOnStart() { - if (!mRecorrectionEnabled) return; - - final InputConnection ic = getCurrentInputConnection(); - if (ic == null) return; - // There could be a pending composing span. Clean it up first. - ic.finishComposingText(); - - if (isShowingSuggestionsStrip() && isSuggestionsRequested()) { - // First get the cursor position. This is required by setOldSuggestions(), so that - // it can pass the correct range to setComposingRegion(). At this point, we don't - // have valid values for mLastSelectionStart/End because onUpdateSelection() has - // not been called yet. - ExtractedTextRequest etr = new ExtractedTextRequest(); - etr.token = 0; // anything is fine here - ExtractedText et = ic.getExtractedText(etr, 0); - if (et == null) return; - - mLastSelectionStart = et.startOffset + et.selectionStart; - mLastSelectionEnd = et.startOffset + et.selectionEnd; - - // Then look for possible corrections in a delayed fashion - if (!TextUtils.isEmpty(et.text) && isCursorTouchingWord()) { - mHandler.postUpdateOldSuggestions(); - } - } - } - @Override public void onFinishInput() { super.onFinishInput(); @@ -769,7 +717,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar // If the composing span has been cleared, save the typed word in the history for // recorrection before we reset the candidate strip. Then, we'll be able to show // suggestions for recorrection right away. - saveWordInHistory(mComposing); + mRecorrection.saveWordInHistory(mWord, mComposing); } mComposing.setLength(0); mHasUncommittedTypedChars = false; @@ -789,7 +737,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar if (TextEntryState.isAcceptedDefault() || TextEntryState.isSpaceAfterPicked()) { if (TextEntryState.isAcceptedDefault()) TextEntryState.reset(); - mJustAddedAutoSpace = false; // The user moved the cursor. + mJustAddedMagicSpace = false; // The user moved the cursor. } } mJustAccepted = false; @@ -799,34 +747,15 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mLastSelectionStart = newSelStart; mLastSelectionEnd = newSelEnd; - if (mRecorrectionEnabled && isShowingSuggestionsStrip()) { - // Don't look for corrections if the keyboard is not visible - if (mKeyboardSwitcher.isInputViewShown()) { - // Check if we should go in or out of correction mode. - if (isSuggestionsRequested() - && (candidatesStart == candidatesEnd || newSelStart != oldSelStart - || TextEntryState.isRecorrecting()) - && (newSelStart < newSelEnd - 1 || !mHasUncommittedTypedChars)) { - if (isCursorTouchingWord() || mLastSelectionStart < mLastSelectionEnd) { - mHandler.cancelUpdateBigramPredictions(); - mHandler.postUpdateOldSuggestions(); - } else { - abortRecorrection(false); - // If showing the "touch again to save" hint, do not replace it. Else, - // show the bigrams if we are at the end of the text, punctuation otherwise. - if (mCandidateView != null - && !mCandidateView.isShowingAddToDictionaryHint()) { - InputConnection ic = getCurrentInputConnection(); - if (null == ic || !TextUtils.isEmpty(ic.getTextAfterCursor(1, 0))) { - if (!isShowingPunctuationList()) setPunctuationSuggestions(); - } else { - mHandler.postUpdateBigramPredictions(); - } - } - } - } - } - } + mRecorrection.updateRecorrectionSelection(mKeyboardSwitcher, + mCandidateView, candidatesStart, candidatesEnd, newSelStart, + newSelEnd, oldSelStart, mLastSelectionStart, + mLastSelectionEnd, mHasUncommittedTypedChars); + } + + public void setLastSelection(int start, int end) { + mLastSelectionStart = start; + mLastSelectionEnd = end; } /** @@ -839,7 +768,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar */ @Override public void onExtractedTextClicked() { - if (mRecorrectionEnabled && isSuggestionsRequested()) return; + if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return; super.onExtractedTextClicked(); } @@ -855,7 +784,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar */ @Override public void onExtractedCursorMovement(int dx, int dy) { - if (mRecorrectionEnabled && isSuggestionsRequested()) return; + if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return; super.onExtractedCursorMovement(dx, dy); } @@ -871,7 +800,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mOptionsDialog = null; } mVoiceProxy.hideVoiceWindow(mConfigurationChanging); - mWordHistory.clear(); + mRecorrection.clearWordsInHistory(); super.hideWindow(); } @@ -1030,39 +959,22 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar return false; } - private void swapPunctuationAndSpace() { + private void swapSwapperAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); + // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called. if (lastTwo != null && lastTwo.length() == 2 - && lastTwo.charAt(0) == Keyboard.CODE_SPACE - && isSentenceSeparator(lastTwo.charAt(1))) { + && lastTwo.charAt(0) == Keyboard.CODE_SPACE) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); - mJustAddedAutoSpace = true; - } - } - - private void reswapPeriodAndSpace() { - final InputConnection ic = getCurrentInputConnection(); - if (ic == null) return; - CharSequence lastThree = ic.getTextBeforeCursor(3, 0); - if (lastThree != null && lastThree.length() == 3 - && lastThree.charAt(0) == Keyboard.CODE_PERIOD - && lastThree.charAt(1) == Keyboard.CODE_SPACE - && lastThree.charAt(2) == Keyboard.CODE_PERIOD) { - ic.beginBatchEdit(); - ic.deleteSurroundingText(3, 0); - ic.commitText(" ..", 1); - ic.endBatchEdit(); - mKeyboardSwitcher.updateShiftState(); } } - private void doubleSpace() { + private void maybeDoubleSpace() { if (mCorrectionMode == Suggest.CORRECTION_NONE) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; @@ -1078,7 +990,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar ic.commitText(". ", 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); - mJustAddedAutoSpace = true; } else { mHandler.startDoubleSpacesTimer(); } @@ -1205,9 +1116,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar handleTab(); break; default: - if (primaryCode != Keyboard.CODE_ENTER) { - mJustAddedAutoSpace = false; - } if (isWordSeparator(primaryCode)) { handleSeparator(primaryCode, x, y); } else { @@ -1224,7 +1132,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mVoiceProxy.commitVoiceInput(); InputConnection ic = getCurrentInputConnection(); if (ic == null) return; - abortRecorrection(false); + mRecorrection.abortRecorrection(false); ic.beginBatchEdit(); commitTyped(ic); maybeRemovePreviousPeriod(text); @@ -1232,7 +1140,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); mKeyboardSwitcher.onKey(Keyboard.CODE_DUMMY); - mJustAddedAutoSpace = false; + mJustAddedMagicSpace = false; mEnteredText = text; } @@ -1330,20 +1238,15 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar } } - private void abortRecorrection(boolean force) { - if (force || TextEntryState.isRecorrecting()) { - TextEntryState.onAbortRecorrection(); - setCandidatesViewShown(isCandidateStripVisible()); - getCurrentInputConnection().finishComposingText(); - clearSuggestions(); - } - } - private void handleCharacter(int primaryCode, int[] keyCodes, int x, int y) { mVoiceProxy.handleCharacter(); - if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isRecorrecting()) { - abortRecorrection(false); + if (mJustAddedMagicSpace && isMagicSpaceStripper(primaryCode)) { + removeTrailingSpace(); + } + + if (mLastSelectionStart == mLastSelectionEnd) { + mRecorrection.abortRecorrection(false); } int code = primaryCode; @@ -1351,7 +1254,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar if (!mHasUncommittedTypedChars) { mHasUncommittedTypedChars = true; mComposing.setLength(0); - saveWordInHistory(mBestWord); + mRecorrection.saveWordInHistory(mWord, mBestWord); mWord.reset(); clearSuggestions(); } @@ -1394,6 +1297,12 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar } else { sendKeyChar((char)code); } + if (mJustAddedMagicSpace && isMagicSpaceSwapper(primaryCode)) { + swapSwapperAndSpace(); + } else { + mJustAddedMagicSpace = false; + } + switcher.updateShiftState(); if (LatinIME.PERF_DEBUG) measureCps(); TextEntryState.typedCharacter((char) code, isWordSeparator(code), x, y); @@ -1413,43 +1322,39 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); - abortRecorrection(false); + mRecorrection.abortRecorrection(false); } if (mHasUncommittedTypedChars) { // In certain languages where single quote is a separator, it's better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the elision // requires the last vowel to be removed. - if (mAutoCorrectOn && primaryCode != '\'') { + if (mAutoCorrectOn && primaryCode != Keyboard.CODE_SINGLE_QUOTE) { pickedDefault = pickDefaultSuggestion(primaryCode); - // Picked the suggestion by the space key. We consider this - // as "added an auto space". - if (primaryCode == Keyboard.CODE_SPACE) { - mJustAddedAutoSpace = true; - } } else { commitTyped(ic); } } - if (mJustAddedAutoSpace && primaryCode == Keyboard.CODE_ENTER) { - removeTrailingSpace(); - mJustAddedAutoSpace = false; + + if (mJustAddedMagicSpace) { + if (isMagicSpaceSwapper(primaryCode)) { + sendKeyChar((char)primaryCode); + swapSwapperAndSpace(); + } else { + if (isMagicSpaceStripper(primaryCode)) removeTrailingSpace(); + sendKeyChar((char)primaryCode); + mJustAddedMagicSpace = false; + } + } else { + sendKeyChar((char)primaryCode); } - sendKeyChar((char)primaryCode); - // Handle the case of ". ." -> " .." with auto-space if necessary - // before changing the TextEntryState. - if (TextEntryState.isPunctuationAfterAccepted() && primaryCode == Keyboard.CODE_PERIOD) { - reswapPeriodAndSpace(); + if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) { + maybeDoubleSpace(); } TextEntryState.typedCharacter((char) primaryCode, true, x, y); - if (TextEntryState.isPunctuationAfterAccepted() && primaryCode != Keyboard.CODE_ENTER) { - swapPunctuationAndSpace(); - } else if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) { - doubleSpace(); - } if (pickedDefault) { CharSequence typedWord = mWord.getTypedWord(); TextEntryState.backToAcceptedDefault(typedWord); @@ -1486,38 +1391,22 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar inputView.closing(); } - private void saveWordInHistory(CharSequence result) { - if (mWord.size() <= 1) { - return; - } - // Skip if result is null. It happens in some edge case. - if (TextUtils.isEmpty(result)) { - return; - } - - // Make a copy of the CharSequence, since it is/could be a mutable CharSequence - final String resultCopy = result.toString(); - WordAlternatives entry = new WordAlternatives(resultCopy, - new WordComposer(mWord)); - mWordHistory.add(entry); - } - - private boolean isSuggestionsRequested() { + public boolean isSuggestionsRequested() { return mIsSettingsSuggestionStripOn && (mCorrectionMode > 0 || isShowingSuggestionsStrip()); } - private boolean isShowingPunctuationList() { + public boolean isShowingPunctuationList() { return mSuggestPuncList == mCandidateView.getSuggestions(); } - private boolean isShowingSuggestionsStrip() { + public boolean isShowingSuggestionsStrip() { return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE) || (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE && mOrientation == Configuration.ORIENTATION_PORTRAIT); } - private boolean isCandidateStripVisible() { + public boolean isCandidateStripVisible() { if (mCandidateView == null) return false; if (mCandidateView.isShowingAddToDictionaryHint() || TextEntryState.isRecorrecting()) @@ -1579,16 +1468,6 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar showSuggestions(mWord); } - private SuggestedWords.Builder getTypedSuggestions(WordComposer word) { - return mSuggest.getSuggestedWordBuilder(mKeyboardSwitcher.getInputView(), word, null); - } - - private void showCorrections(WordAlternatives alternatives) { - SuggestedWords.Builder builder = alternatives.getAlternatives(); - builder.setTypedWordValid(false).setHasMinimalSuggestion(false); - showSuggestions(builder.build(), alternatives.getOriginalWord()); - } - private void showSuggestions(WordComposer word) { // TODO: May need a better way of retrieving previous word CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(), @@ -1627,7 +1506,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar showSuggestions(builder.build(), typedWord); } - private void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) { + public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) { setSuggestions(suggestedWords); if (suggestedWords.size() > 0) { if (Utils.shouldBlockedBySafetyNetForAutoCorrection(suggestedWords, mSuggest)) { @@ -1694,10 +1573,17 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); + // Find out whether the previous character is a space. If it is, as a special case + // for punctuation entered through the suggestion strip, it should be considered + // a magic space even if it was a normal space. This is meant to help in case the user + // pressed space on purpose of displaying the suggestion strip punctuation. final char primaryCode = suggestion.charAt(0); + final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0); + if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true; onCodeInput(primaryCode, new int[] { primaryCode }, KeyboardActionListener.NOT_A_TOUCH_COORDINATE, KeyboardActionListener.NOT_A_TOUCH_COORDINATE); + mJustAddedMagicSpace = false; if (ic != null) { ic.endBatchEdit(); } @@ -1720,9 +1606,8 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar index, suggestions.mWords); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space - if (mAutoSpace && !recorrecting) { - sendSpace(); - mJustAddedAutoSpace = true; + if (mShouldInsertMagicSpace && !recorrecting) { + sendMagicSpace(); } // We should show the hint if the user pressed the first entry AND either: @@ -1776,91 +1661,11 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar mVoiceProxy.rememberReplacedWord(suggestion, mWordSeparators); ic.commitText(suggestion, 1); } - saveWordInHistory(suggestion); + mRecorrection.saveWordInHistory(mWord, suggestion); mHasUncommittedTypedChars = false; mCommittedLength = suggestion.length(); } - /** - * Tries to apply any typed alternatives for the word if we have any cached alternatives, - * otherwise tries to find new corrections and completions for the word. - * @param touching The word that the cursor is touching, with position information - * @return true if an alternative was found, false otherwise. - */ - private boolean applyTypedAlternatives(EditingUtils.SelectedWord touching) { - // If we didn't find a match, search for result in typed word history - WordComposer foundWord = null; - WordAlternatives alternatives = null; - // Search old suggestions to suggest re-corrected suggestions. - for (WordAlternatives entry : mWordHistory) { - if (TextUtils.equals(entry.getChosenWord(), touching.mWord)) { - foundWord = entry.mWordComposer; - alternatives = entry; - break; - } - } - // If we didn't find a match, at least suggest corrections as re-corrected suggestions. - if (foundWord == null - && (AutoCorrection.isValidWord( - mSuggest.getUnigramDictionaries(), touching.mWord, true))) { - foundWord = new WordComposer(); - for (int i = 0; i < touching.mWord.length(); i++) { - foundWord.add(touching.mWord.charAt(i), new int[] { - touching.mWord.charAt(i) - }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); - } - foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.mWord.charAt(0))); - } - // Found a match, show suggestions - if (foundWord != null || alternatives != null) { - if (alternatives == null) { - alternatives = new WordAlternatives(touching.mWord, foundWord); - } - showCorrections(alternatives); - if (foundWord != null) { - mWord = new WordComposer(foundWord); - } else { - mWord.reset(); - } - return true; - } - return false; - } - - private void setOldSuggestions() { - if (!InputConnectionCompatUtils.RECORRECTION_SUPPORTED) return; - mVoiceProxy.setShowingVoiceSuggestions(false); - if (mCandidateView != null && mCandidateView.isShowingAddToDictionaryHint()) { - return; - } - InputConnection ic = getCurrentInputConnection(); - if (ic == null) return; - if (!mHasUncommittedTypedChars) { - // Extract the selected or touching text - EditingUtils.SelectedWord touching = EditingUtils.getWordAtCursorOrSelection(ic, - mLastSelectionStart, mLastSelectionEnd, mWordSeparators); - - if (touching != null && touching.mWord.length() > 1) { - ic.beginBatchEdit(); - - if (!mVoiceProxy.applyVoiceAlternatives(touching) - && !applyTypedAlternatives(touching)) { - abortRecorrection(true); - } else { - TextEntryState.selectedForRecorrection(); - InputConnectionCompatUtils.underlineWord(ic, touching); - } - - ic.endBatchEdit(); - } else { - abortRecorrection(true); - setPunctuationSuggestions(); // Show the punctuation suggestions list - } - } else { - abortRecorrection(true); - } - } - private static final WordComposer sEmptyWordComposer = new WordComposer(); private void updateBigramPredictions() { if (mSuggest == null || !isSuggestionsRequested()) @@ -1885,7 +1690,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar } } - private void setPunctuationSuggestions() { + public void setPunctuationSuggestions() { setSuggestions(mSuggestPuncList); setCandidatesViewShown(isCandidateStripVisible()); } @@ -1925,15 +1730,18 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar } if (mUserBigramDictionary != null) { + // We don't want to register as bigrams words separated by a separator. + // For example "I will, and you too" : we don't want the pair ("will" "and") to be + // a bigram. CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(), - mSentenceSeparators); + mWordSeparators); if (!TextUtils.isEmpty(prevWord)) { mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString()); } } } - private boolean isCursorTouchingWord() { + public boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); @@ -2001,12 +1809,17 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar return separators.contains(String.valueOf((char)code)); } - private boolean isSentenceSeparator(int code) { - return mSentenceSeparators.contains(String.valueOf((char)code)); + private boolean isMagicSpaceStripper(int code) { + return mMagicSpaceStrippers.contains(String.valueOf((char)code)); + } + + private boolean isMagicSpaceSwapper(int code) { + return mMagicSpaceSwappers.contains(String.valueOf((char)code)); } - private void sendSpace() { + private void sendMagicSpace() { sendKeyChar((char)Keyboard.CODE_SPACE); + mJustAddedMagicSpace = true; mKeyboardSwitcher.updateShiftState(); } @@ -2402,7 +2215,7 @@ public class LatinIME extends InputMethodServiceCompatWrapper implements Keyboar p.println(" mCorrectionMode=" + mCorrectionMode); p.println(" mHasUncommittedTypedChars=" + mHasUncommittedTypedChars); p.println(" mAutoCorrectOn=" + mAutoCorrectOn); - p.println(" mAutoSpace=" + mAutoSpace); + p.println(" mShouldInsertMagicSpace=" + mShouldInsertMagicSpace); p.println(" mApplicationSpecifiedCompletionOn=" + mApplicationSpecifiedCompletionOn); p.println(" TextEntryState.state=" + TextEntryState.getState()); p.println(" mSoundOn=" + mSoundOn); diff --git a/java/src/com/android/inputmethod/latin/Recorrection.java b/java/src/com/android/inputmethod/latin/Recorrection.java new file mode 100644 index 000000000..3fa6292ba --- /dev/null +++ b/java/src/com/android/inputmethod/latin/Recorrection.java @@ -0,0 +1,255 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.android.inputmethod.latin; + +import com.android.inputmethod.compat.InputConnectionCompatUtils; +import com.android.inputmethod.deprecated.VoiceProxy; +import com.android.inputmethod.keyboard.KeyboardSwitcher; + +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.text.TextUtils; +import android.view.inputmethod.ExtractedText; +import android.view.inputmethod.ExtractedTextRequest; +import android.view.inputmethod.InputConnection; + +import java.util.ArrayList; + +/** + * Manager of re-correction functionalities + */ +public class Recorrection { + private static final Recorrection sInstance = new Recorrection(); + + private LatinIME mService; + private boolean mRecorrectionEnabled = false; + private final ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>(); + + public static Recorrection getInstance() { + return sInstance; + } + + public static void init(LatinIME context, SharedPreferences prefs) { + if (context == null || prefs == null) { + return; + } + sInstance.initInternal(context, prefs); + } + + private Recorrection() { + } + + public boolean isRecorrectionEnabled() { + return mRecorrectionEnabled; + } + + private void initInternal(LatinIME context, SharedPreferences prefs) { + final Resources res = context.getResources(); + // If the option should not be shown, do not read the re-correction preference + // but always use the default setting defined in the resources. + if (res.getBoolean(R.bool.config_enable_show_recorrection_option)) { + mRecorrectionEnabled = prefs.getBoolean(Settings.PREF_RECORRECTION_ENABLED, + res.getBoolean(R.bool.config_default_recorrection_enabled)); + } else { + mRecorrectionEnabled = res.getBoolean(R.bool.config_default_recorrection_enabled); + } + mService = context; + } + + public void checkRecorrectionOnStart() { + if (!mRecorrectionEnabled) return; + + final InputConnection ic = mService.getCurrentInputConnection(); + if (ic == null) return; + // There could be a pending composing span. Clean it up first. + ic.finishComposingText(); + + if (mService.isShowingSuggestionsStrip() && mService.isSuggestionsRequested()) { + // First get the cursor position. This is required by setOldSuggestions(), so that + // it can pass the correct range to setComposingRegion(). At this point, we don't + // have valid values for mLastSelectionStart/End because onUpdateSelection() has + // not been called yet. + ExtractedTextRequest etr = new ExtractedTextRequest(); + etr.token = 0; // anything is fine here + ExtractedText et = ic.getExtractedText(etr, 0); + if (et == null) return; + mService.setLastSelection( + et.startOffset + et.selectionStart, et.startOffset + et.selectionEnd); + + // Then look for possible corrections in a delayed fashion + if (!TextUtils.isEmpty(et.text) && mService.isCursorTouchingWord()) { + mService.mHandler.postUpdateOldSuggestions(); + } + } + } + + public void updateRecorrectionSelection(KeyboardSwitcher keyboardSwitcher, + CandidateView candidateView, int candidatesStart, int candidatesEnd, int newSelStart, + int newSelEnd, int oldSelStart, int lastSelectionStart, + int lastSelectionEnd, boolean hasUncommittedTypedChars) { + if (mRecorrectionEnabled && mService.isShowingSuggestionsStrip()) { + // Don't look for corrections if the keyboard is not visible + if (keyboardSwitcher.isInputViewShown()) { + // Check if we should go in or out of correction mode. + if (mService.isSuggestionsRequested() + && (candidatesStart == candidatesEnd || newSelStart != oldSelStart + || TextEntryState.isRecorrecting()) + && (newSelStart < newSelEnd - 1 || !hasUncommittedTypedChars)) { + if (mService.isCursorTouchingWord() || lastSelectionStart < lastSelectionEnd) { + mService.mHandler.cancelUpdateBigramPredictions(); + mService.mHandler.postUpdateOldSuggestions(); + } else { + abortRecorrection(false); + // If showing the "touch again to save" hint, do not replace it. Else, + // show the bigrams if we are at the end of the text, punctuation otherwise. + if (candidateView != null + && !candidateView.isShowingAddToDictionaryHint()) { + InputConnection ic = mService.getCurrentInputConnection(); + if (null == ic || !TextUtils.isEmpty(ic.getTextAfterCursor(1, 0))) { + if (!mService.isShowingPunctuationList()) { + mService.setPunctuationSuggestions(); + } + } else { + mService.mHandler.postUpdateBigramPredictions(); + } + } + } + } + } + } + } + + public void saveWordInHistory(WordComposer word, CharSequence result) { + if (word.size() <= 1) { + return; + } + // Skip if result is null. It happens in some edge case. + if (TextUtils.isEmpty(result)) { + return; + } + + // Make a copy of the CharSequence, since it is/could be a mutable CharSequence + final String resultCopy = result.toString(); + WordAlternatives entry = new WordAlternatives(resultCopy, new WordComposer(word)); + mWordHistory.add(entry); + } + + public void clearWordsInHistory() { + mWordHistory.clear(); + } + + /** + * Tries to apply any typed alternatives for the word if we have any cached alternatives, + * otherwise tries to find new corrections and completions for the word. + * @param touching The word that the cursor is touching, with position information + * @return true if an alternative was found, false otherwise. + */ + public boolean applyTypedAlternatives(WordComposer word, Suggest suggest, + KeyboardSwitcher keyboardSwitcher, EditingUtils.SelectedWord touching) { + // If we didn't find a match, search for result in typed word history + WordComposer foundWord = null; + WordAlternatives alternatives = null; + // Search old suggestions to suggest re-corrected suggestions. + for (WordAlternatives entry : mWordHistory) { + if (TextUtils.equals(entry.getChosenWord(), touching.mWord)) { + foundWord = entry.mWordComposer; + alternatives = entry; + break; + } + } + // If we didn't find a match, at least suggest corrections as re-corrected suggestions. + if (foundWord == null + && (AutoCorrection.isValidWord(suggest.getUnigramDictionaries(), + touching.mWord, true))) { + foundWord = new WordComposer(); + for (int i = 0; i < touching.mWord.length(); i++) { + foundWord.add(touching.mWord.charAt(i), + new int[] { touching.mWord.charAt(i) }, WordComposer.NOT_A_COORDINATE, + WordComposer.NOT_A_COORDINATE); + } + foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.mWord.charAt(0))); + } + // Found a match, show suggestions + if (foundWord != null || alternatives != null) { + if (alternatives == null) { + alternatives = new WordAlternatives(touching.mWord, foundWord); + } + showRecorrections(suggest, keyboardSwitcher, alternatives); + if (foundWord != null) { + word.init(foundWord); + } else { + word.reset(); + } + return true; + } + return false; + } + + + private void showRecorrections(Suggest suggest, KeyboardSwitcher keyboardSwitcher, + WordAlternatives alternatives) { + SuggestedWords.Builder builder = alternatives.getAlternatives(suggest, keyboardSwitcher); + builder.setTypedWordValid(false).setHasMinimalSuggestion(false); + mService.showSuggestions(builder.build(), alternatives.getOriginalWord()); + } + + public void setRecorrectionSuggestions(VoiceProxy voiceProxy, CandidateView candidateView, + Suggest suggest, KeyboardSwitcher keyboardSwitcher, WordComposer word, + boolean hasUncommittedTypedChars, int lastSelectionStart, int lastSelectionEnd, + String wordSeparators) { + if (!InputConnectionCompatUtils.RECORRECTION_SUPPORTED) return; + voiceProxy.setShowingVoiceSuggestions(false); + if (candidateView != null && candidateView.isShowingAddToDictionaryHint()) { + return; + } + InputConnection ic = mService.getCurrentInputConnection(); + if (ic == null) return; + if (!hasUncommittedTypedChars) { + // Extract the selected or touching text + EditingUtils.SelectedWord touching = EditingUtils.getWordAtCursorOrSelection(ic, + lastSelectionStart, lastSelectionEnd, wordSeparators); + + if (touching != null && touching.mWord.length() > 1) { + ic.beginBatchEdit(); + + if (applyTypedAlternatives(word, suggest, keyboardSwitcher, touching) + || voiceProxy.applyVoiceAlternatives(touching)) { + TextEntryState.selectedForRecorrection(); + InputConnectionCompatUtils.underlineWord(ic, touching); + } else { + abortRecorrection(true); + } + + ic.endBatchEdit(); + } else { + abortRecorrection(true); + mService.setPunctuationSuggestions(); // Show the punctuation suggestions list + } + } else { + abortRecorrection(true); + } + } + + public void abortRecorrection(boolean force) { + if (force || TextEntryState.isRecorrecting()) { + TextEntryState.onAbortRecorrection(); + mService.setCandidatesViewShown(mService.isCandidateStripVisible()); + mService.getCurrentInputConnection().finishComposingText(); + mService.clearSuggestions(); + } + } +} diff --git a/java/src/com/android/inputmethod/latin/WordAlternatives.java b/java/src/com/android/inputmethod/latin/WordAlternatives.java new file mode 100644 index 000000000..0e9914400 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/WordAlternatives.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package com.android.inputmethod.latin; + +import com.android.inputmethod.keyboard.KeyboardSwitcher; + +import android.text.TextUtils; + +public class WordAlternatives { + public final CharSequence mChosenWord; + public final WordComposer mWordComposer; + + public WordAlternatives(CharSequence chosenWord, WordComposer wordComposer) { + mChosenWord = chosenWord; + mWordComposer = wordComposer; + } + + public CharSequence getChosenWord() { + return mChosenWord; + } + + public CharSequence getOriginalWord() { + return mWordComposer.getTypedWord(); + } + + public SuggestedWords.Builder getAlternatives( + Suggest suggest, KeyboardSwitcher keyboardSwitcher) { + return getTypedSuggestions(suggest, keyboardSwitcher, mWordComposer); + } + + @Override + public int hashCode() { + return mChosenWord.hashCode(); + } + + @Override + public boolean equals(Object o) { + return o instanceof CharSequence && TextUtils.equals(mChosenWord, (CharSequence)o); + } + + private static SuggestedWords.Builder getTypedSuggestions( + Suggest suggest, KeyboardSwitcher keyboardSwitcher, WordComposer word) { + return suggest.getSuggestedWordBuilder(keyboardSwitcher.getInputView(), word, null); + } +}
\ No newline at end of file diff --git a/java/src/com/android/inputmethod/latin/WordComposer.java b/java/src/com/android/inputmethod/latin/WordComposer.java index 02583895b..cf0592920 100644 --- a/java/src/com/android/inputmethod/latin/WordComposer.java +++ b/java/src/com/android/inputmethod/latin/WordComposer.java @@ -31,18 +31,18 @@ public class WordComposer { /** * The list of unicode values for each keystroke (including surrounding keys) */ - private final ArrayList<int[]> mCodes; + private ArrayList<int[]> mCodes; private int mTypedLength; - private final int[] mXCoordinates; - private final int[] mYCoordinates; + private int[] mXCoordinates; + private int[] mYCoordinates; /** * The word chosen from the candidate list, until it is committed. */ private String mPreferredWord; - private final StringBuilder mTypedWord; + private StringBuilder mTypedWord; private int mCapsCount; @@ -63,6 +63,10 @@ public class WordComposer { } WordComposer(WordComposer source) { + init(source); + } + + public void init(WordComposer source) { mCodes = new ArrayList<int[]>(source.mCodes); mPreferredWord = source.mPreferredWord; mTypedWord = new StringBuilder(source.mTypedWord); |