Merge "Update the Russian dictionary"
diff --git a/java/res/values/strings.xml b/java/res/values/strings.xml
index 12ffdbb..54ff23b 100644
--- a/java/res/values/strings.xml
+++ b/java/res/values/strings.xml
@@ -383,6 +383,8 @@
     <string name="read_external_dictionary_multiple_files_title">Select a dictionary file to install</string>
     <!-- Title of the confirmation dialog to install a file as an external dictionary [CHAR LIMIT=50] -->
     <string name="read_external_dictionary_confirm_install_message">Really install this file for <xliff:g id="locale_name">%s</xliff:g>?</string>
+    <!-- Title for an error dialog that contains the details of the error in the body [CHAR LIMIT=80] -->
+    <string name="error">There was an error</string>
 
     <!-- Title of the button to revert to the default value of the device in the settings dialog [CHAR LIMIT=15] -->
     <string name="button_default">Default</string>
diff --git a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
index ba9cb1f..1ce61fb 100644
--- a/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
+++ b/java/src/com/android/inputmethod/keyboard/MainKeyboardView.java
@@ -888,10 +888,9 @@
         mDrawingHandler.dismissGestureFloatingPreviewText(mGestureFloatingPreviewTextLingerTimeout);
     }
 
-    public void showGesturePreviewTrail(final PointerTracker tracker,
-            final boolean isOldestTracker) {
+    public void showGesturePreviewTrail(final PointerTracker tracker) {
         locatePreviewPlacerView();
-        mPreviewPlacerView.invalidatePointer(tracker, isOldestTracker);
+        mPreviewPlacerView.invalidatePointer(tracker);
     }
 
     // Note that this method is called from a non-UI thread.
diff --git a/java/src/com/android/inputmethod/keyboard/PointerTracker.java b/java/src/com/android/inputmethod/keyboard/PointerTracker.java
index 036372c..469076f 100644
--- a/java/src/com/android/inputmethod/keyboard/PointerTracker.java
+++ b/java/src/com/android/inputmethod/keyboard/PointerTracker.java
@@ -83,7 +83,7 @@
         public void dismissKeyPreview(PointerTracker tracker);
         public void showSlidingKeyInputPreview(PointerTracker tracker);
         public void dismissSlidingKeyInputPreview();
-        public void showGesturePreviewTrail(PointerTracker tracker, boolean isOldestTracker);
+        public void showGesturePreviewTrail(PointerTracker tracker);
     }
 
     public interface TimerProxy {
@@ -709,8 +709,8 @@
         return sPointerTrackerQueue.size();
     }
 
-    private static boolean isOldestTrackerInQueue(final PointerTracker tracker) {
-        return sPointerTrackerQueue.getOldestElement() == tracker;
+    public boolean isOldestTrackerInQueue() {
+        return sPointerTrackerQueue.getOldestElement() == this;
     }
 
     private void mayStartBatchInput(final Key key) {
@@ -732,7 +732,7 @@
             dismissAllMoreKeysPanels();
         }
         mTimerProxy.cancelLongPressTimer();
-        mDrawingProxy.showGesturePreviewTrail(this, isOldestTrackerInQueue(this));
+        mDrawingProxy.showGesturePreviewTrail(this);
     }
 
     public void updateBatchInputByTimer(final long eventTime) {
@@ -748,7 +748,7 @@
         if (mIsTrackingCanceled) {
             return;
         }
-        mDrawingProxy.showGesturePreviewTrail(this, isOldestTrackerInQueue(this));
+        mDrawingProxy.showGesturePreviewTrail(this);
     }
 
     private void updateBatchInput(final long eventTime) {
@@ -789,7 +789,7 @@
         if (mIsTrackingCanceled) {
             return;
         }
-        mDrawingProxy.showGesturePreviewTrail(this, isOldestTrackerInQueue(this));
+        mDrawingProxy.showGesturePreviewTrail(this);
     }
 
     private void cancelBatchInput() {
diff --git a/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java b/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java
index 501bde0..cf47b14 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/AbstractDrawingPreview.java
@@ -17,6 +17,7 @@
 package com.android.inputmethod.keyboard.internal;
 
 import android.graphics.Canvas;
+import android.view.View;
 
 import com.android.inputmethod.keyboard.PointerTracker;
 
@@ -25,9 +26,18 @@
  * GestureFloatingPrevewText, GestureTrail, and SlidingKeyInputPreview.
  */
 public abstract class AbstractDrawingPreview {
+    private final View mDrawingView;
     private boolean mPreviewEnabled;
 
-    public void setPreviewEnabled(final boolean enabled) {
+    protected AbstractDrawingPreview(final View drawingView) {
+        mDrawingView = drawingView;
+    }
+
+    public final View getDrawingView() {
+        return mDrawingView;
+    }
+
+    public final void setPreviewEnabled(final boolean enabled) {
         mPreviewEnabled = enabled;
     }
 
@@ -35,6 +45,14 @@
         return mPreviewEnabled;
     }
 
+    public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) {
+        // Default implementation is empty.
+    }
+
+    public void onDetachFromWindow() {
+        // Default implementation is empty.
+    }
+
     /**
      * Draws the preview
      * @param canvas The canvas where the preview is drawn.
@@ -43,7 +61,7 @@
 
     /**
      * Set the position of the preview.
-     * @param pt The new location of the preview is based on the points in PointerTracker pt.
+     * @param tracker The new location of the preview is based on the points in PointerTracker.
      */
-    public abstract void setPreviewPosition(final PointerTracker pt);
+    public abstract void setPreviewPosition(final PointerTracker tracker);
 }
diff --git a/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java b/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java
index 2c5bb59..e21f86d 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/GestureFloatingPreviewText.java
@@ -16,7 +16,6 @@
 
 package com.android.inputmethod.keyboard.internal;
 
-import android.content.Context;
 import android.content.res.TypedArray;
 import android.graphics.Canvas;
 import android.graphics.Paint;
@@ -24,6 +23,7 @@
 import android.graphics.Rect;
 import android.graphics.RectF;
 import android.text.TextUtils;
+import android.view.View;
 
 import com.android.inputmethod.keyboard.PointerTracker;
 import com.android.inputmethod.latin.CoordinateUtils;
@@ -98,16 +98,18 @@
             PREVIEW_TEXT_ARRAY_CAPACITY);
 
     protected SuggestedWords mSuggestedWords = SuggestedWords.EMPTY;
-    protected final Context mContext;
     public final int[] mLastPointerCoords = CoordinateUtils.newInstance();
 
-    public GestureFloatingPreviewText(final TypedArray typedArray, final Context context) {
+    public GestureFloatingPreviewText(final View drawingView, final TypedArray typedArray) {
+        super(drawingView);
         mParams = new GesturePreviewTextParams(typedArray);
         mHighlightedWordIndex = 0;
-        mContext = context;
     }
 
     public void setSuggetedWords(final SuggestedWords suggestedWords) {
+        if (!isPreviewEnabled()) {
+            return;
+        }
         mSuggestedWords = suggestedWords;
         updatePreviewPosition();
     }
@@ -120,8 +122,13 @@
     }
 
     @Override
-    public void setPreviewPosition(final PointerTracker pt) {
-        pt.getLastCoordinates(mLastPointerCoords);
+    public void setPreviewPosition(final PointerTracker tracker) {
+        final boolean needsToUpdateLastPointer =
+                tracker.isOldestTrackerInQueue() && isPreviewEnabled();
+        if (!needsToUpdateLastPointer) {
+            return;
+        }
+        tracker.getLastCoordinates(mLastPointerCoords);
         updatePreviewPosition();
     }
 
@@ -164,7 +171,7 @@
         final float rectWidth = textWidth + hPad * 2.0f;
         final float rectHeight = textHeight + vPad * 2.0f;
 
-        final int displayWidth = mContext.getResources().getDisplayMetrics().widthPixels;
+        final int displayWidth = getDrawingView().getResources().getDisplayMetrics().widthPixels;
         final float rectX = Math.min(
                 Math.max(CoordinateUtils.x(mLastPointerCoords) - rectWidth / 2.0f, 0.0f),
                 displayWidth - rectWidth);
@@ -176,5 +183,7 @@
         final int textY = (int)(rectY + vPad) + textHeight;
         mPreviewTextXArray.add(0, textX);
         mPreviewTextYArray.add(0, textY);
+        // TODO: Should narrow the invalidate region.
+        getDrawingView().invalidate();
     }
 }
diff --git a/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java b/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java
index d344742..83a06cb 100644
--- a/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java
+++ b/java/src/com/android/inputmethod/keyboard/internal/PreviewPlacerView.java
@@ -41,7 +41,7 @@
 public final class PreviewPlacerView extends RelativeLayout {
     private final int[] mKeyboardViewOrigin = CoordinateUtils.newInstance();
 
-    // TODO: Consolidate gesture preview trail with {@link KeyboardView}
+    // TODO: Separate gesture preview trail drawing code into separate class.
     private final SparseArray<GesturePreviewTrail> mGesturePreviewTrails =
             CollectionUtils.newSparseArray();
     private final Params mGesturePreviewTrailParams;
@@ -55,6 +55,7 @@
     private final Rect mOffscreenSrcRect = new Rect();
     private final Rect mDirtyRect = new Rect();
     private final Rect mGesturePreviewTrailBoundsRect = new Rect(); // per trail
+    // TODO: Move these AbstractDrawingPvreiew objects to MainKeyboardView.
     private final GestureFloatingPreviewText mGestureFloatingPreviewText;
     private boolean mShowSlidingKeyInputPreview;
     private final int[] mRubberBandFrom = CoordinateUtils.newInstance();
@@ -104,7 +105,7 @@
                 attrs, R.styleable.MainKeyboardView, defStyle, R.style.MainKeyboardView);
         // TODO: mGestureFloatingPreviewText could be an instance of GestureFloatingPreviewText or
         // MultiGesturePreviewText, depending on the user's choice in the settings.
-        mGestureFloatingPreviewText = new GestureFloatingPreviewText(mainKeyboardViewAttr, context);
+        mGestureFloatingPreviewText = new GestureFloatingPreviewText(this, mainKeyboardViewAttr);
         mGesturePreviewTrailParams = new Params(mainKeyboardViewAttr);
         mainKeyboardViewAttr.recycle();
 
@@ -120,11 +121,14 @@
         setLayerType(LAYER_TYPE_HARDWARE, layerPaint);
     }
 
-    public void setKeyboardViewGeometry(final int[] originCoords, final int w, final int h) {
+    public void setKeyboardViewGeometry(final int[] originCoords, final int width,
+            final int height) {
         CoordinateUtils.copy(mKeyboardViewOrigin, originCoords);
-        mOffscreenOffsetY = (int)(h * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
-        mOffscreenWidth = w;
-        mOffscreenHeight = mOffscreenOffsetY + h;
+        mGestureFloatingPreviewText.setKeyboardGeometry(originCoords, width, height);
+        mOffscreenOffsetY = (int)(
+                height * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO);
+        mOffscreenWidth = width;
+        mOffscreenHeight = mOffscreenOffsetY + height;
     }
 
     public void setGesturePreviewMode(final boolean drawsGesturePreviewTrail,
@@ -133,12 +137,8 @@
         mGestureFloatingPreviewText.setPreviewEnabled(drawsGestureFloatingPreviewText);
     }
 
-    public void invalidatePointer(final PointerTracker tracker, final boolean isOldestTracker) {
-        final boolean needsToUpdateLastPointer =
-                isOldestTracker && mGestureFloatingPreviewText.isPreviewEnabled();
-        if (needsToUpdateLastPointer) {
-            mGestureFloatingPreviewText.setPreviewPosition(tracker);
-        }
+    public void invalidatePointer(final PointerTracker tracker) {
+        mGestureFloatingPreviewText.setPreviewPosition(tracker);
 
         if (mDrawsGesturePreviewTrail) {
             GesturePreviewTrail trail;
@@ -150,10 +150,8 @@
                 }
             }
             trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime());
-        }
 
-        // TODO: Should narrow the invalidate region.
-        if (mDrawsGesturePreviewTrail || needsToUpdateLastPointer) {
+            // TODO: Should narrow the invalidate region.
             invalidate();
         }
     }
@@ -175,6 +173,8 @@
 
     @Override
     protected void onDetachedFromWindow() {
+        super.onDetachedFromWindow();
+        mGestureFloatingPreviewText.onDetachFromWindow();
         freeOffscreenBuffer();
     }
 
@@ -254,9 +254,7 @@
     }
 
     public void setGestureFloatingPreviewText(final SuggestedWords suggestedWords) {
-        if (!mGestureFloatingPreviewText.isPreviewEnabled()) return;
         mGestureFloatingPreviewText.setSuggetedWords(suggestedWords);
-        invalidate();
     }
 
     private void drawSlidingKeyInputPreview(final Canvas canvas) {
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
index 5eab292..d725b9f 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java
@@ -25,6 +25,7 @@
 import android.util.Log;
 
 import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
@@ -162,9 +163,9 @@
             InputStream inputStream = null;
             InputStream uncompressedStream = null;
             InputStream decryptedStream = null;
-            BufferedInputStream bufferedStream = null;
+            BufferedInputStream bufferedInputStream = null;
             File outputFile = null;
-            FileOutputStream outputStream = null;
+            BufferedOutputStream bufferedOutputStream = null;
             AssetFileDescriptor afd = null;
             final Uri wordListUri = wordListUriBuilder.build();
             try {
@@ -178,7 +179,6 @@
                 // Just to be sure, delete the file. This may fail silently, and return false: this
                 // is the right thing to do, as we just want to continue anyway.
                 outputFile.delete();
-                outputStream = new FileOutputStream(outputFile);
                 // Get the appropriate decryption method for this try
                 switch (mode) {
                     case COMPRESSED_CRYPTED_COMPRESSED:
@@ -206,10 +206,11 @@
                         inputStream = originalSourceStream;
                         break;
                 }
-                bufferedStream = new BufferedInputStream(inputStream);
-                checkMagicAndCopyFileTo(bufferedStream, outputStream);
-                outputStream.flush();
-                outputStream.close();
+                bufferedInputStream = new BufferedInputStream(inputStream);
+                bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
+                checkMagicAndCopyFileTo(bufferedInputStream, bufferedOutputStream);
+                bufferedOutputStream.flush();
+                bufferedOutputStream.close();
                 final File finalFile = new File(finalFileName);
                 finalFile.delete();
                 if (!outputFile.renameTo(finalFile)) {
@@ -241,12 +242,12 @@
                     if (null != inputStream) inputStream.close();
                     if (null != uncompressedStream) uncompressedStream.close();
                     if (null != decryptedStream) decryptedStream.close();
-                    if (null != bufferedStream) bufferedStream.close();
+                    if (null != bufferedInputStream) bufferedInputStream.close();
                 } catch (Exception e) {
                     Log.e(TAG, "Exception while closing a file descriptor : " + e);
                 }
                 try {
-                    if (null != outputStream) outputStream.close();
+                    if (null != bufferedOutputStream) bufferedOutputStream.close();
                 } catch (Exception e) {
                     Log.e(TAG, "Exception while closing a file : " + e);
                 }
@@ -301,9 +302,8 @@
      * @param input the stream to be copied.
      * @param output an output stream to copy the data to.
      */
-    // TODO: make output a BufferedOutputStream
-    private static void checkMagicAndCopyFileTo(final BufferedInputStream input,
-            final FileOutputStream output) throws FileNotFoundException, IOException {
+    public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
+            final BufferedOutputStream output) throws FileNotFoundException, IOException {
         // Check the magic number
         final int length = MAGIC_NUMBER_VERSION_2.length;
         final byte[] magicNumberBuffer = new byte[length];
diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
index 83dabbe..ecb63e8 100644
--- a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
+++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java
@@ -56,7 +56,7 @@
     private static final String COMMON_PREFERENCES_NAME = "LatinImeDictPrefs";
 
     // Name of the category for the main dictionary
-    private static final String MAIN_DICTIONARY_CATEGORY = "main";
+    public static final String MAIN_DICTIONARY_CATEGORY = "main";
     public static final String ID_CATEGORY_SEPARATOR = ":";
 
     // The key considered to read the version attribute in a dictionary file.
diff --git a/java/src/com/android/inputmethod/latin/DebugSettings.java b/java/src/com/android/inputmethod/latin/DebugSettings.java
index 905852a..ad52adf 100644
--- a/java/src/com/android/inputmethod/latin/DebugSettings.java
+++ b/java/src/com/android/inputmethod/latin/DebugSettings.java
@@ -77,6 +77,7 @@
                         public boolean onPreferenceClick(final Preference arg0) {
                             ExternalDictionaryGetterForDebug.chooseAndInstallDictionary(
                                     getActivity());
+                            mServiceNeedsRestart = true;
                             return true;
                         }
                     });
diff --git a/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java b/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java
index 5f91d03..03e8763 100644
--- a/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java
+++ b/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java
@@ -21,12 +21,17 @@
 import android.content.DialogInterface;
 import android.content.DialogInterface.OnClickListener;
 import android.os.Environment;
+import android.util.Log;
 
 import com.android.inputmethod.latin.makedict.BinaryDictIOUtils;
 import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader;
 import com.android.inputmethod.latin.makedict.UnsupportedFormatException;
 
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Locale;
@@ -121,13 +126,56 @@
                 }).setPositiveButton(android.R.string.ok, new OnClickListener() {
                     @Override
                     public void onClick(final DialogInterface dialog, final int which) {
-                        installFile(file, header);
+                        installFile(context, file, header);
                         dialog.dismiss();
                     }
                 }).create().show();
     }
 
-    private static void installFile(final File file, final FileHeader header) {
-        // TODO: actually install the dictionary
+    private static void installFile(final Context context, final File file,
+            final FileHeader header) {
+        BufferedOutputStream outputStream = null;
+        File tempFile = null;
+        try {
+            final String locale =
+                    header.mDictionaryOptions.mAttributes.get(DICTIONARY_LOCALE_ATTRIBUTE);
+            // Create the id for a main dictionary for this locale
+            final String id = BinaryDictionaryGetter.MAIN_DICTIONARY_CATEGORY
+                    + BinaryDictionaryGetter.ID_CATEGORY_SEPARATOR + locale;
+            final String finalFileName =
+                    BinaryDictionaryGetter.getCacheFileName(id, locale, context);
+            final String tempFileName = BinaryDictionaryGetter.getTempFileName(id, context);
+            tempFile = new File(tempFileName);
+            tempFile.delete();
+            outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
+            final BufferedInputStream bufferedStream = new BufferedInputStream(
+                    new FileInputStream(file));
+            BinaryDictionaryFileDumper.checkMagicAndCopyFileTo(bufferedStream, outputStream);
+            outputStream.flush();
+            final File finalFile = new File(finalFileName);
+            finalFile.delete();
+            if (!tempFile.renameTo(finalFile)) {
+                throw new IOException("Can't move the file to its final name");
+            }
+        } catch (IOException e) {
+            // There was an error: show a dialog
+            new AlertDialog.Builder(context)
+                    .setTitle(R.string.error)
+                    .setMessage(e.toString())
+                    .setPositiveButton(android.R.string.ok, new OnClickListener() {
+                        @Override
+                        public void onClick(final DialogInterface dialog, final int which) {
+                            dialog.dismiss();
+                        }
+                    }).create().show();
+            return;
+        } finally {
+            try {
+                if (null != outputStream) outputStream.close();
+                if (null != tempFile) tempFile.delete();
+            } catch (IOException e) {
+                // Don't do anything
+            }
+        }
     }
 }
diff --git a/native/jni/src/geometry_utils.h b/native/jni/src/geometry_utils.h
index 64bbbd4..4cbb127 100644
--- a/native/jni/src/geometry_utils.h
+++ b/native/jni/src/geometry_utils.h
@@ -44,5 +44,10 @@
     }
     return diff;
 }
+
+static AK_FORCE_INLINE int getDistanceInt(const int x1, const int y1, const int x2,
+        const int y2) {
+    return static_cast<int>(hypotf(static_cast<float>(x1 - x2), static_cast<float>(y1 - y2)));
+}
 } // namespace latinime
 #endif // LATINIME_GEOMETRY_UTILS_H
diff --git a/native/jni/src/proximity_info.cpp b/native/jni/src/proximity_info.cpp
index 3669fd3..c563b07 100644
--- a/native/jni/src/proximity_info.cpp
+++ b/native/jni/src/proximity_info.cpp
@@ -164,7 +164,7 @@
     for (int i = 0; i < KEY_COUNT; i++) {
         mKeyKeyDistancesG[i][i] = 0;
         for (int j = i + 1; j < KEY_COUNT; j++) {
-            mKeyKeyDistancesG[i][j] = ProximityInfoUtils::getDistanceInt(
+            mKeyKeyDistancesG[i][j] = getDistanceInt(
                     mCenterXsG[i], mCenterYsG[i], mCenterXsG[j], mCenterYsG[j]);
             mKeyKeyDistancesG[j][i] = mKeyKeyDistancesG[i][j];
         }
diff --git a/native/jni/src/proximity_info_state.cpp b/native/jni/src/proximity_info_state.cpp
index 118d5c0..31b6e4b 100644
--- a/native/jni/src/proximity_info_state.cpp
+++ b/native/jni/src/proximity_info_state.cpp
@@ -23,7 +23,7 @@
 #include "geometry_utils.h"
 #include "proximity_info.h"
 #include "proximity_info_state.h"
-#include "proximity_info_utils.h"
+#include "proximity_info_state_utils.h"
 
 namespace latinime {
 
@@ -94,82 +94,11 @@
     mSampledInputSize = 0;
 
     if (xCoordinates && yCoordinates) {
-        if (DEBUG_SAMPLING_POINTS) {
-            if (isGeometric) {
-                for (int i = 0; i < inputSize; ++i) {
-                    AKLOGI("(%d) x %d, y %d, time %d",
-                            i, xCoordinates[i], yCoordinates[i], times[i]);
-                }
-            }
-        }
-#ifdef DO_ASSERT_TEST
-        if (times) {
-            for (int i = 0; i < inputSize; ++i) {
-                if (i > 0) {
-                    ASSERT(times[i] >= times[i - 1]);
-                }
-            }
-        }
-#endif
-        const bool proximityOnly = !isGeometric && (xCoordinates[0] < 0 || yCoordinates[0] < 0);
-        int lastInputIndex = pushTouchPointStartIndex;
-        for (int i = lastInputIndex; i < inputSize; ++i) {
-            const int pid = pointerIds ? pointerIds[i] : 0;
-            if (pointerId == pid) {
-                lastInputIndex = i;
-            }
-        }
-        if (DEBUG_GEO_FULL) {
-            AKLOGI("Init ProximityInfoState: last input index = %d", lastInputIndex);
-        }
-        // Working space to save near keys distances for current, prev and prevprev input point.
-        NearKeysDistanceMap nearKeysDistances[3];
-        // These pointers are swapped for each inputs points.
-        NearKeysDistanceMap *currentNearKeysDistances = &nearKeysDistances[0];
-        NearKeysDistanceMap *prevNearKeysDistances = &nearKeysDistances[1];
-        NearKeysDistanceMap *prevPrevNearKeysDistances = &nearKeysDistances[2];
-        // "sumAngle" is accumulated by each angle of input points. And when "sumAngle" exceeds
-        // the threshold we save that point, reset sumAngle. This aims to keep the figure of
-        // the curve.
-        float sumAngle = 0.0f;
-
-        for (int i = pushTouchPointStartIndex; i <= lastInputIndex; ++i) {
-            // Assuming pointerId == 0 if pointerIds is null.
-            const int pid = pointerIds ? pointerIds[i] : 0;
-            if (DEBUG_GEO_FULL) {
-                AKLOGI("Init ProximityInfoState: (%d)PID = %d", i, pid);
-            }
-            if (pointerId == pid) {
-                const int c = isGeometric ? NOT_A_COORDINATE : getPrimaryCodePointAt(i);
-                const int x = proximityOnly ? NOT_A_COORDINATE : xCoordinates[i];
-                const int y = proximityOnly ? NOT_A_COORDINATE : yCoordinates[i];
-                const int time = times ? times[i] : -1;
-
-                if (i > 1) {
-                    const float prevAngle = getAngle(xCoordinates[i - 2], yCoordinates[i - 2],
-                            xCoordinates[i - 1], yCoordinates[i - 1]);
-                    const float currentAngle =
-                            getAngle(xCoordinates[i - 1], yCoordinates[i - 1], x, y);
-                    sumAngle += getAngleDiff(prevAngle, currentAngle);
-                }
-
-                if (pushTouchPoint(i, c, x, y, time, isGeometric /* do sampling */,
-                        i == lastInputIndex, sumAngle, currentNearKeysDistances,
-                        prevNearKeysDistances, prevPrevNearKeysDistances)) {
-                    // Previous point information was popped.
-                    NearKeysDistanceMap *tmp = prevNearKeysDistances;
-                    prevNearKeysDistances = currentNearKeysDistances;
-                    currentNearKeysDistances = tmp;
-                } else {
-                    NearKeysDistanceMap *tmp = prevPrevNearKeysDistances;
-                    prevPrevNearKeysDistances = prevNearKeysDistances;
-                    prevNearKeysDistances = currentNearKeysDistances;
-                    currentNearKeysDistances = tmp;
-                    sumAngle = 0.0f;
-                }
-            }
-        }
-        mSampledInputSize = mSampledInputXs.size();
+        mSampledInputSize = ProximityInfoStateUtils::updateTouchPoints(
+                mProximityInfo->getMostCommonKeyWidth(), mProximityInfo, mMaxPointToKeyLength,
+                mInputProximities, xCoordinates, yCoordinates, times, pointerIds, inputSize,
+                isGeometric, pointerId, pushTouchPointStartIndex,
+                &mSampledInputXs, &mSampledInputYs, &mTimes, &mLengthCache, &mInputIndice);
     }
 
     if (mSampledInputSize > 0 && isGeometric) {
@@ -324,7 +253,7 @@
             if (i < mSampledInputSize - 1 && j >= mInputIndice[i + 1]) {
                 break;
             }
-            length += ProximityInfoUtils::getDistanceInt(xCoordinates[j], yCoordinates[j],
+            length += getDistanceInt(xCoordinates[j], yCoordinates[j],
                     xCoordinates[j + 1], yCoordinates[j + 1]);
             duration += times[j + 1] - times[j];
         }
@@ -333,7 +262,7 @@
                 break;
             }
             // TODO: use mLengthCache instead?
-            length += ProximityInfoUtils::getDistanceInt(xCoordinates[j], yCoordinates[j],
+            length += getDistanceInt(xCoordinates[j], yCoordinates[j],
                     xCoordinates[j + 1], yCoordinates[j + 1]);
             duration += times[j + 1] - times[j];
         }
@@ -388,8 +317,7 @@
     while (start > 0 && tempBeelineDistance < lookupRadius) {
         tempTime += times[start] - times[start - 1];
         --start;
-        tempBeelineDistance = ProximityInfoUtils::getDistanceInt(x0, y0, xCoordinates[start],
-                yCoordinates[start]);
+        tempBeelineDistance = getDistanceInt(x0, y0, xCoordinates[start], yCoordinates[start]);
     }
     // Exclusive unless this is an edge point
     if (start > 0 && start < actualInputIndex) {
@@ -402,8 +330,7 @@
     while (end < (inputSize - 1) && tempBeelineDistance < lookupRadius) {
         tempTime += times[end + 1] - times[end];
         ++end;
-        tempBeelineDistance = ProximityInfoUtils::getDistanceInt(x0, y0, xCoordinates[end],
-                 yCoordinates[end]);
+        tempBeelineDistance = getDistanceInt(x0, y0, xCoordinates[end], yCoordinates[end]);
     }
     // Exclusive unless this is an edge point
     if (end > actualInputIndex && end < (inputSize - 1)) {
@@ -421,7 +348,7 @@
     const int y2 = yCoordinates[start];
     const int x3 = xCoordinates[end];
     const int y3 = yCoordinates[end];
-    const int beelineDistance = ProximityInfoUtils::getDistanceInt(x2, y2, x3, y3);
+    const int beelineDistance = getDistanceInt(x2, y2, x3, y3);
     int adjustedStartTime = times[start];
     if (start == 0 && actualInputIndex == 0 && inputSize > 1) {
         adjustedStartTime += FIRST_POINT_TIME_OFFSET_MILLIS;
@@ -477,166 +404,6 @@
     return true;
 }
 
-// Calculating point to key distance for all near keys and returning the distance between
-// the given point and the nearest key position.
-float ProximityInfoState::updateNearKeysDistances(const int x, const int y,
-        NearKeysDistanceMap *const currentNearKeysDistances) {
-    static const float NEAR_KEY_THRESHOLD = 2.0f;
-
-    currentNearKeysDistances->clear();
-    const int keyCount = mProximityInfo->getKeyCount();
-    float nearestKeyDistance = mMaxPointToKeyLength;
-    for (int k = 0; k < keyCount; ++k) {
-        const float dist = mProximityInfo->getNormalizedSquaredDistanceFromCenterFloatG(k, x, y);
-        if (dist < NEAR_KEY_THRESHOLD) {
-            currentNearKeysDistances->insert(std::pair<int, float>(k, dist));
-        }
-        if (nearestKeyDistance > dist) {
-            nearestKeyDistance = dist;
-        }
-    }
-    return nearestKeyDistance;
-}
-
-// Check if previous point is at local minimum position to near keys.
-bool ProximityInfoState::isPrevLocalMin(const NearKeysDistanceMap *const currentNearKeysDistances,
-        const NearKeysDistanceMap *const prevNearKeysDistances,
-        const NearKeysDistanceMap *const prevPrevNearKeysDistances) const {
-    static const float MARGIN = 0.01f;
-
-    for (NearKeysDistanceMap::const_iterator it = prevNearKeysDistances->begin();
-        it != prevNearKeysDistances->end(); ++it) {
-        NearKeysDistanceMap::const_iterator itPP = prevPrevNearKeysDistances->find(it->first);
-        NearKeysDistanceMap::const_iterator itC = currentNearKeysDistances->find(it->first);
-        if ((itPP == prevPrevNearKeysDistances->end() || itPP->second > it->second + MARGIN)
-                && (itC == currentNearKeysDistances->end() || itC->second > it->second + MARGIN)) {
-            return true;
-        }
-    }
-    return false;
-}
-
-// Calculating a point score that indicates usefulness of the point.
-float ProximityInfoState::getPointScore(
-        const int x, const int y, const int time, const bool lastPoint, const float nearest,
-        const float sumAngle, const NearKeysDistanceMap *const currentNearKeysDistances,
-        const NearKeysDistanceMap *const prevNearKeysDistances,
-        const NearKeysDistanceMap *const prevPrevNearKeysDistances) const {
-    static const int DISTANCE_BASE_SCALE = 100;
-    static const float NEAR_KEY_THRESHOLD = 0.6f;
-    static const int CORNER_CHECK_DISTANCE_THRESHOLD_SCALE = 25;
-    static const float NOT_LOCALMIN_DISTANCE_SCORE = -1.0f;
-    static const float LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE = 1.0f;
-    static const float CORNER_ANGLE_THRESHOLD = M_PI_F * 2.0f / 3.0f;
-    static const float CORNER_SUM_ANGLE_THRESHOLD = M_PI_F / 4.0f;
-    static const float CORNER_SCORE = 1.0f;
-
-    const size_t size = mSampledInputXs.size();
-    // If there is only one point, add this point. Besides, if the previous point's distance map
-    // is empty, we re-compute nearby keys distances from the current point.
-    // Note that the current point is the first point in the incremental input that needs to
-    // be re-computed.
-    if (size <= 1 || prevNearKeysDistances->empty()) {
-        return 0.0f;
-    }
-
-    const int baseSampleRate = mProximityInfo->getMostCommonKeyWidth();
-    const int distPrev = ProximityInfoUtils::getDistanceInt(
-            mSampledInputXs.back(), mSampledInputYs.back(),
-            mSampledInputXs[size - 2], mSampledInputYs[size - 2]) * DISTANCE_BASE_SCALE;
-    float score = 0.0f;
-
-    // Location
-    if (!isPrevLocalMin(currentNearKeysDistances, prevNearKeysDistances,
-        prevPrevNearKeysDistances)) {
-        score += NOT_LOCALMIN_DISTANCE_SCORE;
-    } else if (nearest < NEAR_KEY_THRESHOLD) {
-        // Promote points nearby keys
-        score += LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE;
-    }
-    // Angle
-    const float angle1 = getAngle(x, y, mSampledInputXs.back(), mSampledInputYs.back());
-    const float angle2 = getAngle(mSampledInputXs.back(), mSampledInputYs.back(),
-            mSampledInputXs[size - 2], mSampledInputYs[size - 2]);
-    const float angleDiff = getAngleDiff(angle1, angle2);
-
-    // Save corner
-    if (distPrev > baseSampleRate * CORNER_CHECK_DISTANCE_THRESHOLD_SCALE
-            && (sumAngle > CORNER_SUM_ANGLE_THRESHOLD || angleDiff > CORNER_ANGLE_THRESHOLD)) {
-        score += CORNER_SCORE;
-    }
-    return score;
-}
-
-// Sampling touch point and pushing information to vectors.
-// Returning if previous point is popped or not.
-bool ProximityInfoState::pushTouchPoint(const int inputIndex, const int nodeCodePoint, int x, int y,
-        const int time, const bool sample, const bool isLastPoint, const float sumAngle,
-        NearKeysDistanceMap *const currentNearKeysDistances,
-        const NearKeysDistanceMap *const prevNearKeysDistances,
-        const NearKeysDistanceMap *const prevPrevNearKeysDistances) {
-    static const int LAST_POINT_SKIP_DISTANCE_SCALE = 4;
-
-    size_t size = mSampledInputXs.size();
-    bool popped = false;
-    if (nodeCodePoint < 0 && sample) {
-        const float nearest = updateNearKeysDistances(x, y, currentNearKeysDistances);
-        const float score = getPointScore(x, y, time, isLastPoint, nearest, sumAngle,
-                currentNearKeysDistances, prevNearKeysDistances, prevPrevNearKeysDistances);
-        if (score < 0) {
-            // Pop previous point because it would be useless.
-            popInputData();
-            size = mSampledInputXs.size();
-            popped = true;
-        } else {
-            popped = false;
-        }
-        // Check if the last point should be skipped.
-        if (isLastPoint && size > 0) {
-            if (ProximityInfoUtils::getDistanceInt(x, y, mSampledInputXs.back(),
-                    mSampledInputYs.back()) * LAST_POINT_SKIP_DISTANCE_SCALE
-                            < mProximityInfo->getMostCommonKeyWidth()) {
-                // This point is not used because it's too close to the previous point.
-                if (DEBUG_GEO_FULL) {
-                    AKLOGI("p0: size = %zd, x = %d, y = %d, lx = %d, ly = %d, dist = %d, "
-                           "width = %d", size, x, y, mSampledInputXs.back(), mSampledInputYs.back(),
-                           ProximityInfoUtils::getDistanceInt(x, y, mSampledInputXs.back(),
-                                   mSampledInputYs.back()),
-                           mProximityInfo->getMostCommonKeyWidth()
-                                   / LAST_POINT_SKIP_DISTANCE_SCALE);
-                }
-                return popped;
-            }
-        }
-    }
-
-    if (nodeCodePoint >= 0 && (x < 0 || y < 0)) {
-        const int keyId = mProximityInfo->getKeyIndexOf(nodeCodePoint);
-        if (keyId >= 0) {
-            x = mProximityInfo->getKeyCenterXOfKeyIdG(keyId);
-            y = mProximityInfo->getKeyCenterYOfKeyIdG(keyId);
-        }
-    }
-
-    // Pushing point information.
-    if (size > 0) {
-        mLengthCache.push_back(
-                mLengthCache.back() + ProximityInfoUtils::getDistanceInt(
-                        x, y, mSampledInputXs.back(), mSampledInputYs.back()));
-    } else {
-        mLengthCache.push_back(0);
-    }
-    mSampledInputXs.push_back(x);
-    mSampledInputYs.push_back(y);
-    mTimes.push_back(time);
-    mInputIndice.push_back(inputIndex);
-    if (DEBUG_GEO_FULL) {
-        AKLOGI("pushTouchPoint: x = %03d, y = %03d, time = %d, index = %d, popped ? %01d",
-                x, y, time, inputIndex, popped);
-    }
-    return popped;
-}
-
 float ProximityInfoState::calculateNormalizedSquaredDistance(
         const int keyIndex, const int inputIndex) const {
     if (keyIndex == NOT_AN_INDEX) {
@@ -809,11 +576,8 @@
 }
 
 void ProximityInfoState::popInputData() {
-    mSampledInputXs.pop_back();
-    mSampledInputYs.pop_back();
-    mTimes.pop_back();
-    mLengthCache.pop_back();
-    mInputIndice.pop_back();
+    ProximityInfoStateUtils::popInputData(&mSampledInputXs, &mSampledInputYs, &mTimes,
+            &mLengthCache, &mInputIndice);
 }
 
 float ProximityInfoState::getDirection(const int index0, const int index1) const {
diff --git a/native/jni/src/proximity_info_state.h b/native/jni/src/proximity_info_state.h
index 655fda5..0f0eb7d 100644
--- a/native/jni/src/proximity_info_state.h
+++ b/native/jni/src/proximity_info_state.h
@@ -24,6 +24,7 @@
 #include "char_utils.h"
 #include "defines.h"
 #include "hash_map_compat.h"
+#include "proximity_info_state_utils.h"
 
 namespace latinime {
 
@@ -230,7 +231,7 @@
     }
 
     inline const int *getProximityCodePointsAt(const int index) const {
-        return mInputProximities + (index * MAX_PROXIMITY_CHARS_SIZE_INTERNAL);
+        return ProximityInfoStateUtils::getProximityCodePointsAt(mInputProximities, index);
     }
 
     float updateNearKeysDistances(const int x, const int y,
diff --git a/native/jni/src/proximity_info_state_utils.h b/native/jni/src/proximity_info_state_utils.h
new file mode 100644
index 0000000..53b992a
--- /dev/null
+++ b/native/jni/src/proximity_info_state_utils.h
@@ -0,0 +1,319 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef LATINIME_PROXIMITY_INFO_STATE_UTILS_H
+#define LATINIME_PROXIMITY_INFO_STATE_UTILS_H
+
+#include <vector>
+
+#include "defines.h"
+#include "geometry_utils.h"
+#include "hash_map_compat.h"
+#include "proximity_info.h"
+
+namespace latinime {
+class ProximityInfoStateUtils {
+ public:
+    static int updateTouchPoints(const int mostCommonKeyWidth,
+            const ProximityInfo *const proximityInfo, const int maxPointToKeyLength,
+            const int *const inputProximities,
+            const int *const inputXCoordinates, const int *const inputYCoordinates,
+            const int *const times, const int *const pointerIds, const int inputSize,
+            const bool isGeometric, const int pointerId, const int pushTouchPointStartIndex,
+            std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs,
+            std::vector<int> *sampledInputTimes, std::vector<int> *sampledLengthCache,
+            std::vector<int> *sampledInputIndice) {
+        if (DEBUG_SAMPLING_POINTS) {
+            if (times) {
+                for (int i = 0; i < inputSize; ++i) {
+                    AKLOGI("(%d) x %d, y %d, time %d",
+                            i, xCoordinates[i], yCoordinates[i], times[i]);
+                }
+            }
+        }
+#ifdef DO_ASSERT_TEST
+        if (times) {
+            for (int i = 0; i < inputSize; ++i) {
+                if (i > 0) {
+                    ASSERT(times[i] >= times[i - 1]);
+                }
+            }
+        }
+#endif
+        const bool proximityOnly = !isGeometric
+                && (inputXCoordinates[0] < 0 || inputYCoordinates[0] < 0);
+        int lastInputIndex = pushTouchPointStartIndex;
+        for (int i = lastInputIndex; i < inputSize; ++i) {
+            const int pid = pointerIds ? pointerIds[i] : 0;
+            if (pointerId == pid) {
+                lastInputIndex = i;
+            }
+        }
+        if (DEBUG_GEO_FULL) {
+            AKLOGI("Init ProximityInfoState: last input index = %d", lastInputIndex);
+        }
+        // Working space to save near keys distances for current, prev and prevprev input point.
+        NearKeysDistanceMap nearKeysDistances[3];
+        // These pointers are swapped for each inputs points.
+        NearKeysDistanceMap *currentNearKeysDistances = &nearKeysDistances[0];
+        NearKeysDistanceMap *prevNearKeysDistances = &nearKeysDistances[1];
+        NearKeysDistanceMap *prevPrevNearKeysDistances = &nearKeysDistances[2];
+        // "sumAngle" is accumulated by each angle of input points. And when "sumAngle" exceeds
+        // the threshold we save that point, reset sumAngle. This aims to keep the figure of
+        // the curve.
+        float sumAngle = 0.0f;
+
+        for (int i = pushTouchPointStartIndex; i <= lastInputIndex; ++i) {
+            // Assuming pointerId == 0 if pointerIds is null.
+            const int pid = pointerIds ? pointerIds[i] : 0;
+            if (DEBUG_GEO_FULL) {
+                AKLOGI("Init ProximityInfoState: (%d)PID = %d", i, pid);
+            }
+            if (pointerId == pid) {
+                const int c = isGeometric ?
+                        NOT_A_COORDINATE : getPrimaryCodePointAt(inputProximities, i);
+                const int x = proximityOnly ? NOT_A_COORDINATE : inputXCoordinates[i];
+                const int y = proximityOnly ? NOT_A_COORDINATE : inputYCoordinates[i];
+                const int time = times ? times[i] : -1;
+
+                if (i > 1) {
+                    const float prevAngle = getAngle(
+                            inputXCoordinates[i - 2], inputYCoordinates[i - 2],
+                            inputXCoordinates[i - 1], inputYCoordinates[i - 1]);
+                    const float currentAngle =
+                            getAngle(inputXCoordinates[i - 1], inputYCoordinates[i - 1], x, y);
+                    sumAngle += getAngleDiff(prevAngle, currentAngle);
+                }
+
+                if (pushTouchPoint(mostCommonKeyWidth, proximityInfo, maxPointToKeyLength,
+                        i, c, x, y, time, isGeometric /* do sampling */,
+                        i == lastInputIndex, sumAngle, currentNearKeysDistances,
+                        prevNearKeysDistances, prevPrevNearKeysDistances,
+                        sampledInputXs, sampledInputYs, sampledInputTimes, sampledLengthCache,
+                        sampledInputIndice)) {
+                    // Previous point information was popped.
+                    NearKeysDistanceMap *tmp = prevNearKeysDistances;
+                    prevNearKeysDistances = currentNearKeysDistances;
+                    currentNearKeysDistances = tmp;
+                } else {
+                    NearKeysDistanceMap *tmp = prevPrevNearKeysDistances;
+                    prevPrevNearKeysDistances = prevNearKeysDistances;
+                    prevNearKeysDistances = currentNearKeysDistances;
+                    currentNearKeysDistances = tmp;
+                    sumAngle = 0.0f;
+                }
+            }
+        }
+        return sampledInputXs->size();
+    }
+
+    static const int *getProximityCodePointsAt(
+            const int *const inputProximities, const int index) {
+        return inputProximities + (index * MAX_PROXIMITY_CHARS_SIZE_INTERNAL);
+    }
+
+    static int getPrimaryCodePointAt(const int *const inputProximities, const int index) {
+        return getProximityCodePointsAt(inputProximities, index)[0];
+    }
+
+    static void popInputData(std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs,
+            std::vector<int> *sampledInputTimes, std::vector<int> *sampledLengthCache,
+            std::vector<int> *sampledInputIndice) {
+        sampledInputXs->pop_back();
+        sampledInputYs->pop_back();
+        sampledInputTimes->pop_back();
+        sampledLengthCache->pop_back();
+        sampledInputIndice->pop_back();
+    }
+
+ private:
+    DISALLOW_IMPLICIT_CONSTRUCTORS(ProximityInfoStateUtils);
+
+    typedef hash_map_compat<int, float> NearKeysDistanceMap;
+
+    // Calculating point to key distance for all near keys and returning the distance between
+    // the given point and the nearest key position.
+    static float updateNearKeysDistances(const ProximityInfo *const proximityInfo,
+            const float maxPointToKeyLength, const int x, const int y,
+            NearKeysDistanceMap *const currentNearKeysDistances) {
+        static const float NEAR_KEY_THRESHOLD = 2.0f;
+
+        currentNearKeysDistances->clear();
+        const int keyCount = proximityInfo->getKeyCount();
+        float nearestKeyDistance = maxPointToKeyLength;
+        for (int k = 0; k < keyCount; ++k) {
+            const float dist = proximityInfo->getNormalizedSquaredDistanceFromCenterFloatG(k, x, y);
+            if (dist < NEAR_KEY_THRESHOLD) {
+                currentNearKeysDistances->insert(std::pair<int, float>(k, dist));
+            }
+            if (nearestKeyDistance > dist) {
+                nearestKeyDistance = dist;
+            }
+        }
+        return nearestKeyDistance;
+    }
+
+    // Check if previous point is at local minimum position to near keys.
+    static bool isPrevLocalMin(const NearKeysDistanceMap *const currentNearKeysDistances,
+            const NearKeysDistanceMap *const prevNearKeysDistances,
+            const NearKeysDistanceMap *const prevPrevNearKeysDistances) {
+        static const float MARGIN = 0.01f;
+
+        for (NearKeysDistanceMap::const_iterator it = prevNearKeysDistances->begin();
+            it != prevNearKeysDistances->end(); ++it) {
+            NearKeysDistanceMap::const_iterator itPP = prevPrevNearKeysDistances->find(it->first);
+            NearKeysDistanceMap::const_iterator itC = currentNearKeysDistances->find(it->first);
+            if ((itPP == prevPrevNearKeysDistances->end() || itPP->second > it->second + MARGIN)
+                    && (itC == currentNearKeysDistances->end()
+                            || itC->second > it->second + MARGIN)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    // Calculating a point score that indicates usefulness of the point.
+    static float getPointScore(const int mostCommonKeyWidth,
+            const int x, const int y, const int time, const bool lastPoint, const float nearest,
+            const float sumAngle, const NearKeysDistanceMap *const currentNearKeysDistances,
+            const NearKeysDistanceMap *const prevNearKeysDistances,
+            const NearKeysDistanceMap *const prevPrevNearKeysDistances,
+            std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs) {
+        static const int DISTANCE_BASE_SCALE = 100;
+        static const float NEAR_KEY_THRESHOLD = 0.6f;
+        static const int CORNER_CHECK_DISTANCE_THRESHOLD_SCALE = 25;
+        static const float NOT_LOCALMIN_DISTANCE_SCORE = -1.0f;
+        static const float LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE = 1.0f;
+        static const float CORNER_ANGLE_THRESHOLD = M_PI_F * 2.0f / 3.0f;
+        static const float CORNER_SUM_ANGLE_THRESHOLD = M_PI_F / 4.0f;
+        static const float CORNER_SCORE = 1.0f;
+
+        const size_t size = sampledInputXs->size();
+        // If there is only one point, add this point. Besides, if the previous point's distance map
+        // is empty, we re-compute nearby keys distances from the current point.
+        // Note that the current point is the first point in the incremental input that needs to
+        // be re-computed.
+        if (size <= 1 || prevNearKeysDistances->empty()) {
+            return 0.0f;
+        }
+
+        const int baseSampleRate = mostCommonKeyWidth;
+        const int distPrev = getDistanceInt(
+                sampledInputXs->back(), sampledInputYs->back(),
+                (*sampledInputXs)[size - 2], (*sampledInputYs)[size - 2]) * DISTANCE_BASE_SCALE;
+        float score = 0.0f;
+
+        // Location
+        if (!isPrevLocalMin(currentNearKeysDistances, prevNearKeysDistances,
+            prevPrevNearKeysDistances)) {
+            score += NOT_LOCALMIN_DISTANCE_SCORE;
+        } else if (nearest < NEAR_KEY_THRESHOLD) {
+            // Promote points nearby keys
+            score += LOCALMIN_DISTANCE_AND_NEAR_TO_KEY_SCORE;
+        }
+        // Angle
+        const float angle1 = getAngle(x, y, sampledInputXs->back(), sampledInputYs->back());
+        const float angle2 = getAngle(sampledInputXs->back(), sampledInputYs->back(),
+                (*sampledInputXs)[size - 2], (*sampledInputYs)[size - 2]);
+        const float angleDiff = getAngleDiff(angle1, angle2);
+
+        // Save corner
+        if (distPrev > baseSampleRate * CORNER_CHECK_DISTANCE_THRESHOLD_SCALE
+                && (sumAngle > CORNER_SUM_ANGLE_THRESHOLD || angleDiff > CORNER_ANGLE_THRESHOLD)) {
+            score += CORNER_SCORE;
+        }
+        return score;
+    }
+
+    // Sampling touch point and pushing information to vectors.
+    // Returning if previous point is popped or not.
+    static bool pushTouchPoint(const int mostCommonKeyWidth,
+            const ProximityInfo *const proximityInfo, const int maxPointToKeyLength,
+            const int inputIndex, const int nodeCodePoint, int x, int y,
+            const int time, const bool sample, const bool isLastPoint, const float sumAngle,
+            NearKeysDistanceMap *const currentNearKeysDistances,
+            const NearKeysDistanceMap *const prevNearKeysDistances,
+            const NearKeysDistanceMap *const prevPrevNearKeysDistances,
+            std::vector<int> *sampledInputXs, std::vector<int> *sampledInputYs,
+            std::vector<int> *sampledInputTimes, std::vector<int> *sampledLengthCache,
+            std::vector<int> *sampledInputIndice) {
+        static const int LAST_POINT_SKIP_DISTANCE_SCALE = 4;
+
+        size_t size = sampledInputXs->size();
+        bool popped = false;
+        if (nodeCodePoint < 0 && sample) {
+            const float nearest = updateNearKeysDistances(
+                    proximityInfo, maxPointToKeyLength, x, y, currentNearKeysDistances);
+            const float score = getPointScore(mostCommonKeyWidth, x, y, time, isLastPoint, nearest,
+                    sumAngle, currentNearKeysDistances, prevNearKeysDistances,
+                    prevPrevNearKeysDistances, sampledInputXs, sampledInputYs);
+            if (score < 0) {
+                // Pop previous point because it would be useless.
+                popInputData(sampledInputXs, sampledInputYs, sampledInputTimes, sampledLengthCache,
+                        sampledInputIndice);
+                size = sampledInputXs->size();
+                popped = true;
+            } else {
+                popped = false;
+            }
+            // Check if the last point should be skipped.
+            if (isLastPoint && size > 0) {
+                if (getDistanceInt(x, y, sampledInputXs->back(),
+                        sampledInputYs->back()) * LAST_POINT_SKIP_DISTANCE_SCALE
+                                < mostCommonKeyWidth) {
+                    // This point is not used because it's too close to the previous point.
+                    if (DEBUG_GEO_FULL) {
+                        AKLOGI("p0: size = %zd, x = %d, y = %d, lx = %d, ly = %d, dist = %d, "
+                               "width = %d", size, x, y, mSampledInputXs.back(),
+                               mSampledInputYs.back(), ProximityInfoUtils::getDistanceInt(
+                                       x, y, mSampledInputXs.back(), mSampledInputYs.back()),
+                               mProximityInfo->getMostCommonKeyWidth()
+                                       / LAST_POINT_SKIP_DISTANCE_SCALE);
+                    }
+                    return popped;
+                }
+            }
+        }
+
+        if (nodeCodePoint >= 0 && (x < 0 || y < 0)) {
+            const int keyId = proximityInfo->getKeyIndexOf(nodeCodePoint);
+            if (keyId >= 0) {
+                x = proximityInfo->getKeyCenterXOfKeyIdG(keyId);
+                y = proximityInfo->getKeyCenterYOfKeyIdG(keyId);
+            }
+        }
+
+        // Pushing point information.
+        if (size > 0) {
+            sampledLengthCache->push_back(
+                    sampledLengthCache->back() + getDistanceInt(
+                            x, y, sampledInputXs->back(), sampledInputYs->back()));
+        } else {
+            sampledLengthCache->push_back(0);
+        }
+        sampledInputXs->push_back(x);
+        sampledInputYs->push_back(y);
+        sampledInputTimes->push_back(time);
+        sampledInputIndice->push_back(inputIndex);
+        if (DEBUG_GEO_FULL) {
+            AKLOGI("pushTouchPoint: x = %03d, y = %03d, time = %d, index = %d, popped ? %01d",
+                    x, y, time, inputIndex, popped);
+        }
+        return popped;
+    }
+};
+} // namespace latinime
+#endif // LATINIME_PROXIMITY_INFO_STATE_UTILS_H
diff --git a/native/jni/src/proximity_info_utils.h b/native/jni/src/proximity_info_utils.h
index 5adcc2e..0930207 100644
--- a/native/jni/src/proximity_info_utils.h
+++ b/native/jni/src/proximity_info_utils.h
@@ -92,11 +92,6 @@
         return SQUARE_FLOAT(x1 - x2) + SQUARE_FLOAT(y1 - y2);
     }
 
-    static AK_FORCE_INLINE int getDistanceInt(const int x1, const int y1, const int x2,
-            const int y2) {
-        return static_cast<int>(hypotf(static_cast<float>(x1 - x2), static_cast<float>(y1 - y2)));
-    }
-
     static inline float pointToLineSegSquaredDistanceFloat(const float x, const float y,
         const float x1, const float y1, const float x2, const float y2, const bool extend) {
         const float ray1x = x - x1;