diff options
Diffstat (limited to 'java/src/com/android/inputmethod/latin')
105 files changed, 4802 insertions, 2391 deletions
diff --git a/java/src/com/android/inputmethod/latin/AbstractDictionaryWriter.java b/java/src/com/android/inputmethod/latin/AbstractDictionaryWriter.java new file mode 100644 index 000000000..ebbcedc96 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/AbstractDictionaryWriter.java @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin; + +import android.content.Context; +import android.util.Log; + +import com.android.inputmethod.latin.makedict.UnsupportedFormatException; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +// TODO: Quit extending Dictionary after implementing dynamic binary dictionary. +abstract public class AbstractDictionaryWriter extends Dictionary { + /** Used for Log actions from this class */ + private static final String TAG = AbstractDictionaryWriter.class.getSimpleName(); + + private final Context mContext; + + public AbstractDictionaryWriter(final Context context, final String dictType) { + super(dictType); + mContext = context; + } + + abstract public void clear(); + + abstract public void addUnigramWord(final String word, final String shortcutTarget, + final int frequency, final boolean isNotAWord); + + abstract public void addBigramWords(final String word0, final String word1, + final int frequency, final boolean isValid); + + abstract public void removeBigramWords(final String word0, final String word1); + + abstract protected void writeBinaryDictionary(final FileOutputStream out) + throws IOException, UnsupportedFormatException; + + public void write(final String fileName) { + final String tempFileName = fileName + ".temp"; + final File file = new File(mContext.getFilesDir(), fileName); + final File tempFile = new File(mContext.getFilesDir(), tempFileName); + FileOutputStream out = null; + try { + out = new FileOutputStream(tempFile); + writeBinaryDictionary(out); + out.flush(); + out.close(); + tempFile.renameTo(file); + } catch (IOException e) { + Log.e(TAG, "IO exception while writing file", e); + } catch (UnsupportedFormatException e) { + Log.e(TAG, "Unsupported format", e); + } finally { + if (out != null) { + try { + out.close(); + } catch (IOException e) { + // ignore + } + } + } + } +} diff --git a/java/src/com/android/inputmethod/latin/AssetFileAddress.java b/java/src/com/android/inputmethod/latin/AssetFileAddress.java index 47c750f54..875192554 100644 --- a/java/src/com/android/inputmethod/latin/AssetFileAddress.java +++ b/java/src/com/android/inputmethod/latin/AssetFileAddress.java @@ -24,7 +24,7 @@ import java.io.File; * the package file. Open it correctly thus requires the name of the package it is in, but * also the offset in the file and the length of this data. This class encapsulates these three. */ -final class AssetFileAddress { +public final class AssetFileAddress { public final String mFilename; public final long mOffset; public final long mLength; diff --git a/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java b/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java index 986b1a178..42c57946d 100644 --- a/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java +++ b/java/src/com/android/inputmethod/latin/AudioAndHapticFeedbackManager.java @@ -16,6 +16,8 @@ package com.android.inputmethod.latin; +import com.android.inputmethod.latin.settings.SettingsValues; + import android.content.Context; import android.media.AudioManager; import android.os.Vibrator; diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionary.java b/java/src/com/android/inputmethod/latin/BinaryDictionary.java index 4fc1919dc..d181bf697 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionary.java @@ -21,6 +21,11 @@ import android.util.SparseArray; import com.android.inputmethod.keyboard.ProximityInfo; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; +import com.android.inputmethod.latin.settings.AdditionalFeaturesSettingUtils; +import com.android.inputmethod.latin.settings.NativeSuggestOptions; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.JniUtils; +import com.android.inputmethod.latin.utils.StringUtils; import java.util.ArrayList; import java.util.Arrays; @@ -33,7 +38,7 @@ public final class BinaryDictionary extends Dictionary { private static final String TAG = BinaryDictionary.class.getSimpleName(); // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h - private static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH; + private static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH; // Must be equal to MAX_RESULTS in native/jni/src/defines.h private static final int MAX_RESULTS = 18; @@ -45,7 +50,7 @@ public final class BinaryDictionary extends Dictionary { private final int[] mOutputScores = new int[MAX_RESULTS]; private final int[] mOutputTypes = new int[MAX_RESULTS]; - private final boolean mUseFullEditDistance; + private final NativeSuggestOptions mNativeSuggestOptions = new NativeSuggestOptions(); private final SparseArray<DicTraverseSession> mDicTraverseSessions = CollectionUtils.newSparseArray(); @@ -74,35 +79,42 @@ public final class BinaryDictionary extends Dictionary { * @param length the length of the binary data. * @param useFullEditDistance whether to use the full edit distance in suggestions * @param dictType the dictionary type, as a human-readable string + * @param isUpdatable whether to open the dictionary file in writable mode. */ public BinaryDictionary(final String filename, final long offset, final long length, - final boolean useFullEditDistance, final Locale locale, final String dictType) { + final boolean useFullEditDistance, final Locale locale, final String dictType, + final boolean isUpdatable) { super(dictType); mLocale = locale; - mUseFullEditDistance = useFullEditDistance; - loadDictionary(filename, offset, length); + mNativeSuggestOptions.setUseFullEditDistance(useFullEditDistance); + loadDictionary(filename, offset, length, isUpdatable); } static { JniUtils.loadNativeLibrary(); } - private static native long openNative(String sourceDir, long dictOffset, long dictSize); + private static native long openNative(String sourceDir, long dictOffset, long dictSize, + boolean isUpdatable); private static native void closeNative(long dict); private static native int getProbabilityNative(long dict, int[] word); - private static native boolean isValidBigramNative(long dict, int[] word1, int[] word2); + private static native boolean isValidBigramNative(long dict, int[] word0, int[] word1); private static native int getSuggestionsNative(long dict, long proximityInfo, long traverseSession, int[] xCoordinates, int[] yCoordinates, int[] times, int[] pointerIds, int[] inputCodePoints, int inputSize, int commitPoint, - boolean isGesture, int[] prevWordCodePointArray, boolean useFullEditDistance, + int[] suggestOptions, int[] prevWordCodePointArray, int[] outputCodePoints, int[] outputScores, int[] outputIndices, int[] outputTypes); private static native float calcNormalizedScoreNative(int[] before, int[] after, int score); private static native int editDistanceNative(int[] before, int[] after); + private static native void addUnigramWordNative(long dict, int[] word, int probability); + private static native void addBigramWordsNative(long dict, int[] word0, int[] word1, + int probability); + private static native void removeBigramWordsNative(long dict, int[] word0, int[] word1); // TODO: Move native dict into session private final void loadDictionary(final String path, final long startOffset, - final long length) { - mNativeDict = openNative(path, startOffset, length); + final long length, final boolean isUpdatable) { + mNativeDict = openNative(path, startOffset, length, isUpdatable); } @Override @@ -135,12 +147,15 @@ public final class BinaryDictionary extends Dictionary { final InputPointers ips = composer.getInputPointers(); final int inputSize = isGesture ? ips.getPointerSize() : composerSize; + mNativeSuggestOptions.setIsGesture(isGesture); + mNativeSuggestOptions.setAdditionalFeaturesOptions( + AdditionalFeaturesSettingUtils.getAdditionalNativeSuggestOptions()); // proximityInfo and/or prevWordForBigrams may not be null. final int count = getSuggestionsNative(mNativeDict, proximityInfo.getNativeProximityInfo(), getTraverseSession(sessionId).getSession(), ips.getXCoordinates(), ips.getYCoordinates(), ips.getTimes(), ips.getPointerIds(), mInputCodePoints, - inputSize, 0 /* commitPoint */, isGesture, prevWordCodePointArray, - mUseFullEditDistance, mOutputCodePoints, mOutputScores, mSpaceIndices, + inputSize, 0 /* commitPoint */, mNativeSuggestOptions.getOptions(), + prevWordCodePointArray, mOutputCodePoints, mOutputScores, mSpaceIndices, mOutputTypes); final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList(); for (int j = 0; j < count; ++j) { @@ -202,11 +217,40 @@ public final class BinaryDictionary extends Dictionary { // TODO: Add a batch process version (isValidBigramMultiple?) to avoid excessive numbers of jni // calls when checking for changes in an entire dictionary. - public boolean isValidBigram(final String word1, final String word2) { - if (TextUtils.isEmpty(word1) || TextUtils.isEmpty(word2)) return false; + public boolean isValidBigram(final String word0, final String word1) { + if (TextUtils.isEmpty(word0) || TextUtils.isEmpty(word1)) return false; + final int[] codePoints0 = StringUtils.toCodePointArray(word0); final int[] codePoints1 = StringUtils.toCodePointArray(word1); - final int[] codePoints2 = StringUtils.toCodePointArray(word2); - return isValidBigramNative(mNativeDict, codePoints1, codePoints2); + return isValidBigramNative(mNativeDict, codePoints0, codePoints1); + } + + // Add a unigram entry to binary dictionary in native code. + public void addUnigramWord(final String word, final int probability) { + if (TextUtils.isEmpty(word)) { + return; + } + final int[] codePoints = StringUtils.toCodePointArray(word); + addUnigramWordNative(mNativeDict, codePoints, probability); + } + + // Add a bigram entry to binary dictionary in native code. + public void addBigramWords(final String word0, final String word1, final int probability) { + if (TextUtils.isEmpty(word0) || TextUtils.isEmpty(word1)) { + return; + } + final int[] codePoints0 = StringUtils.toCodePointArray(word0); + final int[] codePoints1 = StringUtils.toCodePointArray(word1); + addBigramWordsNative(mNativeDict, codePoints0, codePoints1, probability); + } + + // Remove a bigram entry form binary dictionary in native code. + public void removeBigramWords(final String word0, final String word1) { + if (TextUtils.isEmpty(word0) || TextUtils.isEmpty(word1)) { + return; + } + final int[] codePoints0 = StringUtils.toCodePointArray(word0); + final int[] codePoints1 = StringUtils.toCodePointArray(word1); + removeBigramWordsNative(mNativeDict, codePoints0, codePoints1); } @Override diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java index a9b58de44..722a82961 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryFileDumper.java @@ -28,10 +28,15 @@ import android.text.TextUtils; import android.util.Log; import com.android.inputmethod.dictionarypack.DictionaryPackConstants; -import com.android.inputmethod.latin.DictionaryInfoUtils.DictionaryInfo; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.DictionaryInfoUtils; +import com.android.inputmethod.latin.utils.DictionaryInfoUtils.DictionaryInfo; +import com.android.inputmethod.latin.utils.FileTransforms; +import com.android.inputmethod.latin.utils.MetadataFileUriGetter; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; +import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -304,6 +309,7 @@ public final class BinaryDictionaryFileDumper { Log.e(TAG, "Could not have the dictionary pack delete a word list"); } BinaryDictionaryGetter.removeFilesWithIdExcept(context, wordlistId, finalFile); + Log.e(TAG, "Successfully copied file for wordlist ID " + wordlistId); // Success! Close files (through the finally{} clause) and return. return; } catch (Exception e) { @@ -319,20 +325,12 @@ public final class BinaryDictionaryFileDumper { // Try the next method. } finally { // Ignore exceptions while closing files. - try { - if (null != afd) afd.close(); - if (null != inputStream) inputStream.close(); - if (null != uncompressedStream) uncompressedStream.close(); - if (null != decryptedStream) decryptedStream.close(); - if (null != bufferedInputStream) bufferedInputStream.close(); - } catch (Exception e) { - Log.e(TAG, "Exception while closing a file descriptor", e); - } - try { - if (null != bufferedOutputStream) bufferedOutputStream.close(); - } catch (Exception e) { - Log.e(TAG, "Exception while closing a file", e); - } + closeAssetFileDescriptorAndReportAnyException(afd); + closeCloseableAndReportAnyException(inputStream); + closeCloseableAndReportAnyException(uncompressedStream); + closeCloseableAndReportAnyException(decryptedStream); + closeCloseableAndReportAnyException(bufferedInputStream); + closeCloseableAndReportAnyException(bufferedOutputStream); } } @@ -352,6 +350,26 @@ public final class BinaryDictionaryFileDumper { } } + // Ideally the two following methods should be merged, but AssetFileDescriptor does not + // implement Closeable although it does implement #close(), and Java does not have + // structural typing. + private static void closeAssetFileDescriptorAndReportAnyException( + final AssetFileDescriptor file) { + try { + if (null != file) file.close(); + } catch (Exception e) { + Log.e(TAG, "Exception while closing a file", e); + } + } + + private static void closeCloseableAndReportAnyException(final Closeable file) { + try { + if (null != file) file.close(); + } catch (Exception e) { + Log.e(TAG, "Exception while closing a file", e); + } + } + /** * Queries a content provider for word list data for some locale and cache the returned files * @@ -363,8 +381,14 @@ public final class BinaryDictionaryFileDumper { */ public static void cacheWordListsFromContentProvider(final Locale locale, final Context context, final boolean hasDefaultWordList) { - final ContentProviderClient providerClient = context.getContentResolver(). + final ContentProviderClient providerClient; + try { + providerClient = context.getContentResolver(). acquireContentProviderClient(getProviderUriBuilder("").build()); + } catch (final SecurityException e) { + Log.e(TAG, "No permission to communicate with the dictionary provider", e); + return; + } if (null == providerClient) { Log.e(TAG, "Can't establish communication with the dictionary provider"); return; @@ -417,7 +441,6 @@ public final class BinaryDictionaryFileDumper { final ContentProviderClient client, final String clientId) throws RemoteException { final String metadataFileUri = MetadataFileUriGetter.getMetadataUri(context); final String metadataAdditionalId = MetadataFileUriGetter.getMetadataAdditionalId(context); - if (TextUtils.isEmpty(metadataFileUri)) return; // Tell the content provider to reset all information about this client id final Uri metadataContentUri = getProviderUriBuilder(clientId) .appendPath(QUERY_PATH_METADATA) diff --git a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java index 98eadcacb..fa301b5a6 100644 --- a/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java +++ b/java/src/com/android/inputmethod/latin/BinaryDictionaryGetter.java @@ -16,17 +16,17 @@ package com.android.inputmethod.latin; -import com.android.inputmethod.latin.define.ProductionFlag; -import com.android.inputmethod.latin.makedict.BinaryDictInputOutput; -import com.android.inputmethod.latin.makedict.FormatSpec; - import android.content.Context; import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetFileDescriptor; import android.util.Log; +import com.android.inputmethod.latin.makedict.BinaryDictInputOutput; +import com.android.inputmethod.latin.makedict.FormatSpec; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.DictionaryInfoUtils; +import com.android.inputmethod.latin.utils.LocaleUtils; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -39,7 +39,7 @@ import java.util.Locale; /** * Helper class to get the address of a mmap'able dictionary file. */ -final class BinaryDictionaryGetter { +final public class BinaryDictionaryGetter { /** * Used for Log actions from this class @@ -223,14 +223,10 @@ final class BinaryDictionaryGetter { } } - // ## HACK ## we prevent usage of a dictionary before version 18 for English only. The reason - // for this is, since those do not include whitelist entries, the new code with an old version - // of the dictionary would lose whitelist functionality. + // ## HACK ## we prevent usage of a dictionary before version 18. The reason for this is, since + // those do not include whitelist entries, the new code with an old version of the dictionary + // would lose whitelist functionality. private static boolean hackCanUseDictionaryFile(final Locale locale, final File f) { - // Only for English - other languages didn't have a whitelist, hence this - // ad-hoc ## HACK ## - if (!Locale.ENGLISH.getLanguage().equals(locale.getLanguage())) return true; - FileInputStream inStream = null; try { // Read the version of the file @@ -290,17 +286,8 @@ final class BinaryDictionaryGetter { final Context context) { final boolean hasDefaultWordList = DictionaryFactory.isDictionaryAvailable(context, locale); - // TODO: The development-only-diagnostic version is not supported by the Dictionary Pack - // Service yet - if (!ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - // We need internet access to do the following. Only do this if the package actually - // has the permission. - if (context.checkCallingOrSelfPermission(android.Manifest.permission.INTERNET) - == PackageManager.PERMISSION_GRANTED) { - BinaryDictionaryFileDumper.cacheWordListsFromContentProvider(locale, context, - hasDefaultWordList); - } - } + BinaryDictionaryFileDumper.cacheWordListsFromContentProvider(locale, context, + hasDefaultWordList); final File[] cachedWordLists = getCachedWordLists(locale.toString(), context); final String mainDictId = DictionaryInfoUtils.getMainDictId(locale); final DictPackSettings dictPackSettings = new DictPackSettings(context); diff --git a/java/src/com/android/inputmethod/latin/Constants.java b/java/src/com/android/inputmethod/latin/Constants.java index 86bb25562..6d67bdb04 100644 --- a/java/src/com/android/inputmethod/latin/Constants.java +++ b/java/src/com/android/inputmethod/latin/Constants.java @@ -126,15 +126,6 @@ public final class Constants { } } - public static final class Dictionary { - // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h - public static final int MAX_WORD_LENGTH = 48; - - private Dictionary() { - // This utility class is no publicly instantiable. - } - } - public static final int NOT_A_CODE = -1; public static final int NOT_A_COORDINATE = -1; @@ -142,6 +133,10 @@ public final class Constants { public static final int SPELL_CHECKER_COORDINATE = -3; public static final int EXTERNAL_KEYBOARD_COORDINATE = -4; + + // Must be equal to MAX_WORD_LENGTH in native/jni/src/defines.h + public static final int DICTIONARY_MAX_WORD_LENGTH = 48; + public static boolean isValidCoordinate(final int coordinate) { // Detect {@link NOT_A_COORDINATE}, {@link SUGGESTION_STRIP_COORDINATE}, // and {@link SPELL_CHECKER_COORDINATE}. @@ -149,6 +144,13 @@ public final class Constants { } /** + * Custom request code used in + * {@link com.android.inputmethod.keyboard.KeyboardActionListener#onCustomRequest(int)}. + */ + // The code to show input method picker. + public static final int CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER = 1; + + /** * Some common keys code. Must be positive. */ public static final int CODE_ENTER = '\n'; @@ -172,22 +174,23 @@ public final class Constants { /** * Special keys code. Must be negative. - * These should be aligned with KeyboardCodesSet.ID_TO_NAME[], - * KeyboardCodesSet.DEFAULT[] and KeyboardCodesSet.RTL[] + * These should be aligned with {@link KeyboardCodesSet#ID_TO_NAME}, + * {@link KeyboardCodesSet#DEFAULT}, and {@link KeyboardCodesSet#RTL}. */ public static final int CODE_SHIFT = -1; - public static final int CODE_SWITCH_ALPHA_SYMBOL = -2; - public static final int CODE_OUTPUT_TEXT = -3; - public static final int CODE_DELETE = -4; - public static final int CODE_SETTINGS = -5; - public static final int CODE_SHORTCUT = -6; - public static final int CODE_ACTION_NEXT = -7; - public static final int CODE_ACTION_PREVIOUS = -8; - public static final int CODE_LANGUAGE_SWITCH = -9; - public static final int CODE_RESEARCH = -10; - public static final int CODE_SHIFT_ENTER = -11; + public static final int CODE_CAPSLOCK = -2; + public static final int CODE_SWITCH_ALPHA_SYMBOL = -3; + public static final int CODE_OUTPUT_TEXT = -4; + public static final int CODE_DELETE = -5; + public static final int CODE_SETTINGS = -6; + public static final int CODE_SHORTCUT = -7; + public static final int CODE_ACTION_NEXT = -8; + public static final int CODE_ACTION_PREVIOUS = -9; + public static final int CODE_LANGUAGE_SWITCH = -10; + public static final int CODE_RESEARCH = -11; + public static final int CODE_SHIFT_ENTER = -12; // Code value representing the code is not specified. - public static final int CODE_UNSPECIFIED = -12; + public static final int CODE_UNSPECIFIED = -13; public static boolean isLetterCode(final int code) { return code >= CODE_SPACE; @@ -196,6 +199,7 @@ public final class Constants { public static String printableCode(final int code) { switch (code) { case CODE_SHIFT: return "shift"; + case CODE_CAPSLOCK: return "capslock"; case CODE_SWITCH_ALPHA_SYMBOL: return "symbol"; case CODE_OUTPUT_TEXT: return "text"; case CODE_DELETE: return "delete"; @@ -215,10 +219,6 @@ public final class Constants { } } - // Constants for CSV parsing. - public static final char CSV_SEPARATOR = ','; - public static final char CSV_ESCAPE = '\\'; - private Constants() { // This utility class is not publicly instantiable. } diff --git a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java index b9db9a092..c99d0e2ea 100644 --- a/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/ContactsBinaryDictionary.java @@ -30,6 +30,8 @@ import android.provider.ContactsContract.Contacts; import android.text.TextUtils; import android.util.Log; +import com.android.inputmethod.latin.utils.StringUtils; + import java.util.List; import java.util.Locale; @@ -107,7 +109,6 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary { @Override public void loadDictionaryAsync() { - clearFusionDictionary(); loadDeviceAccountsEmailAddresses(); loadDictionaryAsyncForUri(ContactsContract.Profile.CONTENT_URI); // TODO: Switch this URL to the newer ContactsContract too @@ -234,6 +235,11 @@ public class ContactsBinaryDictionary extends ExpandableBinaryDictionary { } @Override + protected boolean needsToReloadBeforeWriting() { + return true; + } + + @Override protected boolean hasContentChanged() { final long startTime = SystemClock.uptimeMillis(); final int contactCount = getContactCount(); diff --git a/java/src/com/android/inputmethod/latin/DicTraverseSession.java b/java/src/com/android/inputmethod/latin/DicTraverseSession.java index 534e2116b..45b281318 100644 --- a/java/src/com/android/inputmethod/latin/DicTraverseSession.java +++ b/java/src/com/android/inputmethod/latin/DicTraverseSession.java @@ -16,6 +16,8 @@ package com.android.inputmethod.latin; +import com.android.inputmethod.latin.utils.JniUtils; + import java.util.Locale; public final class DicTraverseSession { diff --git a/java/src/com/android/inputmethod/latin/Dictionary.java b/java/src/com/android/inputmethod/latin/Dictionary.java index acd7c2aa1..7c3e4a740 100644 --- a/java/src/com/android/inputmethod/latin/Dictionary.java +++ b/java/src/com/android/inputmethod/latin/Dictionary.java @@ -35,8 +35,13 @@ public abstract class Dictionary { public static final String TYPE_CONTACTS = "contacts"; // User dictionary, the system-managed one. public static final String TYPE_USER = "user"; - // User history dictionary internal to LatinIME. + // User history dictionary internal to LatinIME. This assumes bigram prediction for now. public static final String TYPE_USER_HISTORY = "history"; + // Personalization binary dictionary internal to LatinIME. + public static final String TYPE_PERSONALIZATION = "personalization"; + // Personalization prediction dictionary internal to LatinIME's Java code. + public static final String TYPE_PERSONALIZATION_PREDICTION_IN_JAVA = + "personalization_prediction_in_java"; // Spawned by resuming suggestions. Comes from a span that was in the TextView. public static final String TYPE_RESUMED = "resumed"; protected final String mDictType; diff --git a/java/src/com/android/inputmethod/latin/DictionaryCollection.java b/java/src/com/android/inputmethod/latin/DictionaryCollection.java index ed2b44223..d05bb1e55 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryCollection.java +++ b/java/src/com/android/inputmethod/latin/DictionaryCollection.java @@ -16,10 +16,11 @@ package com.android.inputmethod.latin; +import android.util.Log; + import com.android.inputmethod.keyboard.ProximityInfo; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; - -import android.util.Log; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.util.ArrayList; import java.util.Collection; diff --git a/java/src/com/android/inputmethod/latin/DictionaryFactory.java b/java/src/com/android/inputmethod/latin/DictionaryFactory.java index 40e51672a..3721132c5 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryFactory.java +++ b/java/src/com/android/inputmethod/latin/DictionaryFactory.java @@ -21,6 +21,10 @@ import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.util.Log; +import com.android.inputmethod.annotations.UsedForTesting; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.DictionaryInfoUtils; + import java.io.File; import java.util.ArrayList; import java.util.LinkedList; @@ -56,7 +60,8 @@ public final class DictionaryFactory { if (null != assetFileList) { for (final AssetFileAddress f : assetFileList) { final BinaryDictionary binaryDictionary = new BinaryDictionary(f.mFilename, - f.mOffset, f.mLength, useFullEditDistance, locale, Dictionary.TYPE_MAIN); + f.mOffset, f.mLength, useFullEditDistance, locale, Dictionary.TYPE_MAIN, + false /* isUpdatable */); if (binaryDictionary.isValidDictionary()) { dictList.add(binaryDictionary); } @@ -109,7 +114,8 @@ public final class DictionaryFactory { return null; } return new BinaryDictionary(sourceDir, afd.getStartOffset(), afd.getLength(), - false /* useFullEditDistance */, locale, Dictionary.TYPE_MAIN); + false /* useFullEditDistance */, locale, Dictionary.TYPE_MAIN, + false /* isUpdatable */); } catch (android.content.res.Resources.NotFoundException e) { Log.e(TAG, "Could not find the resource"); return null; @@ -126,21 +132,22 @@ public final class DictionaryFactory { /** * Create a dictionary from passed data. This is intended for unit tests only. - * @param dictionary the file to read - * @param startOffset the offset in the file where the data starts - * @param length the length of the data + * @param dictionaryList the list of files to read, with their offsets and lengths * @param useFullEditDistance whether to use the full edit distance in suggestions * @return the created dictionary, or null. */ - public static Dictionary createDictionaryForTest(File dictionary, long startOffset, long length, + @UsedForTesting + public static Dictionary createDictionaryForTest(final AssetFileAddress[] dictionaryList, final boolean useFullEditDistance, Locale locale) { - if (dictionary.isFile()) { - return new BinaryDictionary(dictionary.getAbsolutePath(), startOffset, length, - useFullEditDistance, locale, Dictionary.TYPE_MAIN); - } else { - Log.e(TAG, "Could not find the file. path=" + dictionary.getAbsolutePath()); - return null; + final DictionaryCollection dictionaryCollection = + new DictionaryCollection(Dictionary.TYPE_MAIN); + for (final AssetFileAddress address : dictionaryList) { + final BinaryDictionary binaryDictionary = new BinaryDictionary(address.mFilename, + address.mOffset, address.mLength, useFullEditDistance, locale, + Dictionary.TYPE_MAIN, false /* isUpdatable */); + dictionaryCollection.addDictionary(binaryDictionary); } + return dictionaryCollection; } /** diff --git a/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java b/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java index 56096127e..2dcfdb0b7 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java +++ b/java/src/com/android/inputmethod/latin/DictionaryPackInstallBroadcastReceiver.java @@ -17,6 +17,7 @@ package com.android.inputmethod.latin; import com.android.inputmethod.dictionarypack.DictionaryPackConstants; +import com.android.inputmethod.latin.utils.TargetPackageInfoGetterTask; import android.content.BroadcastReceiver; import android.content.Context; diff --git a/java/src/com/android/inputmethod/latin/DictionaryWriter.java b/java/src/com/android/inputmethod/latin/DictionaryWriter.java new file mode 100644 index 000000000..8be04c1c0 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/DictionaryWriter.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin; + +import android.content.Context; + +import com.android.inputmethod.keyboard.ProximityInfo; +import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; +import com.android.inputmethod.latin.makedict.BinaryDictInputOutput; +import com.android.inputmethod.latin.makedict.FormatSpec; +import com.android.inputmethod.latin.makedict.FusionDictionary; +import com.android.inputmethod.latin.makedict.FusionDictionary.Node; +import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; +import com.android.inputmethod.latin.makedict.UnsupportedFormatException; +import com.android.inputmethod.latin.utils.CollectionUtils; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; + +/** + * An in memory dictionary for memorizing entries and writing a binary dictionary. + */ +public class DictionaryWriter extends AbstractDictionaryWriter { + // TODO: Regenerate version 3 binary dictionary. + private static final int BINARY_DICT_VERSION = 2; + private static final FormatSpec.FormatOptions FORMAT_OPTIONS = + new FormatSpec.FormatOptions(BINARY_DICT_VERSION); + + private FusionDictionary mFusionDictionary; + + public DictionaryWriter(final Context context, final String dictType) { + super(context, dictType); + clear(); + } + + @Override + public void clear() { + final HashMap<String, String> attributes = CollectionUtils.newHashMap(); + mFusionDictionary = new FusionDictionary(new Node(), + new FusionDictionary.DictionaryOptions(attributes, false, false)); + } + + /** + * Adds a word unigram to the fusion dictionary. + */ + // TODO: Create "cache dictionary" to cache fresh words for frequently updated dictionaries, + // considering performance regression. + @Override + public void addUnigramWord(final String word, final String shortcutTarget, final int frequency, + final boolean isNotAWord) { + if (shortcutTarget == null) { + mFusionDictionary.add(word, frequency, null, isNotAWord); + } else { + // TODO: Do this in the subclass, with this class taking an arraylist. + final ArrayList<WeightedString> shortcutTargets = CollectionUtils.newArrayList(); + shortcutTargets.add(new WeightedString(shortcutTarget, frequency)); + mFusionDictionary.add(word, frequency, shortcutTargets, isNotAWord); + } + } + + @Override + public void addBigramWords(final String word0, final String word1, final int frequency, + final boolean isValid) { + mFusionDictionary.setBigram(word0, word1, frequency); + } + + @Override + public void removeBigramWords(final String word0, final String word1) { + // This class don't support removing bigram words. + } + + @Override + protected void writeBinaryDictionary(final FileOutputStream out) + throws IOException, UnsupportedFormatException { + BinaryDictInputOutput.writeDictionaryBinary(out, mFusionDictionary, FORMAT_OPTIONS); + } + + @Override + public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer, + final String prevWord, final ProximityInfo proximityInfo, + boolean blockOffensiveWords) { + // This class doesn't support suggestion. + return null; + } + + @Override + public boolean isValidWord(String word) { + // This class doesn't support dictionary retrieval. + return false; + } +} diff --git a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java index 887d657e9..3f11391ba 100644 --- a/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/ExpandableBinaryDictionary.java @@ -22,19 +22,12 @@ import android.util.Log; import com.android.inputmethod.keyboard.ProximityInfo; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.makedict.BinaryDictInputOutput; -import com.android.inputmethod.latin.makedict.FormatSpec; -import com.android.inputmethod.latin.makedict.FusionDictionary; -import com.android.inputmethod.latin.makedict.FusionDictionary.Node; -import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; -import com.android.inputmethod.latin.makedict.UnsupportedFormatException; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; -import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Abstract base class for an expandable dictionary that can be created and updated dynamically @@ -55,7 +48,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { /** * The maximum length of a word in this dictionary. */ - protected static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH; + protected static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH; /** * A static map of locks, each of which controls access to a single binary dictionary file. They @@ -75,8 +68,8 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { */ private BinaryDictionary mBinaryDictionary; - /** The expandable fusion dictionary used to generate the binary dictionary. */ - private FusionDictionary mFusionDictionary; + /** The in-memory dictionary used to generate the binary dictionary. */ + private AbstractDictionaryWriter mDictionaryWriter; /** * The name of this dictionary, used as the filename for storing the binary dictionary. Multiple @@ -91,10 +84,6 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { /** Controls access to the local binary dictionary for this instance. */ private final DictionaryController mLocalDictionaryController = new DictionaryController(); - private static final int BINARY_DICT_VERSION = 1; - private static final FormatSpec.FormatOptions FORMAT_OPTIONS = - new FormatSpec.FormatOptions(BINARY_DICT_VERSION); - /** * Abstract method for loading the unigrams and bigrams of a given dictionary in a background * thread. @@ -136,7 +125,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { mContext = context; mBinaryDictionary = null; mSharedDictionaryController = getSharedDictionaryController(filename); - clearFusionDictionary(); + mDictionaryWriter = new DictionaryWriter(context, dictType); } protected static String getFilenameWithLocale(final String name, final String localeStr) { @@ -149,53 +138,57 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { @Override public void close() { // Ensure that no other threads are accessing the local binary dictionary. - mLocalDictionaryController.lock(); + mLocalDictionaryController.writeLock().lock(); try { if (mBinaryDictionary != null) { mBinaryDictionary.close(); mBinaryDictionary = null; } + mDictionaryWriter.close(); } finally { - mLocalDictionaryController.unlock(); + mLocalDictionaryController.writeLock().unlock(); } } /** - * Clears the fusion dictionary on the Java side. Note: Does not modify the binary dictionary on - * the native side. + * Adds a word unigram to the dictionary. Used for loading a dictionary. */ - public void clearFusionDictionary() { - final HashMap<String, String> attributes = CollectionUtils.newHashMap(); - mFusionDictionary = new FusionDictionary(new Node(), - new FusionDictionary.DictionaryOptions(attributes, false, false)); + protected void addWord(final String word, final String shortcutTarget, + final int frequency, final boolean isNotAWord) { + mDictionaryWriter.addUnigramWord(word, shortcutTarget, frequency, isNotAWord); } /** - * Adds a word unigram to the fusion dictionary. Call updateBinaryDictionary when all changes - * are done to update the binary dictionary. + * Sets a word bigram in the dictionary. Used for loading a dictionary. */ - // TODO: Create "cache dictionary" to cache fresh words for frequently updated dictionaries, - // considering performance regression. - protected void addWord(final String word, final String shortcutTarget, final int frequency, - final boolean isNotAWord) { - if (shortcutTarget == null) { - mFusionDictionary.add(word, frequency, null, isNotAWord); - } else { - // TODO: Do this in the subclass, with this class taking an arraylist. - final ArrayList<WeightedString> shortcutTargets = CollectionUtils.newArrayList(); - shortcutTargets.add(new WeightedString(shortcutTarget, frequency)); - mFusionDictionary.add(word, frequency, shortcutTargets, isNotAWord); + protected void setBigram(final String prevWord, final String word, final int frequency) { + mDictionaryWriter.addBigramWords(prevWord, word, frequency, true /* isValid */); + } + + /** + * Dynamically adds a word unigram to the dictionary. + */ + protected void addWordDynamically(final String word, final String shortcutTarget, + final int frequency, final boolean isNotAWord) { + mLocalDictionaryController.writeLock().lock(); + try { + mDictionaryWriter.addUnigramWord(word, shortcutTarget, frequency, isNotAWord); + } finally { + mLocalDictionaryController.writeLock().unlock(); } } /** - * Sets a word bigram in the fusion dictionary. Call updateBinaryDictionary when all changes are - * done to update the binary dictionary. + * Dynamically sets a word bigram in the dictionary. */ - // TODO: Create "cache dictionary" to cache fresh bigrams for frequently updated dictionaries, - // considering performance regression. - protected void setBigram(final String prevWord, final String word, final int frequency) { - mFusionDictionary.setBigram(prevWord, word, frequency); + protected void setBigramDynamically(final String prevWord, final String word, + final int frequency) { + mLocalDictionaryController.writeLock().lock(); + try { + mDictionaryWriter.addBigramWords(prevWord, word, frequency, true /* isValid */); + } finally { + mLocalDictionaryController.writeLock().unlock(); + } } @Override @@ -203,14 +196,29 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { final String prevWord, final ProximityInfo proximityInfo, final boolean blockOffensiveWords) { asyncReloadDictionaryIfRequired(); - if (mLocalDictionaryController.tryLock()) { + // Write lock because getSuggestions in native updates session status. + if (mLocalDictionaryController.writeLock().tryLock()) { try { + final ArrayList<SuggestedWordInfo> inMemDictSuggestion = + mDictionaryWriter.getSuggestions(composer, prevWord, proximityInfo, + blockOffensiveWords); if (mBinaryDictionary != null) { - return mBinaryDictionary.getSuggestions(composer, prevWord, proximityInfo, - blockOffensiveWords); + final ArrayList<SuggestedWordInfo> binarySuggestion = + mBinaryDictionary.getSuggestions(composer, prevWord, proximityInfo, + blockOffensiveWords); + if (inMemDictSuggestion == null) { + return binarySuggestion; + } else if (binarySuggestion == null) { + return inMemDictSuggestion; + } else { + binarySuggestion.addAll(binarySuggestion); + return binarySuggestion; + } + } else { + return inMemDictSuggestion; } } finally { - mLocalDictionaryController.unlock(); + mLocalDictionaryController.writeLock().unlock(); } } return null; @@ -223,11 +231,11 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { } protected boolean isValidWordInner(final String word) { - if (mLocalDictionaryController.tryLock()) { + if (mLocalDictionaryController.readLock().tryLock()) { try { return isValidWordLocked(word); } finally { - mLocalDictionaryController.unlock(); + mLocalDictionaryController.readLock().unlock(); } } return false; @@ -238,22 +246,6 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { return mBinaryDictionary.isValidWord(word); } - protected boolean isValidBigram(final String word1, final String word2) { - if (mBinaryDictionary == null) return false; - return mBinaryDictionary.isValidBigram(word1, word2); - } - - protected boolean isValidBigramInner(final String word1, final String word2) { - if (mLocalDictionaryController.tryLock()) { - try { - return isValidBigramLocked(word1, word2); - } finally { - mLocalDictionaryController.unlock(); - } - } - return false; - } - protected boolean isValidBigramLocked(final String word1, final String word2) { if (mBinaryDictionary == null) return false; return mBinaryDictionary.isValidBigram(word1, word2); @@ -272,7 +264,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { * Loads the current binary dictionary from internal storage. Assumes the dictionary file * exists. */ - protected void loadBinaryDictionary() { + private void loadBinaryDictionary() { if (DEBUG) { Log.d(TAG, "Loading binary dictionary: " + mFilename + " request=" + mSharedDictionaryController.mLastUpdateRequestTime + " update=" @@ -285,15 +277,18 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { // Build the new binary dictionary final BinaryDictionary newBinaryDictionary = new BinaryDictionary(filename, 0, length, - true /* useFullEditDistance */, null, mDictType); + true /* useFullEditDistance */, null, mDictType, false /* isUpdatable */); if (mBinaryDictionary != null) { // Ensure all threads accessing the current dictionary have finished before swapping in // the new one. final BinaryDictionary oldBinaryDictionary = mBinaryDictionary; - mLocalDictionaryController.lock(); - mBinaryDictionary = newBinaryDictionary; - mLocalDictionaryController.unlock(); + mLocalDictionaryController.writeLock().lock(); + try { + mBinaryDictionary = newBinaryDictionary; + } finally { + mLocalDictionaryController.writeLock().unlock(); + } oldBinaryDictionary.close(); } else { mBinaryDictionary = newBinaryDictionary; @@ -301,6 +296,12 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { } /** + * Abstract method for checking if it is required to reload the dictionary before writing + * a binary dictionary. + */ + abstract protected boolean needsToReloadBeforeWriting(); + + /** * Generates and writes a new binary dictionary based on the contents of the fusion dictionary. */ private void generateBinaryDictionary() { @@ -309,33 +310,11 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { + mSharedDictionaryController.mLastUpdateRequestTime + " update=" + mSharedDictionaryController.mLastUpdateTime); } - - loadDictionaryAsync(); - - final String tempFileName = mFilename + ".temp"; - final File file = new File(mContext.getFilesDir(), mFilename); - final File tempFile = new File(mContext.getFilesDir(), tempFileName); - FileOutputStream out = null; - try { - out = new FileOutputStream(tempFile); - BinaryDictInputOutput.writeDictionaryBinary(out, mFusionDictionary, FORMAT_OPTIONS); - out.flush(); - out.close(); - tempFile.renameTo(file); - clearFusionDictionary(); - } catch (IOException e) { - Log.e(TAG, "IO exception while writing file", e); - } catch (UnsupportedFormatException e) { - Log.e(TAG, "Unsupported format", e); - } finally { - if (out != null) { - try { - out.close(); - } catch (IOException e) { - // ignore - } - } + if (needsToReloadBeforeWriting()) { + mDictionaryWriter.clear(); + loadDictionaryAsync(); } + mDictionaryWriter.write(mFilename); } /** @@ -388,7 +367,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { private final void syncReloadDictionaryInternal() { // Ensure that only one thread attempts to read or write to the shared binary dictionary // file at the same time. - mSharedDictionaryController.lock(); + mSharedDictionaryController.writeLock().lock(); try { final long time = SystemClock.uptimeMillis(); final boolean dictionaryFileExists = dictionaryFileExists(); @@ -414,9 +393,15 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { // shared dictionary. loadBinaryDictionary(); } + if (mBinaryDictionary != null && !mBinaryDictionary.isValidDictionary()) { + // Binary dictionary is not valid. Regenerate the dictionary file. + mSharedDictionaryController.mLastUpdateTime = time; + generateBinaryDictionary(); + loadBinaryDictionary(); + } mLocalDictionaryController.mLastUpdateTime = time; } finally { - mSharedDictionaryController.unlock(); + mSharedDictionaryController.writeLock().unlock(); } } @@ -441,7 +426,7 @@ abstract public class ExpandableBinaryDictionary extends Dictionary { * dictionary is out of date. Can be shared across multiple dictionary instances that access the * same filename. */ - private static class DictionaryController extends ReentrantLock { + private static class DictionaryController extends ReentrantReadWriteLock { private volatile long mLastUpdateTime = 0; private volatile long mLastUpdateRequestTime = 0; diff --git a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java index 0dabdb835..bd2d70365 100644 --- a/java/src/com/android/inputmethod/latin/ExpandableDictionary.java +++ b/java/src/com/android/inputmethod/latin/ExpandableDictionary.java @@ -22,7 +22,8 @@ import android.util.Log; import com.android.inputmethod.keyboard.ProximityInfo; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.UserHistoryForgettingCurveUtils.ForgettingCurveParams; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.UserHistoryForgettingCurveUtils.ForgettingCurveParams; import java.util.ArrayList; import java.util.LinkedList; @@ -42,7 +43,7 @@ public class ExpandableDictionary extends Dictionary { protected static final int BIGRAM_MAX_FREQUENCY = 255; private Context mContext; - private char[] mWordBuilder = new char[Constants.Dictionary.MAX_WORD_LENGTH]; + private char[] mWordBuilder = new char[Constants.DICTIONARY_MAX_WORD_LENGTH]; private int mMaxDepth; private int mInputLength; @@ -86,7 +87,7 @@ public class ExpandableDictionary extends Dictionary { } } - protected interface NextWord { + public interface NextWord { public Node getWordNode(); public int getFrequency(); public ForgettingCurveParams getFcParams(); @@ -160,7 +161,7 @@ public class ExpandableDictionary extends Dictionary { super(dictType); mContext = context; clearDictionary(); - mCodes = new int[Constants.Dictionary.MAX_WORD_LENGTH][]; + mCodes = new int[Constants.DICTIONARY_MAX_WORD_LENGTH][]; } public void loadDictionary() { @@ -197,11 +198,11 @@ public class ExpandableDictionary extends Dictionary { } public int getMaxWordLength() { - return Constants.Dictionary.MAX_WORD_LENGTH; + return Constants.DICTIONARY_MAX_WORD_LENGTH; } public void addWord(final String word, final String shortcutTarget, final int frequency) { - if (word.length() >= Constants.Dictionary.MAX_WORD_LENGTH) { + if (word.length() >= Constants.DICTIONARY_MAX_WORD_LENGTH) { return; } addWordRec(mRoots, word, 0, shortcutTarget, frequency, null); @@ -257,7 +258,7 @@ public class ExpandableDictionary extends Dictionary { final boolean blockOffensiveWords) { if (reloadDictionaryIfRequired()) return null; if (composer.size() > 1) { - if (composer.size() >= Constants.Dictionary.MAX_WORD_LENGTH) { + if (composer.size() >= Constants.DICTIONARY_MAX_WORD_LENGTH) { return null; } final ArrayList<SuggestedWordInfo> suggestions = @@ -628,7 +629,7 @@ public class ExpandableDictionary extends Dictionary { } // Local to reverseLookUp, but do not allocate each time. - private final char[] mLookedUpString = new char[Constants.Dictionary.MAX_WORD_LENGTH]; + private final char[] mLookedUpString = new char[Constants.DICTIONARY_MAX_WORD_LENGTH]; /** * reverseLookUp retrieves the full word given a list of terminal nodes and adds those words @@ -643,7 +644,7 @@ public class ExpandableDictionary extends Dictionary { for (NextWord nextWord : terminalNodes) { node = nextWord.getWordNode(); freq = nextWord.getFrequency(); - int index = Constants.Dictionary.MAX_WORD_LENGTH; + int index = Constants.DICTIONARY_MAX_WORD_LENGTH; do { --index; mLookedUpString[index] = node.mCode; @@ -655,7 +656,7 @@ public class ExpandableDictionary extends Dictionary { // to ignore the word in this case. if (freq >= 0 && node == null) { suggestions.add(new SuggestedWordInfo(new String(mLookedUpString, index, - Constants.Dictionary.MAX_WORD_LENGTH - index), + Constants.DICTIONARY_MAX_WORD_LENGTH - index), freq, SuggestedWordInfo.KIND_CORRECTION, mDictType)); } } @@ -727,172 +728,206 @@ public class ExpandableDictionary extends Dictionary { * to their base characters. If c is in range, BASE_CHARS[c] == c * if c is not a combined character, or the base character if it * is combined. + * + * cf. native/jni/src/utils/char_utils.cpp */ private static final char BASE_CHARS[] = { - 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, - 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, - 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, - 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, - 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, - 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, - 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, - 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, - 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, - 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, - 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, - 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, - 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, - 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, - 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, - 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, - 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, - 0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f, - 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, - 0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f, - 0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, - 0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020, - 0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7, - 0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf, - 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043, - 0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049, - 0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7, - 0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f - // Manually changed df to 73 - 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063, - 0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069, - 0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7, - 0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f - 0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063, - 0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064, - 0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065, - 0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067, - 0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127, - 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, - 0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b, - 0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, - 0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e, - 0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f, - 0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072, - 0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073, - 0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167, - 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, - 0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079, - 0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073, - 0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187, - 0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f, - 0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197, - 0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f, - 0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7, - 0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055, - 0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7, - 0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf, - 0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c, - 0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049, - 0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc, - 0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4, - 0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067, - 0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292, - 0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7, - 0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8, - 0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065, - 0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f, - 0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075, - 0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068, - 0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061, - 0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f, - 0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237, - 0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f, - 0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247, - 0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f, - 0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257, - 0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f, - 0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267, - 0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f, - 0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277, - 0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f, - 0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287, - 0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f, - 0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297, - 0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f, - 0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7, - 0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af, - 0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077, - 0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf, - 0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7, - 0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf, - 0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7, - 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df, - 0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7, - 0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef, - 0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7, - 0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff, - 0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307, - 0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f, - 0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317, - 0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f, - 0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327, - 0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f, - 0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337, - 0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f, - 0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347, - 0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f, - 0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357, - 0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f, - 0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, - 0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f, - 0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377, - 0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f, - 0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7, - 0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9, - 0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, - 0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f, - 0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7, - 0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9, - 0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7, - 0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf, - 0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7, - 0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf, - 0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7, - 0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df, - 0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7, - 0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef, - 0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7, - 0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff, - 0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406, - 0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f, - 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, - 0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f, - 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, - 0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f, - 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, - 0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f, - 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, - 0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f, - 0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456, - 0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f, - 0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467, - 0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f, - 0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475, - 0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f, - 0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, - 0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f, - 0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497, - 0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f, - 0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7, - 0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af, - 0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7, - 0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf, - 0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7, - 0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf, - 0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435, - 0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437, - 0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e, - 0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443, - 0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7, - 0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff, + /* U+0000 */ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, + /* U+0008 */ 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, + /* U+0010 */ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, + /* U+0018 */ 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, + /* U+0020 */ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, + /* U+0028 */ 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, + /* U+0030 */ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, + /* U+0038 */ 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, + /* U+0040 */ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, + /* U+0048 */ 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, + /* U+0050 */ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, + /* U+0058 */ 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, + /* U+0060 */ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, + /* U+0068 */ 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, + /* U+0070 */ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, + /* U+0078 */ 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, + /* U+0080 */ 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, + /* U+0088 */ 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, + /* U+0090 */ 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, + /* U+0098 */ 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, + /* U+00A0 */ 0x0020, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, + /* U+00A8 */ 0x0020, 0x00A9, 0x0061, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0020, + /* U+00B0 */ 0x00B0, 0x00B1, 0x0032, 0x0033, 0x0020, 0x03BC, 0x00B6, 0x00B7, + /* U+00B8 */ 0x0020, 0x0031, 0x006F, 0x00BB, 0x0031, 0x0031, 0x0033, 0x00BF, + /* U+00C0 */ 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00C6, 0x0043, + /* U+00C8 */ 0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049, + /* U+00D0 */ 0x00D0, 0x004E, 0x004F, 0x004F, 0x004F, 0x004F, 0x004F, 0x00D7, + /* U+00D8 */ 0x004F, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00DE, 0x0073, + // U+00D8: Manually changed from 00D8 to 004F + // TODO: Check if it's really acceptable to consider Ø a diacritical variant of O + // U+00DF: Manually changed from 00DF to 0073 + /* U+00E0 */ 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00E6, 0x0063, + /* U+00E8 */ 0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069, + /* U+00F0 */ 0x00F0, 0x006E, 0x006F, 0x006F, 0x006F, 0x006F, 0x006F, 0x00F7, + /* U+00F8 */ 0x006F, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00FE, 0x0079, + // U+00F8: Manually changed from 00F8 to 006F + // TODO: Check if it's really acceptable to consider ø a diacritical variant of o + /* U+0100 */ 0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063, + /* U+0108 */ 0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064, + /* U+0110 */ 0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065, + /* U+0118 */ 0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067, + /* U+0120 */ 0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127, + /* U+0128 */ 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, + /* U+0130 */ 0x0049, 0x0131, 0x0049, 0x0069, 0x004A, 0x006A, 0x004B, 0x006B, + /* U+0138 */ 0x0138, 0x004C, 0x006C, 0x004C, 0x006C, 0x004C, 0x006C, 0x004C, + /* U+0140 */ 0x006C, 0x004C, 0x006C, 0x004E, 0x006E, 0x004E, 0x006E, 0x004E, + // U+0141: Manually changed from 0141 to 004C + // U+0142: Manually changed from 0142 to 006C + /* U+0148 */ 0x006E, 0x02BC, 0x014A, 0x014B, 0x004F, 0x006F, 0x004F, 0x006F, + /* U+0150 */ 0x004F, 0x006F, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072, + /* U+0158 */ 0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073, + /* U+0160 */ 0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167, + /* U+0168 */ 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, + /* U+0170 */ 0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079, + /* U+0178 */ 0x0059, 0x005A, 0x007A, 0x005A, 0x007A, 0x005A, 0x007A, 0x0073, + /* U+0180 */ 0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187, + /* U+0188 */ 0x0188, 0x0189, 0x018A, 0x018B, 0x018C, 0x018D, 0x018E, 0x018F, + /* U+0190 */ 0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197, + /* U+0198 */ 0x0198, 0x0199, 0x019A, 0x019B, 0x019C, 0x019D, 0x019E, 0x019F, + /* U+01A0 */ 0x004F, 0x006F, 0x01A2, 0x01A3, 0x01A4, 0x01A5, 0x01A6, 0x01A7, + /* U+01A8 */ 0x01A8, 0x01A9, 0x01AA, 0x01AB, 0x01AC, 0x01AD, 0x01AE, 0x0055, + /* U+01B0 */ 0x0075, 0x01B1, 0x01B2, 0x01B3, 0x01B4, 0x01B5, 0x01B6, 0x01B7, + /* U+01B8 */ 0x01B8, 0x01B9, 0x01BA, 0x01BB, 0x01BC, 0x01BD, 0x01BE, 0x01BF, + /* U+01C0 */ 0x01C0, 0x01C1, 0x01C2, 0x01C3, 0x0044, 0x0044, 0x0064, 0x004C, + /* U+01C8 */ 0x004C, 0x006C, 0x004E, 0x004E, 0x006E, 0x0041, 0x0061, 0x0049, + /* U+01D0 */ 0x0069, 0x004F, 0x006F, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, + // U+01D5: Manually changed from 00DC to 0055 + // U+01D6: Manually changed from 00FC to 0075 + // U+01D7: Manually changed from 00DC to 0055 + /* U+01D8 */ 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x01DD, 0x0041, 0x0061, + // U+01D8: Manually changed from 00FC to 0075 + // U+01D9: Manually changed from 00DC to 0055 + // U+01DA: Manually changed from 00FC to 0075 + // U+01DB: Manually changed from 00DC to 0055 + // U+01DC: Manually changed from 00FC to 0075 + // U+01DE: Manually changed from 00C4 to 0041 + // U+01DF: Manually changed from 00E4 to 0061 + /* U+01E0 */ 0x0041, 0x0061, 0x00C6, 0x00E6, 0x01E4, 0x01E5, 0x0047, 0x0067, + // U+01E0: Manually changed from 0226 to 0041 + // U+01E1: Manually changed from 0227 to 0061 + /* U+01E8 */ 0x004B, 0x006B, 0x004F, 0x006F, 0x004F, 0x006F, 0x01B7, 0x0292, + // U+01EC: Manually changed from 01EA to 004F + // U+01ED: Manually changed from 01EB to 006F + /* U+01F0 */ 0x006A, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01F6, 0x01F7, + /* U+01F8 */ 0x004E, 0x006E, 0x0041, 0x0061, 0x00C6, 0x00E6, 0x004F, 0x006F, + // U+01FA: Manually changed from 00C5 to 0041 + // U+01FB: Manually changed from 00E5 to 0061 + // U+01FE: Manually changed from 00D8 to 004F + // TODO: Check if it's really acceptable to consider Ø a diacritical variant of O + // U+01FF: Manually changed from 00F8 to 006F + // TODO: Check if it's really acceptable to consider ø a diacritical variant of o + /* U+0200 */ 0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065, + /* U+0208 */ 0x0049, 0x0069, 0x0049, 0x0069, 0x004F, 0x006F, 0x004F, 0x006F, + /* U+0210 */ 0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075, + /* U+0218 */ 0x0053, 0x0073, 0x0054, 0x0074, 0x021C, 0x021D, 0x0048, 0x0068, + /* U+0220 */ 0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061, + /* U+0228 */ 0x0045, 0x0065, 0x004F, 0x006F, 0x004F, 0x006F, 0x004F, 0x006F, + // U+022A: Manually changed from 00D6 to 004F + // U+022B: Manually changed from 00F6 to 006F + // U+022C: Manually changed from 00D5 to 004F + // U+022D: Manually changed from 00F5 to 006F + /* U+0230 */ 0x004F, 0x006F, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237, + // U+0230: Manually changed from 022E to 004F + // U+0231: Manually changed from 022F to 006F + /* U+0238 */ 0x0238, 0x0239, 0x023A, 0x023B, 0x023C, 0x023D, 0x023E, 0x023F, + /* U+0240 */ 0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247, + /* U+0248 */ 0x0248, 0x0249, 0x024A, 0x024B, 0x024C, 0x024D, 0x024E, 0x024F, + /* U+0250 */ 0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257, + /* U+0258 */ 0x0258, 0x0259, 0x025A, 0x025B, 0x025C, 0x025D, 0x025E, 0x025F, + /* U+0260 */ 0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267, + /* U+0268 */ 0x0268, 0x0269, 0x026A, 0x026B, 0x026C, 0x026D, 0x026E, 0x026F, + /* U+0270 */ 0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277, + /* U+0278 */ 0x0278, 0x0279, 0x027A, 0x027B, 0x027C, 0x027D, 0x027E, 0x027F, + /* U+0280 */ 0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287, + /* U+0288 */ 0x0288, 0x0289, 0x028A, 0x028B, 0x028C, 0x028D, 0x028E, 0x028F, + /* U+0290 */ 0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297, + /* U+0298 */ 0x0298, 0x0299, 0x029A, 0x029B, 0x029C, 0x029D, 0x029E, 0x029F, + /* U+02A0 */ 0x02A0, 0x02A1, 0x02A2, 0x02A3, 0x02A4, 0x02A5, 0x02A6, 0x02A7, + /* U+02A8 */ 0x02A8, 0x02A9, 0x02AA, 0x02AB, 0x02AC, 0x02AD, 0x02AE, 0x02AF, + /* U+02B0 */ 0x0068, 0x0266, 0x006A, 0x0072, 0x0279, 0x027B, 0x0281, 0x0077, + /* U+02B8 */ 0x0079, 0x02B9, 0x02BA, 0x02BB, 0x02BC, 0x02BD, 0x02BE, 0x02BF, + /* U+02C0 */ 0x02C0, 0x02C1, 0x02C2, 0x02C3, 0x02C4, 0x02C5, 0x02C6, 0x02C7, + /* U+02C8 */ 0x02C8, 0x02C9, 0x02CA, 0x02CB, 0x02CC, 0x02CD, 0x02CE, 0x02CF, + /* U+02D0 */ 0x02D0, 0x02D1, 0x02D2, 0x02D3, 0x02D4, 0x02D5, 0x02D6, 0x02D7, + /* U+02D8 */ 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02DE, 0x02DF, + /* U+02E0 */ 0x0263, 0x006C, 0x0073, 0x0078, 0x0295, 0x02E5, 0x02E6, 0x02E7, + /* U+02E8 */ 0x02E8, 0x02E9, 0x02EA, 0x02EB, 0x02EC, 0x02ED, 0x02EE, 0x02EF, + /* U+02F0 */ 0x02F0, 0x02F1, 0x02F2, 0x02F3, 0x02F4, 0x02F5, 0x02F6, 0x02F7, + /* U+02F8 */ 0x02F8, 0x02F9, 0x02FA, 0x02FB, 0x02FC, 0x02FD, 0x02FE, 0x02FF, + /* U+0300 */ 0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307, + /* U+0308 */ 0x0308, 0x0309, 0x030A, 0x030B, 0x030C, 0x030D, 0x030E, 0x030F, + /* U+0310 */ 0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317, + /* U+0318 */ 0x0318, 0x0319, 0x031A, 0x031B, 0x031C, 0x031D, 0x031E, 0x031F, + /* U+0320 */ 0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327, + /* U+0328 */ 0x0328, 0x0329, 0x032A, 0x032B, 0x032C, 0x032D, 0x032E, 0x032F, + /* U+0330 */ 0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337, + /* U+0338 */ 0x0338, 0x0339, 0x033A, 0x033B, 0x033C, 0x033D, 0x033E, 0x033F, + /* U+0340 */ 0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347, + /* U+0348 */ 0x0348, 0x0349, 0x034A, 0x034B, 0x034C, 0x034D, 0x034E, 0x034F, + /* U+0350 */ 0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357, + /* U+0358 */ 0x0358, 0x0359, 0x035A, 0x035B, 0x035C, 0x035D, 0x035E, 0x035F, + /* U+0360 */ 0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, + /* U+0368 */ 0x0368, 0x0369, 0x036A, 0x036B, 0x036C, 0x036D, 0x036E, 0x036F, + /* U+0370 */ 0x0370, 0x0371, 0x0372, 0x0373, 0x02B9, 0x0375, 0x0376, 0x0377, + /* U+0378 */ 0x0378, 0x0379, 0x0020, 0x037B, 0x037C, 0x037D, 0x003B, 0x037F, + /* U+0380 */ 0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00A8, 0x0391, 0x00B7, + /* U+0388 */ 0x0395, 0x0397, 0x0399, 0x038B, 0x039F, 0x038D, 0x03A5, 0x03A9, + /* U+0390 */ 0x03CA, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, + /* U+0398 */ 0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, + /* U+03A0 */ 0x03A0, 0x03A1, 0x03A2, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, + /* U+03A8 */ 0x03A8, 0x03A9, 0x0399, 0x03A5, 0x03B1, 0x03B5, 0x03B7, 0x03B9, + /* U+03B0 */ 0x03CB, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, + /* U+03B8 */ 0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF, + /* U+03C0 */ 0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7, + /* U+03C8 */ 0x03C8, 0x03C9, 0x03B9, 0x03C5, 0x03BF, 0x03C5, 0x03C9, 0x03CF, + /* U+03D0 */ 0x03B2, 0x03B8, 0x03A5, 0x03D2, 0x03D2, 0x03C6, 0x03C0, 0x03D7, + /* U+03D8 */ 0x03D8, 0x03D9, 0x03DA, 0x03DB, 0x03DC, 0x03DD, 0x03DE, 0x03DF, + /* U+03E0 */ 0x03E0, 0x03E1, 0x03E2, 0x03E3, 0x03E4, 0x03E5, 0x03E6, 0x03E7, + /* U+03E8 */ 0x03E8, 0x03E9, 0x03EA, 0x03EB, 0x03EC, 0x03ED, 0x03EE, 0x03EF, + /* U+03F0 */ 0x03BA, 0x03C1, 0x03C2, 0x03F3, 0x0398, 0x03B5, 0x03F6, 0x03F7, + /* U+03F8 */ 0x03F8, 0x03A3, 0x03FA, 0x03FB, 0x03FC, 0x03FD, 0x03FE, 0x03FF, + /* U+0400 */ 0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406, + /* U+0408 */ 0x0408, 0x0409, 0x040A, 0x040B, 0x041A, 0x0418, 0x0423, 0x040F, + /* U+0410 */ 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, + /* U+0418 */ 0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F, + // U+0419: Manually changed from 0418 to 0419 + /* U+0420 */ 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, + /* U+0428 */ 0x0428, 0x0429, 0x042C, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F, + // U+042A: Manually changed from 042A to 042C + /* U+0430 */ 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, + /* U+0438 */ 0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F, + // U+0439: Manually changed from 0438 to 0439 + /* U+0440 */ 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, + /* U+0448 */ 0x0448, 0x0449, 0x044C, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, + // U+044A: Manually changed from 044A to 044C + /* U+0450 */ 0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456, + /* U+0458 */ 0x0458, 0x0459, 0x045A, 0x045B, 0x043A, 0x0438, 0x0443, 0x045F, + /* U+0460 */ 0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467, + /* U+0468 */ 0x0468, 0x0469, 0x046A, 0x046B, 0x046C, 0x046D, 0x046E, 0x046F, + /* U+0470 */ 0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475, + /* U+0478 */ 0x0478, 0x0479, 0x047A, 0x047B, 0x047C, 0x047D, 0x047E, 0x047F, + /* U+0480 */ 0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, + /* U+0488 */ 0x0488, 0x0489, 0x048A, 0x048B, 0x048C, 0x048D, 0x048E, 0x048F, + /* U+0490 */ 0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497, + /* U+0498 */ 0x0498, 0x0499, 0x049A, 0x049B, 0x049C, 0x049D, 0x049E, 0x049F, + /* U+04A0 */ 0x04A0, 0x04A1, 0x04A2, 0x04A3, 0x04A4, 0x04A5, 0x04A6, 0x04A7, + /* U+04A8 */ 0x04A8, 0x04A9, 0x04AA, 0x04AB, 0x04AC, 0x04AD, 0x04AE, 0x04AF, + /* U+04B0 */ 0x04B0, 0x04B1, 0x04B2, 0x04B3, 0x04B4, 0x04B5, 0x04B6, 0x04B7, + /* U+04B8 */ 0x04B8, 0x04B9, 0x04BA, 0x04BB, 0x04BC, 0x04BD, 0x04BE, 0x04BF, + /* U+04C0 */ 0x04C0, 0x0416, 0x0436, 0x04C3, 0x04C4, 0x04C5, 0x04C6, 0x04C7, + /* U+04C8 */ 0x04C8, 0x04C9, 0x04CA, 0x04CB, 0x04CC, 0x04CD, 0x04CE, 0x04CF, + /* U+04D0 */ 0x0410, 0x0430, 0x0410, 0x0430, 0x04D4, 0x04D5, 0x0415, 0x0435, + /* U+04D8 */ 0x04D8, 0x04D9, 0x04D8, 0x04D9, 0x0416, 0x0436, 0x0417, 0x0437, + /* U+04E0 */ 0x04E0, 0x04E1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041E, 0x043E, + /* U+04E8 */ 0x04E8, 0x04E9, 0x04E8, 0x04E9, 0x042D, 0x044D, 0x0423, 0x0443, + /* U+04F0 */ 0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04F6, 0x04F7, + /* U+04F8 */ 0x042B, 0x044B, 0x04FA, 0x04FB, 0x04FC, 0x04FD, 0x04FE, 0x04FF, }; - - // generated with: - // cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }' - } diff --git a/java/src/com/android/inputmethod/latin/InputAttributes.java b/java/src/com/android/inputmethod/latin/InputAttributes.java index dd58db575..21b103e5a 100644 --- a/java/src/com/android/inputmethod/latin/InputAttributes.java +++ b/java/src/com/android/inputmethod/latin/InputAttributes.java @@ -20,6 +20,9 @@ import android.text.InputType; import android.util.Log; import android.view.inputmethod.EditorInfo; +import com.android.inputmethod.latin.utils.InputTypeUtils; +import com.android.inputmethod.latin.utils.StringUtils; + /** * Class to hold attributes of the input field. */ @@ -199,6 +202,6 @@ public final class InputAttributes { if (editorInfo == null) return false; final String findingKey = (packageName != null) ? packageName + "." + key : key; - return StringUtils.containsInCsv(findingKey, editorInfo.privateImeOptions); + return StringUtils.containsInCommaSplittableText(findingKey, editorInfo.privateImeOptions); } } diff --git a/java/src/com/android/inputmethod/latin/InputPointers.java b/java/src/com/android/inputmethod/latin/InputPointers.java index 81c833000..e96a46e12 100644 --- a/java/src/com/android/inputmethod/latin/InputPointers.java +++ b/java/src/com/android/inputmethod/latin/InputPointers.java @@ -17,6 +17,7 @@ package com.android.inputmethod.latin; import com.android.inputmethod.annotations.UsedForTesting; +import com.android.inputmethod.latin.utils.ResizableIntArray; import android.util.Log; diff --git a/java/src/com/android/inputmethod/latin/LastComposedWord.java b/java/src/com/android/inputmethod/latin/LastComposedWord.java index 826dc11e7..642b3a4da 100644 --- a/java/src/com/android/inputmethod/latin/LastComposedWord.java +++ b/java/src/com/android/inputmethod/latin/LastComposedWord.java @@ -16,6 +16,8 @@ package com.android.inputmethod.latin; +import com.android.inputmethod.latin.utils.StringUtils; + import android.text.TextUtils; /** @@ -47,7 +49,7 @@ public final class LastComposedWord { public final String mPrevWord; public final int mCapitalizedMode; public final InputPointers mInputPointers = - new InputPointers(Constants.Dictionary.MAX_WORD_LENGTH); + new InputPointers(Constants.DICTIONARY_MAX_WORD_LENGTH); private boolean mActive; diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index c464a7067..719c7c81f 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -43,7 +43,6 @@ import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.text.InputType; -import android.text.SpannableString; import android.text.TextUtils; import android.text.style.SuggestionSpan; import android.util.Log; @@ -74,11 +73,29 @@ import com.android.inputmethod.keyboard.KeyboardActionListener; import com.android.inputmethod.keyboard.KeyboardId; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.MainKeyboardView; -import com.android.inputmethod.latin.RichInputConnection.Range; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.Utils.Stats; import com.android.inputmethod.latin.define.ProductionFlag; +import com.android.inputmethod.latin.personalization.PersonalizationDictionaryHelper; +import com.android.inputmethod.latin.personalization.PersonalizationPredictionDictionary; +import com.android.inputmethod.latin.personalization.UserHistoryPredictionDictionary; +import com.android.inputmethod.latin.settings.Settings; +import com.android.inputmethod.latin.settings.SettingsActivity; +import com.android.inputmethod.latin.settings.SettingsValues; import com.android.inputmethod.latin.suggestions.SuggestionStripView; +import com.android.inputmethod.latin.utils.ApplicationUtils; +import com.android.inputmethod.latin.utils.AutoCorrectionUtils; +import com.android.inputmethod.latin.utils.CapsModeUtils; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.CompletionInfoUtils; +import com.android.inputmethod.latin.utils.InputTypeUtils; +import com.android.inputmethod.latin.utils.IntentUtils; +import com.android.inputmethod.latin.utils.JniUtils; +import com.android.inputmethod.latin.utils.LatinImeLoggerUtils; +import com.android.inputmethod.latin.utils.PositionalInfoForUserDictPendingAddition; +import com.android.inputmethod.latin.utils.RecapitalizeStatus; +import com.android.inputmethod.latin.utils.StaticInnerHandlerWrapper; +import com.android.inputmethod.latin.utils.TargetPackageInfoGetterTask; +import com.android.inputmethod.latin.utils.TextRange; import com.android.inputmethod.research.ResearchLogger; import java.io.FileDescriptor; @@ -139,7 +156,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private SuggestionStripView mSuggestionStripView; // Never null private SuggestedWords mSuggestedWords = SuggestedWords.EMPTY; - @UsedForTesting Suggest mSuggest; + private Suggest mSuggest; private CompletionInfo[] mApplicationSpecifiedCompletions; private AppWorkaroundsUtils mAppWorkAroundsUtils = new AppWorkaroundsUtils(); @@ -153,7 +170,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private boolean mIsMainDictionaryAvailable; private UserBinaryDictionary mUserDictionary; - private UserHistoryDictionary mUserHistoryDictionary; + private UserHistoryPredictionDictionary mUserHistoryPredictionDictionary; + private PersonalizationPredictionDictionary mPersonalizationPredictionDictionary; private boolean mIsUserDictionaryAvailable; private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; @@ -179,11 +197,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private int mDisplayOrientation; // Object for reacting to adding/removing a dictionary pack. - // TODO: The development-only-diagnostic version is not supported by the Dictionary Pack - // Service yet. private BroadcastReceiver mDictionaryPackInstallReceiver = - ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS - ? null : new DictionaryPackInstallBroadcastReceiver(this); + new DictionaryPackInstallBroadcastReceiver(this); // Keeps track of most recently inserted text (multi-character key) for reverting private String mEnteredText; @@ -204,6 +219,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private static final int MSG_UPDATE_SUGGESTION_STRIP = 2; private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3; private static final int MSG_RESUME_SUGGESTIONS = 4; + private static final int MSG_REOPEN_DICTIONARIES = 5; private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1; @@ -244,6 +260,13 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen case MSG_RESUME_SUGGESTIONS: latinIme.restartSuggestionsOnWordTouchedByCursor(); break; + case MSG_REOPEN_DICTIONARIES: + latinIme.initSuggest(); + // In theory we could call latinIme.updateSuggestionStrip() right away, but + // in the practice, the dictionary is not finished opening yet so we wouldn't + // get any suggestions. Wait one frame. + postUpdateSuggestionStrip(); + break; } } @@ -251,6 +274,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions); } + public void postReopenDictionaries() { + sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES)); + } + public void postResumeSuggestions() { removeMessages(MSG_RESUME_SUGGESTIONS); sendMessageDelayed(obtainMessage(MSG_RESUME_SUGGESTIONS), mDelayUpdateSuggestions); @@ -264,6 +291,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen return hasMessages(MSG_UPDATE_SUGGESTION_STRIP); } + public boolean hasPendingReopenDictionaries() { + return hasMessages(MSG_REOPEN_DICTIONARIES); + } + public void postUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState); @@ -416,6 +447,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } + // Loading the native library eagerly to avoid unexpected UnsatisfiedLinkError at the initial + // JNI call as much as possible. + static { + JniUtils.loadNativeLibrary(); + } + public LatinIME() { super(); mSettings = Settings.getInstance(); @@ -458,19 +495,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, filter); - // TODO: The development-only-diagnostic version is not supported by the Dictionary Pack - // Service yet. - if (!ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - final IntentFilter packageFilter = new IntentFilter(); - packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); - packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); - packageFilter.addDataScheme(SCHEME_PACKAGE); - registerReceiver(mDictionaryPackInstallReceiver, packageFilter); + final IntentFilter packageFilter = new IntentFilter(); + packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); + packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); + packageFilter.addDataScheme(SCHEME_PACKAGE); + registerReceiver(mDictionaryPackInstallReceiver, packageFilter); - final IntentFilter newDictFilter = new IntentFilter(); - newDictFilter.addAction(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION); - registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); - } + final IntentFilter newDictFilter = new IntentFilter(); + newDictFilter.addAction(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION); + registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); } // Has to be package-visible for unit tests @@ -480,8 +513,18 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final InputAttributes inputAttributes = new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode()); mSettings.loadSettings(locale, inputAttributes); - // May need to reset the contacts dictionary depending on the user settings. - resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary()); + AudioAndHapticFeedbackManager.getInstance().onSettingsChanged(mSettings.getCurrent()); + // To load the keyboard we need to load all the settings once, but resetting the + // contacts dictionary should be deferred until after the new layout has been displayed + // to improve responsivity. In the language switching process, we post a reopenDictionaries + // message, then come here to read the settings for the new language before we change + // the layout; at this time, we need to skip resetting the contacts dictionary. It will + // be done later inside {@see #initSuggest()} when the reopenDictionaries message is + // processed. + if (!mHandler.hasPendingReopenDictionaries()) { + // May need to reset the contacts dictionary depending on the user settings. + resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary()); + } } // Note that this method is called from a non-UI thread. @@ -498,33 +541,35 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); final String localeStr = subtypeLocale.toString(); - final ContactsBinaryDictionary oldContactsDictionary; - if (mSuggest != null) { - oldContactsDictionary = mSuggest.getContactsDictionary(); - mSuggest.close(); - } else { - oldContactsDictionary = null; - } - mSuggest = new Suggest(this /* Context */, subtypeLocale, + final Suggest newSuggest = new Suggest(this /* Context */, subtypeLocale, this /* SuggestInitializationListener */); - if (mSettings.getCurrent().mCorrectionEnabled) { - mSuggest.setAutoCorrectionThreshold(mSettings.getCurrent().mAutoCorrectionThreshold); + final SettingsValues settingsValues = mSettings.getCurrent(); + if (settingsValues.mCorrectionEnabled) { + newSuggest.setAutoCorrectionThreshold(settingsValues.mAutoCorrectionThreshold); } mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.getInstance().initSuggest(mSuggest); + ResearchLogger.getInstance().initSuggest(newSuggest); } mUserDictionary = new UserBinaryDictionary(this, localeStr); mIsUserDictionaryAvailable = mUserDictionary.isEnabled(); - mSuggest.setUserDictionary(mUserDictionary); - - resetContactsDictionary(oldContactsDictionary); + newSuggest.setUserDictionary(mUserDictionary); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); - mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, prefs); - mSuggest.setUserHistoryDictionary(mUserHistoryDictionary); + + mUserHistoryPredictionDictionary = PersonalizationDictionaryHelper + .getUserHistoryPredictionDictionary(this, localeStr, prefs); + newSuggest.setUserHistoryPredictionDictionary(mUserHistoryPredictionDictionary); + mPersonalizationPredictionDictionary = PersonalizationDictionaryHelper + .getPersonalizationPredictionDictionary(this, localeStr, prefs); + newSuggest.setPersonalizationPredictionDictionary(mPersonalizationPredictionDictionary); + + final Suggest oldSuggest = mSuggest; + resetContactsDictionary(null != oldSuggest ? oldSuggest.getContactsDictionary() : null); + mSuggest = newSuggest; + if (oldSuggest != null) oldSuggest.close(); } /** @@ -536,8 +581,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen * @param oldContactsDictionary an optional dictionary to use, or null */ private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) { + final Suggest suggest = mSuggest; final boolean shouldSetDictionary = - (null != mSuggest && mSettings.getCurrent().mUseContactsDict); + (null != suggest && mSettings.getCurrent().mUseContactsDict); final ContactsBinaryDictionary dictionaryToUse; if (!shouldSetDictionary) { @@ -564,8 +610,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } - if (null != mSuggest) { - mSuggest.setContactsDictionary(dictionaryToUse); + if (null != suggest) { + suggest.setContactsDictionary(dictionaryToUse); } } @@ -577,8 +623,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen @Override public void onDestroy() { - if (mSuggest != null) { - mSuggest.close(); + final Suggest suggest = mSuggest; + if (suggest != null) { + suggest.close(); mSuggest = null; } mSettings.onDestroy(); @@ -586,11 +633,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { ResearchLogger.getInstance().onDestroy(); } - // TODO: The development-only-diagnostic version is not supported by the Dictionary Pack - // Service yet. - if (!ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - unregisterReceiver(mDictionaryPackInstallReceiver); - } + unregisterReceiver(mDictionaryPackInstallReceiver); LatinImeLogger.commit(); LatinImeLogger.onDestroy(); super.onDestroy(); @@ -676,7 +719,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen super.onStartInputView(editorInfo, restarting); final KeyboardSwitcher switcher = mKeyboardSwitcher; final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); - final SettingsValues currentSettings = mSettings.getCurrent(); + // If we are starting input in a different text field from before, we'll have to reload + // settings, so currentSettingsValues can't be final. + SettingsValues currentSettingsValues = mSettings.getCurrent(); if (editorInfo == null) { Log.e(TAG, "Null EditorInfo in onStartInputView()"); @@ -731,7 +776,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); } - final boolean inputTypeChanged = !currentSettings.isSameInputType(editorInfo); + final boolean inputTypeChanged = !currentSettingsValues.isSameInputType(editorInfo); final boolean isDifferentTextField = !restarting || inputTypeChanged; if (isDifferentTextField) { mSubtypeSwitcher.updateParametersOnStartInputView(); @@ -746,6 +791,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // span, so we should reset our state unconditionally, even if restarting is true. mEnteredText = null; resetComposingState(true /* alsoResetLastComposedWord */); + if (isDifferentTextField) mHandler.postResumeSuggestions(); mDeleteCount = 0; mSpaceState = SPACE_STATE_NONE; mRecapitalizeStatus.deactivate(); @@ -753,7 +799,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // Note: the following does a round-trip IPC on the main thread: be careful final Locale currentLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); - if (null != mSuggest && null != currentLocale && !currentLocale.equals(mSuggest.mLocale)) { + final Suggest suggest = mSuggest; + if (null != suggest && null != currentLocale && !currentLocale.equals(suggest.mLocale)) { initSuggest(); } if (mSuggestionStripView != null) { @@ -769,12 +816,13 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (isDifferentTextField) { mainKeyboardView.closing(); loadSettings(); + currentSettingsValues = mSettings.getCurrent(); - if (mSuggest != null && currentSettings.mCorrectionEnabled) { - mSuggest.setAutoCorrectionThreshold(currentSettings.mAutoCorrectionThreshold); + if (suggest != null && currentSettingsValues.mCorrectionEnabled) { + suggest.setAutoCorrectionThreshold(currentSettingsValues.mAutoCorrectionThreshold); } - switcher.loadKeyboard(editorInfo, currentSettings); + switcher.loadKeyboard(editorInfo, currentSettingsValues); } else if (restarting) { // TODO: Come up with a more comprehensive way to reset the keyboard layout when // a keyboard layout set doesn't get reloaded in this method. @@ -795,14 +843,14 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mHandler.cancelDoubleSpacePeriodTimer(); mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable); - mainKeyboardView.setKeyPreviewPopupEnabled(currentSettings.mKeyPreviewPopupOn, - currentSettings.mKeyPreviewPopupDismissDelay); + mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn, + currentSettingsValues.mKeyPreviewPopupDismissDelay); mainKeyboardView.setSlidingKeyInputPreviewEnabled( - currentSettings.mSlidingKeyInputPreviewEnabled); + currentSettingsValues.mSlidingKeyInputPreviewEnabled); mainKeyboardView.setGestureHandlingEnabledByUser( - currentSettings.mGestureInputEnabled); - mainKeyboardView.setGesturePreviewMode(currentSettings.mGesturePreviewTrailEnabled, - currentSettings.mGestureFloatingPreviewTextEnabled); + currentSettingsValues.mGestureInputEnabled); + mainKeyboardView.setGesturePreviewMode(currentSettingsValues.mGesturePreviewTrailEnabled, + currentSettingsValues.mGestureFloatingPreviewTextEnabled); // If we have a user dictionary addition in progress, we should check now if we should // replace the previously committed string with the word that has actually been added @@ -850,11 +898,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mKeyboardSwitcher.onFinishInputView(); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { - mainKeyboardView.cancelAllMessages(); + mainKeyboardView.cancelAllOngoingEvents(); + mainKeyboardView.deallocateMemory(); } // Remove pending messages related to update suggestions mHandler.cancelUpdateSuggestionStrip(); + // Should do the following in onFinishInputInternal but until JB MR2 it's not called :( + if (mWordComposer.isComposingWord()) mConnection.finishComposingText(); resetComposingState(true /* alsoResetLastComposedWord */); + mRichImm.clearSubtypeCaches(); // Notify ResearchLogger if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { ResearchLogger.latinIME_onFinishInputViewInternal(finishingInput, mLastSelectionStart, @@ -891,20 +943,17 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } } - // TODO: refactor the following code to be less contrived. - // "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means - // that the cursor is not at the end of the composing span, or there is a selection. - // "mLastSelectionStart != newSelStart" means that the cursor is not in the same place - // as last time we were called (if there is a selection, it means the start hasn't - // changed, so it's the end that did). - final boolean selectionChanged = (newSelStart != composingSpanEnd - || newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart; + final boolean selectionChanged = mLastSelectionStart != newSelStart + || mLastSelectionEnd != newSelEnd; + // if composingSpanStart and composingSpanEnd are -1, it means there is no composing // span in the view - we can use that to narrow down whether the cursor was moved // by us or not. If we are composing a word but there is no composing span, then // we know for sure the cursor moved while we were composing and we should reset - // the state. + // the state. TODO: rescind this policy: the framework never removes the composing + // span on its own accord while editing. This test is useless. final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1; + // If the keyboard is not visible, we don't need to do all the housekeeping work, as it // will be reset when the keyboard shows up anyway. // TODO: revisit this when LatinIME supports hardware keyboards. @@ -926,7 +975,14 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // state-related special processing to kick in. mSpaceState = SPACE_STATE_NONE; - if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) { + // TODO: is it still necessary to test for composingSpan related stuff? + final boolean selectionChangedOrSafeToReset = selectionChanged + || (!mWordComposer.isComposingWord()) || noComposingSpan; + final boolean hasOrHadSelection = (oldSelStart != oldSelEnd + || newSelStart != newSelEnd); + final int moveAmount = newSelStart - oldSelStart; + if (selectionChangedOrSafeToReset && (hasOrHadSelection + || !mWordComposer.moveCursorByAndReturnIfInsideComposingWord(moveAmount))) { // If we are composing a word and moving the cursor, we would want to set a // suggestion span for recorrection to work correctly. Unfortunately, that // would involve the keyboard committing some new text, which would move the @@ -937,6 +993,13 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // text, but that is probably too expensive to do, so we decided to leave things // as is. resetEntireInputState(newSelStart); + } else { + // resetEntireInputState calls resetCachesUponCursorMove, but with the second + // argument as true. But in all cases where we don't reset the entire input state, + // we still want to tell the rich input connection about the new cursor position so + // that it can update its caches. + mConnection.resetCachesUponCursorMove(newSelStart, + false /* shouldFinishComposition */); } // We moved the cursor. If we are touching a word, we need to resume suggestion, @@ -1160,10 +1223,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private void resetEntireInputState(final int newCursorPosition) { final boolean shouldFinishComposition = mWordComposer.isComposingWord(); resetComposingState(true /* alsoResetLastComposedWord */); - if (mSettings.getCurrent().mBigramPredictionEnabled) { + final SettingsValues settingsValues = mSettings.getCurrent(); + if (settingsValues.mBigramPredictionEnabled) { clearSuggestionStrip(); } else { - setSuggestedWords(mSettings.getCurrent().mSuggestPuncList, false); + setSuggestedWords(settingsValues.mSuggestPuncList, false); } mConnection.resetCachesUponCursorMove(newCursorPosition, shouldFinishComposition); } @@ -1237,8 +1301,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } private boolean maybeDoubleSpacePeriod() { - if (!mSettings.getCurrent().mCorrectionEnabled) return false; - if (!mSettings.getCurrent().mUseDoubleSpacePeriod) return false; + final SettingsValues settingsValues = mSettings.getCurrent(); + if (!settingsValues.mCorrectionEnabled) return false; + if (!settingsValues.mUseDoubleSpacePeriod) return false; if (!mHandler.isAcceptingDoubleSpacePeriod()) return false; final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 @@ -1314,14 +1379,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen showSubtypeSelectorAndSettings(); } - // Virtual codes representing custom requests. These are used in onCustomRequest() below. - public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1; - @Override public boolean onCustomRequest(final int requestCode) { if (isShowingOptionDialog()) return false; switch (requestCode) { - case CODE_SHOW_INPUT_METHOD_PICKER: + case Constants.CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER: if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { mRichImm.getInputMethodManager().showInputMethodPicker(); return true; @@ -1418,8 +1480,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen LatinImeLogger.logOnDelete(x, y); break; case Constants.CODE_SHIFT: - // Note: calling back to the keyboard on Shift key is handled in onPressKey() - // and onReleaseKey(). + // Note: Calling back to the keyboard on Shift key is handled in + // {@link #onPressKey(int,boolean)} and {@link #onReleaseKey(int,boolean)}. final Keyboard currentKeyboard = switcher.getKeyboard(); if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) { // TODO: Instead of checking for alphabetic keyboard here, separate keycodes for @@ -1427,9 +1489,13 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen handleRecapitalize(); } break; + case Constants.CODE_CAPSLOCK: + // Note: Changing keyboard to shift lock state is handled in + // {@link KeyboardSwitcher#onCodeInput(int)}. + break; case Constants.CODE_SWITCH_ALPHA_SYMBOL: - // Note: calling back to the keyboard on symbol key is handled in onPressKey() - // and onReleaseKey(). + // Note: Calling back to the keyboard on symbol key is handled in + // {@link #onPressKey(int,boolean)} and {@link #onReleaseKey(int,boolean)}. break; case Constants.CODE_SETTINGS: onSettingsKeyPressed(); @@ -1482,8 +1548,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen break; } switcher.onCodeInput(primaryCode); - // Reset after any single keystroke, except shift and symbol-shift + // Reset after any single keystroke, except shift, capslock, and symbol-shift if (!didAutoCorrect && primaryCode != Constants.CODE_SHIFT + && primaryCode != Constants.CODE_CAPSLOCK && primaryCode != Constants.CODE_SWITCH_ALPHA_SYMBOL) mLastComposedWord.deactivate(); if (Constants.CODE_DELETE != primaryCode) { @@ -1496,14 +1563,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final int spaceState) { mSpaceState = SPACE_STATE_NONE; final boolean didAutoCorrect; - if (mSettings.getCurrent().isWordSeparator(primaryCode)) { + final SettingsValues settingsValues = mSettings.getCurrent(); + if (settingsValues.isWordSeparator(primaryCode)) { didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState); } else { didAutoCorrect = false; if (SPACE_STATE_PHANTOM == spaceState) { - if (mSettings.isInternal()) { + if (settingsValues.mIsInternal) { if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) { - Stats.onAutoCorrection( + LatinImeLoggerUtils.onAutoCorrection( "", mWordComposer.getTypedWord(), " ", mWordComposer); } } @@ -1561,10 +1629,12 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen BatchInputUpdater.getInstance().onStartBatchInput(this); mHandler.cancelUpdateSuggestionStrip(); mConnection.beginBatchEdit(); + final SettingsValues settingsValues = mSettings.getCurrent(); if (mWordComposer.isComposingWord()) { - if (mSettings.isInternal()) { + if (settingsValues.mIsInternal) { if (mWordComposer.isBatchMode()) { - Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer); + LatinImeLoggerUtils.onAutoCorrection( + "", mWordComposer.getTypedWord(), " ", mWordComposer); } } final int wordComposerSize = mWordComposer.size(); @@ -1590,7 +1660,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); if (Character.isLetterOrDigit(codePointBeforeCursor) - || mSettings.getCurrent().isUsuallyFollowedBySpace(codePointBeforeCursor)) { + || settingsValues.isUsuallyFollowedBySpace(codePointBeforeCursor)) { mSpaceState = SPACE_STATE_PHANTOM; } mConnection.endBatchEdit(); @@ -1635,8 +1705,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen public void onStartBatchInput(final LatinIME latinIme) { synchronized (mLock) { mHandler.removeMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); - mLatinIme = latinIme; mInBatchInput = true; + mLatinIme = latinIme; + mLatinIme.mHandler.showGesturePreviewAndSuggestionStrip( + SuggestedWords.EMPTY, false /* dismissGestureFloatingPreviewText */); } } @@ -1795,8 +1867,6 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { final String word = mWordComposer.getTypedWord(); ResearchLogger.latinIME_handleBackspace_batch(word, 1); - ResearchLogger.getInstance().uncommitCurrentLogUnit( - word, false /* dumpCurrentLogUnit */); } final String rejectedSuggestion = mWordComposer.getTypedWord(); mWordComposer.reset(); @@ -1810,9 +1880,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mConnection.deleteSurroundingText(1, 0); } } else { + final SettingsValues currentSettings = mSettings.getCurrent(); if (mLastComposedWord.canRevertCommit()) { - if (mSettings.isInternal()) { - Stats.onAutoCorrectionCancellation(); + if (currentSettings.mIsInternal) { + LatinImeLoggerUtils.onAutoCorrectionCancellation(); } revertCommit(); return; @@ -1823,6 +1894,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // like the smiley key or the .com key. final int length = mEnteredText.length(); mConnection.deleteSurroundingText(length, 0); + if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { + ResearchLogger.latinIME_handleBackspace_cancelTextInput(mEnteredText); + } mEnteredText = null; // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. // In addition we know that spaceState is false, and that we should not be @@ -1856,7 +1930,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mLastSelectionEnd = mLastSelectionStart; mConnection.deleteSurroundingText(numCharsDeleted, 0); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.latinIME_handleBackspace(numCharsDeleted); + ResearchLogger.latinIME_handleBackspace(numCharsDeleted, + false /* shouldUncommitLogUnit */); } } else { // There is no selection, just delete one character. @@ -1874,16 +1949,17 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen mConnection.deleteSurroundingText(1, 0); } if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.latinIME_handleBackspace(1); + ResearchLogger.latinIME_handleBackspace(1, true /* shouldUncommitLogUnit */); } if (mDeleteCount > DELETE_ACCELERATE_AT) { mConnection.deleteSurroundingText(1, 0); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.latinIME_handleBackspace(1); + ResearchLogger.latinIME_handleBackspace(1, + true /* shouldUncommitLogUnit */); } } } - if (mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) { + if (currentSettings.isSuggestionsRequested(mDisplayOrientation)) { restartSuggestionsOnWordBeforeCursorIfAtEndOfWord(); } } @@ -1900,8 +1976,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } if ((SPACE_STATE_WEAK == spaceState || SPACE_STATE_SWAP_PUNCTUATION == spaceState) && isFromSuggestionStrip) { - if (mSettings.getCurrent().isUsuallyPrecededBySpace(code)) return false; - if (mSettings.getCurrent().isUsuallyFollowedBySpace(code)) return true; + final SettingsValues currentSettings = mSettings.getCurrent(); + if (currentSettings.isUsuallyPrecededBySpace(code)) return false; + if (currentSettings.isUsuallyFollowedBySpace(code)) return true; mConnection.removeTrailingSpace(); } return false; @@ -1913,8 +1990,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // TODO: remove isWordConnector() and use isUsuallyFollowedBySpace() instead. // See onStartBatchInput() to see how to do it. - if (SPACE_STATE_PHANTOM == spaceState && - !mSettings.getCurrent().isWordConnector(primaryCode)) { + final SettingsValues currentSettings = mSettings.getCurrent(); + if (SPACE_STATE_PHANTOM == spaceState && !currentSettings.isWordConnector(primaryCode)) { if (isComposingWord) { // Sanity check throw new RuntimeException("Should not be composing here"); @@ -1932,9 +2009,9 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // dozen milliseconds. Avoid calling it as much as possible, since we are on the UI // thread here. if (!isComposingWord && (isAlphabet(primaryCode) - || mSettings.getCurrent().isWordConnector(primaryCode)) - && mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation) && - !mConnection.isCursorTouchingWord(mSettings.getCurrent())) { + || currentSettings.isWordConnector(primaryCode)) + && currentSettings.isSuggestionsRequested(mDisplayOrientation) && + !mConnection.isCursorTouchingWord(currentSettings)) { // Reset entirely the composing state anyway, then start composing a new word unless // the character is a single quote. The idea here is, single quote is not a // separator and it should be treated as a normal character, except in the first @@ -1977,8 +2054,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint(); } mHandler.postUpdateSuggestionStrip(); - if (mSettings.isInternal()) { - Utils.Stats.onNonSeparator((char)primaryCode, x, y); + if (currentSettings.mIsInternal) { + LatinImeLoggerUtils.onNonSeparator((char)primaryCode, x, y); } } @@ -1990,9 +2067,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final CharSequence selectedText = mConnection.getSelectedText(0 /* flags, 0 for no styles */); if (TextUtils.isEmpty(selectedText)) return; // Race condition with the input connection + final SettingsValues currentSettings = mSettings.getCurrent(); mRecapitalizeStatus.initialize(mLastSelectionStart, mLastSelectionEnd, - selectedText.toString(), mSettings.getCurrentLocale(), - mSettings.getWordSeparators()); + selectedText.toString(), currentSettings.mLocale, + currentSettings.mWordSeparators); // We trim leading and trailing whitespace. mRecapitalizeStatus.trim(); // Trimming the object may have changed the length of the string, and we need to @@ -2020,17 +2098,15 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // Returns true if we did an autocorrection, false otherwise. private boolean handleSeparator(final int primaryCode, final int x, final int y, final int spaceState) { - if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.latinIME_handleSeparator(primaryCode, mWordComposer.isComposingWord()); - } boolean didAutoCorrect = false; if (mWordComposer.isCursorFrontOrMiddleOfComposingWord()) { // If we are in the middle of a recorrection, we need to commit the recorrection // first so that we can insert the separator at the current cursor position. resetEntireInputState(mLastSelectionStart); } + final SettingsValues currentSettings = mSettings.getCurrent(); if (mWordComposer.isComposingWord()) { - if (mSettings.getCurrent().mCorrectionEnabled) { + if (currentSettings.mCorrectionEnabled) { // TODO: maybe cache Strings in an <String> sparse array or something commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1)); didAutoCorrect = true; @@ -2043,13 +2119,16 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen Constants.SUGGESTION_STRIP_COORDINATE == x); if (SPACE_STATE_PHANTOM == spaceState && - mSettings.getCurrent().isUsuallyPrecededBySpace(primaryCode)) { + currentSettings.isUsuallyPrecededBySpace(primaryCode)) { promotePhantomSpace(); } + if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { + ResearchLogger.latinIME_handleSeparator(primaryCode, mWordComposer.isComposingWord()); + } sendKeyCodePoint(primaryCode); if (Constants.CODE_SPACE == primaryCode) { - if (mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) { + if (currentSettings.isSuggestionsRequested(mDisplayOrientation)) { if (maybeDoubleSpacePeriod()) { mSpaceState = SPACE_STATE_DOUBLE; } else if (!isShowingPunctuationList()) { @@ -2064,7 +2143,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen swapSwapperAndSpace(); mSpaceState = SPACE_STATE_SWAP_PUNCTUATION; } else if (SPACE_STATE_PHANTOM == spaceState - && mSettings.getCurrent().isUsuallyFollowedBySpace(primaryCode)) { + && currentSettings.isUsuallyFollowedBySpace(primaryCode)) { // If we are in phantom space state, and the user presses a separator, we want to // stay in phantom space state so that the next keypress has a chance to add the // space. For example, if I type "Good dat", pick "day" from the suggestion strip @@ -2082,8 +2161,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // already displayed or not, so it's okay. setPunctuationSuggestions(); } - if (mSettings.isInternal()) { - Utils.Stats.onSeparator((char)primaryCode, x, y); + if (currentSettings.mIsInternal) { + LatinImeLoggerUtils.onSeparator((char)primaryCode, x, y); } mKeyboardSwitcher.updateShiftState(); @@ -2115,17 +2194,18 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } private boolean isSuggestionsStripVisible() { + final SettingsValues currentSettings = mSettings.getCurrent(); if (mSuggestionStripView == null) return false; if (mSuggestionStripView.isShowingAddToDictionaryHint()) return true; - if (null == mSettings.getCurrent()) + if (null == currentSettings) return false; - if (!mSettings.getCurrent().isSuggestionStripVisibleInOrientation(mDisplayOrientation)) + if (!currentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation)) return false; - if (mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) + if (currentSettings.isApplicationSpecifiedCompletionsOn()) return true; - return mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation); + return currentSettings.isSuggestionsRequested(mDisplayOrientation); } private void clearSuggestionStrip() { @@ -2158,10 +2238,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private void updateSuggestionStrip() { mHandler.cancelUpdateSuggestionStrip(); + final SettingsValues currentSettings = mSettings.getCurrent(); // Check if we have a suggestion engine attached. if (mSuggest == null - || !mSettings.getCurrent().isSuggestionsRequested(mDisplayOrientation)) { + || !currentSettings.isSuggestionsRequested(mDisplayOrientation)) { if (mWordComposer.isComposingWord()) { Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not " + "requested!"); @@ -2169,7 +2250,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen return; } - if (!mWordComposer.isComposingWord() && !mSettings.getCurrent().mBigramPredictionEnabled) { + if (!mWordComposer.isComposingWord() && !currentSettings.mBigramPredictionEnabled) { setPunctuationSuggestions(); return; } @@ -2182,19 +2263,21 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private SuggestedWords getSuggestedWords(final int sessionId) { final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); - if (keyboard == null || mSuggest == null) { + final Suggest suggest = mSuggest; + if (keyboard == null || suggest == null) { return SuggestedWords.EMPTY; } // Get the word on which we should search the bigrams. If we are composing a word, it's // whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we // should just skip whitespace if any, so 1. // TODO: this is slow (2-way IPC) - we should probably cache this instead. + final SettingsValues currentSettings = mSettings.getCurrent(); final String prevWord = - mConnection.getNthPreviousWord(mSettings.getCurrent().mWordSeparators, + mConnection.getNthPreviousWord(currentSettings.mWordSeparators, mWordComposer.isComposingWord() ? 2 : 1); - return mSuggest.getSuggestedWords(mWordComposer, prevWord, keyboard.getProximityInfo(), - mSettings.getBlockPotentiallyOffensive(), - mSettings.getCurrent().mCorrectionEnabled, sessionId); + return suggest.getSuggestedWords(mWordComposer, prevWord, keyboard.getProximityInfo(), + currentSettings.mBlockPotentiallyOffensive, + currentSettings.mCorrectionEnabled, sessionId); } private SuggestedWords getSuggestedWordsOrOlderSuggestions(final int sessionId) { @@ -2272,7 +2355,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen + "is empty? Impossible! I must commit suicide."); } if (mSettings.isInternal()) { - Stats.onAutoCorrection(typedWord, autoCorrection, separatorString, mWordComposer); + LatinImeLoggerUtils.onAutoCorrection( + typedWord, autoCorrection, separatorString, mWordComposer); } if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { final SuggestedWords suggestedWords = mSuggestedWords; @@ -2319,18 +2403,19 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } mConnection.beginBatchEdit(); + final SettingsValues currentSettings = mSettings.getCurrent(); if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0 // In the batch input mode, a manually picked suggested word should just replace // the current batch input text and there is no need for a phantom space. && !mWordComposer.isBatchMode()) { final int firstChar = Character.codePointAt(suggestion, 0); - if (!mSettings.getCurrent().isWordSeparator(firstChar) - || mSettings.getCurrent().isUsuallyPrecededBySpace(firstChar)) { + if (!currentSettings.isWordSeparator(firstChar) + || currentSettings.isUsuallyPrecededBySpace(firstChar)) { promotePhantomSpace(); } } - if (mSettings.getCurrent().isApplicationSpecifiedCompletionsOn() + if (currentSettings.isApplicationSpecifiedCompletionsOn() && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { mSuggestedWords = SuggestedWords.EMPTY; @@ -2354,7 +2439,8 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen LastComposedWord.NOT_A_SEPARATOR); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion, - mWordComposer.isBatchMode()); + mWordComposer.isBatchMode(), suggestionInfo.mScore, suggestionInfo.mKind, + suggestionInfo.mSourceDict); } mConnection.endBatchEdit(); // Don't allow cancellation of manual pick @@ -2367,18 +2453,21 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen // AND it's in none of our current dictionaries (main, user or otherwise). // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint + final Suggest suggest = mSuggest; final boolean showingAddToDictionaryHint = - SuggestedWordInfo.KIND_TYPED == suggestionInfo.mKind && mSuggest != null - // If the suggestion is not in the dictionary, the hint should be shown. - && !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true); - - if (mSettings.isInternal()) { - Stats.onSeparator((char)Constants.CODE_SPACE, + (SuggestedWordInfo.KIND_TYPED == suggestionInfo.mKind + || SuggestedWordInfo.KIND_OOV_CORRECTION == suggestionInfo.mKind) + && suggest != null + // If the suggestion is not in the dictionary, the hint should be shown. + && !AutoCorrectionUtils.isValidWord(suggest, suggestion, true); + + if (currentSettings.mIsInternal) { + LatinImeLoggerUtils.onSeparator((char)Constants.CODE_SPACE, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); } if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) { mSuggestionStripView.showAddToDictionaryHint( - suggestion, mSettings.getCurrent().mHintToSaveText); + suggestion, currentSettings.mHintToSaveText); } else { // If we're not showing the "Touch again to save", then update the suggestion strip. mHandler.postUpdateSuggestionStrip(); @@ -2404,10 +2493,11 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } private void setPunctuationSuggestions() { - if (mSettings.getCurrent().mBigramPredictionEnabled) { + final SettingsValues currentSettings = mSettings.getCurrent(); + if (currentSettings.mBigramPredictionEnabled) { clearSuggestionStrip(); } else { - setSuggestedWords(mSettings.getCurrent().mSuggestPuncList, false); + setSuggestedWords(currentSettings.mSuggestPuncList, false); } setAutoCorrectionIndicator(false); setSuggestionStripShown(isSuggestionsStripVisible()); @@ -2415,21 +2505,20 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen private String addToUserHistoryDictionary(final String suggestion) { if (TextUtils.isEmpty(suggestion)) return null; - if (mSuggest == null) return null; + final Suggest suggest = mSuggest; + if (suggest == null) return null; // If correction is not enabled, we don't add words to the user history dictionary. // That's to avoid unintended additions in some sensitive fields, or fields that // expect to receive non-words. - if (!mSettings.getCurrent().mCorrectionEnabled) return null; + final SettingsValues currentSettings = mSettings.getCurrent(); + if (!currentSettings.mCorrectionEnabled) return null; - final Suggest suggest = mSuggest; - final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary; - if (suggest == null || userHistoryDictionary == null) { - // Avoid concurrent issue - return null; - } - final String prevWord - = mConnection.getNthPreviousWord(mSettings.getCurrent().mWordSeparators, 2); + final UserHistoryPredictionDictionary userHistoryPredictionDictionary = + mUserHistoryPredictionDictionary; + if (userHistoryPredictionDictionary == null) return null; + + final String prevWord = mConnection.getNthPreviousWord(currentSettings.mWordSeparators, 2); final String secondWord; if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) { secondWord = suggestion.toLowerCase(mSubtypeSwitcher.getCurrentSubtypeLocale()); @@ -2438,10 +2527,10 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } // We demote unrecognized words (frequency < 0, below) by specifying them as "invalid". // We don't add words with 0-frequency (assuming they would be profanity etc.). - final int maxFreq = AutoCorrection.getMaxFrequency( + final int maxFreq = AutoCorrectionUtils.getMaxFrequency( suggest.getUnigramDictionaries(), suggestion); if (maxFreq == 0) return null; - userHistoryDictionary.addToUserHistory(prevWord, secondWord, maxFreq > 0); + userHistoryPredictionDictionary.addToUserHistory(prevWord, secondWord, maxFreq > 0); return prevWord; } @@ -2458,35 +2547,34 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (mLastSelectionStart != mLastSelectionEnd) return; // If we don't know the cursor location, return. if (mLastSelectionStart < 0) return; - if (!mConnection.isCursorTouchingWord(mSettings.getCurrent())) return; - final Range range = mConnection.getWordRangeAtCursor(mSettings.getWordSeparators(), + final SettingsValues currentSettings = mSettings.getCurrent(); + if (!mConnection.isCursorTouchingWord(currentSettings)) return; + final TextRange range = mConnection.getWordRangeAtCursor(currentSettings.mWordSeparators, 0 /* additionalPrecedingWordsCount */); if (null == range) return; // Happens if we don't have an input connection at all // If for some strange reason (editor bug or so) we measure the text before the cursor as // longer than what the entire text is supposed to be, the safe thing to do is bail out. - if (range.mCharsBefore > mLastSelectionStart) return; + final int numberOfCharsInWordBeforeCursor = range.getNumberOfCharsInWordBeforeCursor(); + if (numberOfCharsInWordBeforeCursor > mLastSelectionStart) return; final ArrayList<SuggestedWordInfo> suggestions = CollectionUtils.newArrayList(); final String typedWord = range.mWord.toString(); - if (range.mWord instanceof SpannableString) { - final SpannableString spannableString = (SpannableString)range.mWord; - int i = 0; - for (Object object : spannableString.getSpans(0, spannableString.length(), - SuggestionSpan.class)) { - SuggestionSpan span = (SuggestionSpan)object; - for (String s : span.getSuggestions()) { - ++i; - if (!TextUtils.equals(s, typedWord)) { - suggestions.add(new SuggestedWordInfo(s, - SuggestionStripView.MAX_SUGGESTIONS - i, - SuggestedWordInfo.KIND_RESUMED, Dictionary.TYPE_RESUMED)); - } + int i = 0; + for (final SuggestionSpan span : range.getSuggestionSpansAtWord()) { + for (final String s : span.getSuggestions()) { + ++i; + if (!TextUtils.equals(s, typedWord)) { + suggestions.add(new SuggestedWordInfo(s, + SuggestionStripView.MAX_SUGGESTIONS - i, + SuggestedWordInfo.KIND_RESUMED, Dictionary.TYPE_RESUMED)); } } } mWordComposer.setComposingWord(typedWord, mKeyboardSwitcher.getKeyboard()); - mWordComposer.setCursorPositionWithinWord(range.mCharsBefore); - mConnection.setComposingRegion(mLastSelectionStart - range.mCharsBefore, - mLastSelectionEnd + range.mCharsAfter); + // TODO: this is in chars but the callee expects code points! + mWordComposer.setCursorPositionWithinWord(numberOfCharsInWordBeforeCursor); + mConnection.setComposingRegion( + mLastSelectionStart - numberOfCharsInWordBeforeCursor, + mLastSelectionEnd + range.getNumberOfCharsInWordAfterCursor()); final SuggestedWords suggestedWords; if (suggestions.isEmpty()) { // We come here if there weren't any suggestion spans on this word. We will try to @@ -2575,18 +2663,16 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen } mConnection.deleteSurroundingText(deleteLength, 0); if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) { - mUserHistoryDictionary.cancelAddingUserHistory(previousWord, committedWord); + mUserHistoryPredictionDictionary.cancelAddingUserHistory(previousWord, committedWord); } mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1); if (mSettings.isInternal()) { - Stats.onSeparator(mLastComposedWord.mSeparatorString, + LatinImeLoggerUtils.onSeparator(mLastComposedWord.mSeparatorString, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); } if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { ResearchLogger.latinIME_revertCommit(committedWord, originallyTypedWord, mWordComposer.isBatchMode(), mLastComposedWord.mSeparatorString); - ResearchLogger.getInstance().uncommitCurrentLogUnit(committedWord, - true /* dumpCurrentLogUnit */); } // Don't restart suggestion yet. We'll restart if the user deletes the // separator. @@ -2599,45 +2685,54 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen public void promotePhantomSpace() { if (mSettings.getCurrent().shouldInsertSpacesAutomatically() && !mConnection.textBeforeCursorLooksLikeURL()) { - sendKeyCodePoint(Constants.CODE_SPACE); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { ResearchLogger.latinIME_promotePhantomSpace(); } + sendKeyCodePoint(Constants.CODE_SPACE); } } - // Used by the RingCharBuffer - public boolean isWordSeparator(final int code) { - return mSettings.getCurrent().isWordSeparator(code); - } - // TODO: Make this private // Outside LatinIME, only used by the {@link InputTestsBase} test suite. @UsedForTesting void loadKeyboard() { - // TODO: Why are we calling {@link #loadSettings()} and {@link #initSuggest()} in a - // different order than in {@link #onStartInputView}? - initSuggest(); + // Since we are switching languages, the most urgent thing is to let the keyboard graphics + // update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on + // the screen. Anything we do right now will delay this, so wait until the next frame + // before we do the rest, like reopening dictionaries and updating suggestions. So we + // post a message. + mHandler.postReopenDictionaries(); loadSettings(); if (mKeyboardSwitcher.getMainKeyboardView() != null) { // Reload keyboard because the current language has been changed. mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent()); } - // Since we just changed languages, we should re-evaluate suggestions with whatever word - // we are currently composing. If we are not composing anything, we may want to display - // predictions or punctuation signs (which is done by the updateSuggestionStrip anyway). - mHandler.postUpdateSuggestionStrip(); } - // Callback called by PointerTracker through the KeyboardActionListener. This is called when a - // key is depressed; release matching call is onReleaseKey below. + private void hapticAndAudioFeedback(final int code, final boolean isRepeatKey) { + final MainKeyboardView keyboardView = mKeyboardSwitcher.getMainKeyboardView(); + if (keyboardView != null && keyboardView.isInSlidingKeyInput()) { + // No need to feedback while sliding input. + return; + } + if (isRepeatKey && code == Constants.CODE_DELETE && !mConnection.canDeleteCharacters()) { + // No need to feedback when repeating delete key will have no effect. + return; + } + AudioAndHapticFeedbackManager.getInstance().hapticAndAudioFeedback(code, keyboardView); + } + + // Callback of the {@link KeyboardActionListener}. This is called when a key is depressed; + // release matching call is {@link #onReleaseKey(int,boolean)} below. @Override - public void onPressKey(final int primaryCode, final boolean isSinglePointer) { + public void onPressKey(final int primaryCode, final boolean isRepeatKey, + final boolean isSinglePointer) { mKeyboardSwitcher.onPressKey(primaryCode, isSinglePointer); + hapticAndAudioFeedback(primaryCode, isRepeatKey); } - // Callback by PointerTracker through the KeyboardActionListener. This is called when a key - // is released; press matching call is onPressKey above. + // Callback of the {@link KeyboardActionListener}. This is called when a key is released; + // press matching call is {@link #onPressKey(int,boolean,boolean)} above. @Override public void onReleaseKey(final int primaryCode, final boolean withSliding) { mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding); @@ -2703,7 +2798,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { mSubtypeSwitcher.onNetworkStateChanged(intent); } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { - mKeyboardSwitcher.onRingerModeChanged(); + AudioAndHapticFeedbackManager.getInstance().onRingerModeChanged(); } } }; @@ -2734,7 +2829,7 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen final CharSequence[] items = new CharSequence[] { // TODO: Should use new string "Select active input modes". getString(R.string.language_selection_title), - getString(Utils.getAcitivityTitleResId(this, SettingsActivity.class)), + getString(ApplicationUtils.getAcitivityTitleResId(this, SettingsActivity.class)), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override @@ -2787,6 +2882,18 @@ public class LatinIME extends InputMethodService implements KeyboardActionListen return mSuggestedWords.size() > 0 ? mSuggestedWords.getWord(0) : null; } + // DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME. + @UsedForTesting + /* package for test */ boolean isCurrentlyWaitingForMainDictionary() { + return mSuggest.isCurrentlyWaitingForMainDictionary(); + } + + // DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME. + @UsedForTesting + /* package for test */ boolean hasMainDictionary() { + return mSuggest.hasMainDictionary(); + } + public void debugDumpStateAndCrashWithException(final String context) { final StringBuilder s = new StringBuilder(mAppWorkAroundsUtils.toString()); s.append("\nAttributes : ").append(mSettings.getCurrent().mInputAttributes) diff --git a/java/src/com/android/inputmethod/latin/RichInputConnection.java b/java/src/com/android/inputmethod/latin/RichInputConnection.java index 980215de6..b69e3f8d2 100644 --- a/java/src/com/android/inputmethod/latin/RichInputConnection.java +++ b/java/src/com/android/inputmethod/latin/RichInputConnection.java @@ -17,7 +17,6 @@ package com.android.inputmethod.latin; import android.inputmethodservice.InputMethodService; -import android.text.SpannableString; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; @@ -28,6 +27,11 @@ import android.view.inputmethod.ExtractedTextRequest; import android.view.inputmethod.InputConnection; import com.android.inputmethod.latin.define.ProductionFlag; +import com.android.inputmethod.latin.settings.SettingsValues; +import com.android.inputmethod.latin.utils.CapsModeUtils; +import com.android.inputmethod.latin.utils.DebugLogUtils; +import com.android.inputmethod.latin.utils.StringUtils; +import com.android.inputmethod.latin.utils.TextRange; import com.android.inputmethod.research.ResearchLogger; import java.util.Locale; @@ -47,16 +51,19 @@ public final class RichInputConnection { private static final boolean DEBUG_PREVIOUS_TEXT = false; private static final boolean DEBUG_BATCH_NESTING = false; // Provision for a long word pair and a separator - private static final int LOOKBACK_CHARACTER_NUM = Constants.Dictionary.MAX_WORD_LENGTH * 2 + 1; + private static final int LOOKBACK_CHARACTER_NUM = Constants.DICTIONARY_MAX_WORD_LENGTH * 2 + 1; private static final Pattern spaceRegex = Pattern.compile("\\s+"); private static final int INVALID_CURSOR_POSITION = -1; /** - * This variable contains the value LatinIME thinks the cursor position should be at now. - * This is a few steps in advance of what the TextView thinks it is, because TextView will - * only know after the IPC calls gets through. + * This variable contains an expected value for the cursor position. This is where the + * cursor may end up after all the keyboard-triggered updates have passed. We keep this to + * compare it to the actual cursor position to guess whether the move was caused by a + * keyboard command or not. + * It's not really the cursor position: the cursor may not be there yet, and it's also expected + * there be cases where it never actually comes to be there. */ - private int mCurrentCursorPosition = INVALID_CURSOR_POSITION; // in chars, not code points + private int mExpectedCursorPosition = INVALID_CURSOR_POSITION; // in chars, not code points /** * This contains the committed text immediately preceding the cursor and the composing * text if any. It is refreshed when the cursor moves by calling upon the TextView. @@ -97,16 +104,16 @@ public final class RichInputConnection { final String reference = (beforeCursor.length() <= actualLength) ? beforeCursor.toString() : beforeCursor.subSequence(beforeCursor.length() - actualLength, beforeCursor.length()).toString(); - if (et.selectionStart != mCurrentCursorPosition + if (et.selectionStart != mExpectedCursorPosition || !(reference.equals(internal.toString()))) { - final String context = "Expected cursor position = " + mCurrentCursorPosition + final String context = "Expected cursor position = " + mExpectedCursorPosition + "\nActual cursor position = " + et.selectionStart + "\nExpected text = " + internal.length() + " " + internal + "\nActual text = " + reference.length() + " " + reference; ((LatinIME)mParent).debugDumpStateAndCrashWithException(context); } else { - Log.e(TAG, Utils.getStackTrace(2)); - Log.e(TAG, "Exp <> Actual : " + mCurrentCursorPosition + " <> " + et.selectionStart); + Log.e(TAG, DebugLogUtils.getStackTrace(2)); + Log.e(TAG, "Exp <> Actual : " + mExpectedCursorPosition + " <> " + et.selectionStart); } } @@ -137,7 +144,7 @@ public final class RichInputConnection { public void resetCachesUponCursorMove(final int newCursorPosition, final boolean shouldFinishComposition) { - mCurrentCursorPosition = newCursorPosition; + mExpectedCursorPosition = newCursorPosition; mComposingText.setLength(0); mCommittedTextBeforeComposingText.setLength(0); final CharSequence textBeforeCursor = getTextBeforeCursor(DEFAULT_TEXT_CACHE_SIZE, 0); @@ -154,7 +161,7 @@ public final class RichInputConnection { if (mNestLevel != 1) { // TODO: exception instead Log.e(TAG, "Batch edit level incorrect : " + mNestLevel); - Log.e(TAG, Utils.getStackTrace(4)); + Log.e(TAG, DebugLogUtils.getStackTrace(4)); } } @@ -162,7 +169,7 @@ public final class RichInputConnection { if (DEBUG_BATCH_NESTING) checkBatchEdit(); if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); mCommittedTextBeforeComposingText.append(mComposingText); - mCurrentCursorPosition += mComposingText.length(); + mExpectedCursorPosition += mComposingText.length(); mComposingText.setLength(0); if (null != mIC) { mIC.finishComposingText(); @@ -176,7 +183,7 @@ public final class RichInputConnection { if (DEBUG_BATCH_NESTING) checkBatchEdit(); if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); mCommittedTextBeforeComposingText.append(text); - mCurrentCursorPosition += text.length() - mComposingText.length(); + mExpectedCursorPosition += text.length() - mComposingText.length(); mComposingText.setLength(0); if (null != mIC) { mIC.commitText(text, i); @@ -188,6 +195,10 @@ public final class RichInputConnection { return mIC.getSelectedText(flags); } + public boolean canDeleteCharacters() { + return mExpectedCursorPosition > 0; + } + /** * Gets the caps modes we should be in after this specific string. * @@ -222,7 +233,7 @@ public final class RichInputConnection { // heavy pressing of delete, for example DEFAULT_TEXT_CACHE_SIZE - 5 times or so. // getCapsMode should be updated to be able to return a "not enough info" result so that // we can get more context only when needed. - if (TextUtils.isEmpty(mCommittedTextBeforeComposingText) && 0 != mCurrentCursorPosition) { + if (TextUtils.isEmpty(mCommittedTextBeforeComposingText) && 0 != mExpectedCursorPosition) { mCommittedTextBeforeComposingText.append( getTextBeforeCursor(DEFAULT_TEXT_CACHE_SIZE, 0)); } @@ -238,22 +249,35 @@ public final class RichInputConnection { mCommittedTextBeforeComposingText.length()); } - public CharSequence getTextBeforeCursor(final int i, final int j) { - // TODO: use mCommittedTextBeforeComposingText if possible to improve performance + public CharSequence getTextBeforeCursor(final int n, final int flags) { + final int cachedLength = + mCommittedTextBeforeComposingText.length() + mComposingText.length(); + // If we have enough characters to satisfy the request, or if we have all characters in + // the text field, then we can return the cached version right away. + if (cachedLength >= n || cachedLength >= mExpectedCursorPosition) { + final StringBuilder s = new StringBuilder(mCommittedTextBeforeComposingText); + s.append(mComposingText); + if (s.length() > n) { + s.delete(0, s.length() - n); + } + return s; + } mIC = mParent.getCurrentInputConnection(); - if (null != mIC) return mIC.getTextBeforeCursor(i, j); + if (null != mIC) { + return mIC.getTextBeforeCursor(n, flags); + } return null; } - public CharSequence getTextAfterCursor(final int i, final int j) { + public CharSequence getTextAfterCursor(final int n, final int flags) { mIC = mParent.getCurrentInputConnection(); - if (null != mIC) return mIC.getTextAfterCursor(i, j); + if (null != mIC) return mIC.getTextAfterCursor(n, flags); return null; } - public void deleteSurroundingText(final int i, final int j) { + public void deleteSurroundingText(final int beforeLength, final int afterLength) { if (DEBUG_BATCH_NESTING) checkBatchEdit(); - final int remainingChars = mComposingText.length() - i; + final int remainingChars = mComposingText.length() - beforeLength; if (remainingChars >= 0) { mComposingText.setLength(remainingChars); } else { @@ -263,15 +287,15 @@ public final class RichInputConnection { + remainingChars, 0); mCommittedTextBeforeComposingText.setLength(len); } - if (mCurrentCursorPosition > i) { - mCurrentCursorPosition -= i; + if (mExpectedCursorPosition > beforeLength) { + mExpectedCursorPosition -= beforeLength; } else { - mCurrentCursorPosition = 0; + mExpectedCursorPosition = 0; } if (null != mIC) { - mIC.deleteSurroundingText(i, j); + mIC.deleteSurroundingText(beforeLength, afterLength); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.richInputConnection_deleteSurroundingText(i, j); + ResearchLogger.richInputConnection_deleteSurroundingText(beforeLength, afterLength); } } if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); @@ -300,7 +324,7 @@ public final class RichInputConnection { switch (keyEvent.getKeyCode()) { case KeyEvent.KEYCODE_ENTER: mCommittedTextBeforeComposingText.append("\n"); - mCurrentCursorPosition += 1; + mExpectedCursorPosition += 1; break; case KeyEvent.KEYCODE_DEL: if (0 == mComposingText.length()) { @@ -312,18 +336,18 @@ public final class RichInputConnection { } else { mComposingText.delete(mComposingText.length() - 1, mComposingText.length()); } - if (mCurrentCursorPosition > 0) mCurrentCursorPosition -= 1; + if (mExpectedCursorPosition > 0) mExpectedCursorPosition -= 1; break; case KeyEvent.KEYCODE_UNKNOWN: if (null != keyEvent.getCharacters()) { mCommittedTextBeforeComposingText.append(keyEvent.getCharacters()); - mCurrentCursorPosition += keyEvent.getCharacters().length(); + mExpectedCursorPosition += keyEvent.getCharacters().length(); } break; default: final String text = new String(new int[] { keyEvent.getUnicodeChar() }, 0, 1); mCommittedTextBeforeComposingText.append(text); - mCurrentCursorPosition += text.length(); + mExpectedCursorPosition += text.length(); break; } } @@ -338,7 +362,6 @@ public final class RichInputConnection { public void setComposingRegion(final int start, final int end) { if (DEBUG_BATCH_NESTING) checkBatchEdit(); if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); - mCurrentCursorPosition = end; final CharSequence textBeforeCursor = getTextBeforeCursor(DEFAULT_TEXT_CACHE_SIZE + (end - start), 0); mCommittedTextBeforeComposingText.setLength(0); @@ -355,32 +378,32 @@ public final class RichInputConnection { } } - public void setComposingText(final CharSequence text, final int i) { + public void setComposingText(final CharSequence text, final int newCursorPosition) { if (DEBUG_BATCH_NESTING) checkBatchEdit(); if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); - mCurrentCursorPosition += text.length() - mComposingText.length(); + mExpectedCursorPosition += text.length() - mComposingText.length(); mComposingText.setLength(0); mComposingText.append(text); // TODO: support values of i != 1. At this time, this is never called with i != 1. if (null != mIC) { - mIC.setComposingText(text, i); + mIC.setComposingText(text, newCursorPosition); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.richInputConnection_setComposingText(text, i); + ResearchLogger.richInputConnection_setComposingText(text, newCursorPosition); } } if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); } - public void setSelection(final int from, final int to) { + public void setSelection(final int start, final int end) { if (DEBUG_BATCH_NESTING) checkBatchEdit(); if (DEBUG_PREVIOUS_TEXT) checkConsistencyForDebug(); if (null != mIC) { - mIC.setSelection(from, to); + mIC.setSelection(start, end); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { - ResearchLogger.richInputConnection_setSelection(from, to); + ResearchLogger.richInputConnection_setSelection(start, end); } } - mCurrentCursorPosition = from; + mExpectedCursorPosition = start; mCommittedTextBeforeComposingText.setLength(0); mCommittedTextBeforeComposingText.append(getTextBeforeCursor(DEFAULT_TEXT_CACHE_SIZE, 0)); } @@ -403,7 +426,7 @@ public final class RichInputConnection { // text should never be null, but just in case, it's better to insert nothing than to crash if (null == text) text = ""; mCommittedTextBeforeComposingText.append(text); - mCurrentCursorPosition += text.length() - mComposingText.length(); + mExpectedCursorPosition += text.length() - mComposingText.length(); mComposingText.setLength(0); if (null != mIC) { mIC.commitCompletion(completionInfo); @@ -418,7 +441,7 @@ public final class RichInputConnection { public String getNthPreviousWord(final String sentenceSeperators, final int n) { mIC = mParent.getCurrentInputConnection(); if (null == mIC) return null; - final CharSequence prev = mIC.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0); + final CharSequence prev = getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0); if (DEBUG_PREVIOUS_TEXT && null != prev) { final int checkLength = LOOKBACK_CHARACTER_NUM - 1; final String reference = prev.length() <= checkLength ? prev.toString() @@ -437,32 +460,6 @@ public final class RichInputConnection { return getNthPreviousWord(prev, sentenceSeperators, n); } - /** - * Represents a range of text, relative to the current cursor position. - */ - public static final class Range { - /** Characters before selection start */ - public final int mCharsBefore; - - /** - * Characters after selection start, including one trailing word - * separator. - */ - public final int mCharsAfter; - - /** The actual characters that make up a word */ - public final CharSequence mWord; - - public Range(int charsBefore, int charsAfter, CharSequence word) { - if (charsBefore < 0 || charsAfter < 0) { - throw new IndexOutOfBoundsException(); - } - this.mCharsBefore = charsBefore; - this.mCharsAfter = charsAfter; - this.mWord = word; - } - } - private static boolean isSeparator(int code, String sep) { return sep.indexOf(code) != -1; } @@ -509,7 +506,7 @@ public final class RichInputConnection { */ public CharSequence getWordAtCursor(String separators) { // getWordRangeAtCursor returns null if the connection is null - Range r = getWordRangeAtCursor(separators, 0); + TextRange r = getWordRangeAtCursor(separators, 0); return (r == null) ? null : r.mWord; } @@ -521,7 +518,8 @@ public final class RichInputConnection { * be included in the returned range * @return a range containing the text surrounding the cursor */ - public Range getWordRangeAtCursor(final String sep, final int additionalPrecedingWordsCount) { + public TextRange getWordRangeAtCursor(final String sep, + final int additionalPrecedingWordsCount) { mIC = mParent.getCurrentInputConnection(); if (mIC == null || sep == null) { return null; @@ -571,19 +569,18 @@ public final class RichInputConnection { } } - final SpannableString word = new SpannableString(TextUtils.concat( - before.subSequence(startIndexInBefore, before.length()), - after.subSequence(0, endIndexInAfter))); - return new Range(before.length() - startIndexInBefore, endIndexInAfter, word); + return new TextRange(TextUtils.concat(before, after), startIndexInBefore, + before.length() + endIndexInAfter, before.length()); } public boolean isCursorTouchingWord(final SettingsValues settingsValues) { - final CharSequence before = getTextBeforeCursor(1, 0); - final CharSequence after = getTextAfterCursor(1, 0); - if (!TextUtils.isEmpty(before) && !settingsValues.isWordSeparator(before.charAt(0)) - && !settingsValues.isWordConnector(before.charAt(0))) { + final int codePointBeforeCursor = getCodePointBeforeCursor(); + if (Constants.NOT_A_CODE != codePointBeforeCursor + && !settingsValues.isWordSeparator(codePointBeforeCursor) + && !settingsValues.isWordConnector(codePointBeforeCursor)) { return true; } + final CharSequence after = getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(after) && !settingsValues.isWordSeparator(after.charAt(0)) && !settingsValues.isWordConnector(after.charAt(0))) { return true; @@ -593,9 +590,8 @@ public final class RichInputConnection { public void removeTrailingSpace() { if (DEBUG_BATCH_NESTING) checkBatchEdit(); - final CharSequence lastOne = getTextBeforeCursor(1, 0); - if (lastOne != null && lastOne.length() == 1 - && lastOne.charAt(0) == Constants.CODE_SPACE) { + final int codePointBeforeCursor = getCodePointBeforeCursor(); + if (Constants.CODE_SPACE == codePointBeforeCursor) { deleteSurroundingText(1, 0); } } @@ -650,7 +646,7 @@ public final class RichInputConnection { // be needed, but it's there just in case something went wrong. final CharSequence textBeforeCursor = getTextBeforeCursor(2, 0); final String periodSpace = ". "; - if (!periodSpace.equals(textBeforeCursor)) { + if (!TextUtils.equals(periodSpace, textBeforeCursor)) { // Theoretically we should not be coming here if there isn't ". " before the // cursor, but the application may be changing the text while we are typing, so // anything goes. We should not crash. @@ -712,14 +708,14 @@ public final class RichInputConnection { */ public boolean isBelatedExpectedUpdate(final int oldSelStart, final int newSelStart) { // If this is an update that arrives at our expected position, it's a belated update. - if (newSelStart == mCurrentCursorPosition) return true; + if (newSelStart == mExpectedCursorPosition) return true; // If this is an update that moves the cursor from our expected position, it must be // an explicit move. - if (oldSelStart == mCurrentCursorPosition) return false; + if (oldSelStart == mExpectedCursorPosition) return false; // The following returns true if newSelStart is between oldSelStart and // mCurrentCursorPosition. We assume that if the updated position is between the old // position and the expected position, then it must be a belated update. - return (newSelStart - oldSelStart) * (mCurrentCursorPosition - newSelStart) >= 0; + return (newSelStart - oldSelStart) * (mExpectedCursorPosition - newSelStart) >= 0; } /** diff --git a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java index 0dd302afa..6b6bbf3a7 100644 --- a/java/src/com/android/inputmethod/latin/RichInputMethodManager.java +++ b/java/src/com/android/inputmethod/latin/RichInputMethodManager.java @@ -28,8 +28,13 @@ import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodSubtype; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; +import com.android.inputmethod.latin.settings.Settings; +import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; import java.util.Collections; +import java.util.HashMap; import java.util.List; /** @@ -46,6 +51,10 @@ public final class RichInputMethodManager { private InputMethodManagerCompatWrapper mImmWrapper; private InputMethodInfo mInputMethodInfoOfThisIme; + final HashMap<InputMethodInfo, List<InputMethodSubtype>> + mSubtypeListCacheWithImplicitlySelectedSubtypes = CollectionUtils.newHashMap(); + final HashMap<InputMethodInfo, List<InputMethodSubtype>> + mSubtypeListCacheWithoutImplicitlySelectedSubtypes = CollectionUtils.newHashMap(); private static final int INDEX_NOT_FOUND = -1; @@ -54,13 +63,6 @@ public final class RichInputMethodManager { return sInstance; } - // Caveat: This may cause IPC - public static boolean isInputMethodManagerValidForUserOfThisProcess(final Context context) { - // Basically called to check whether this IME has been triggered by the current user or not - return !((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)). - getInputMethodList().isEmpty(); - } - public static void init(final Context context) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); sInstance.initInternal(context, prefs); @@ -84,11 +86,11 @@ public final class RichInputMethodManager { mInputMethodInfoOfThisIme = getInputMethodInfoOfThisIme(context); // Initialize additional subtypes. - SubtypeLocale.init(context); + SubtypeLocaleUtils.init(context); final String prefAdditionalSubtypes = Settings.readPrefAdditionalSubtypes( prefs, context.getResources()); final InputMethodSubtype[] additionalSubtypes = - AdditionalSubtype.createAdditionalSubtypesArray(prefAdditionalSubtypes); + AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefAdditionalSubtypes); setAdditionalInputMethodSubtypes(additionalSubtypes); } @@ -109,8 +111,8 @@ public final class RichInputMethodManager { public List<InputMethodSubtype> getMyEnabledInputMethodSubtypeList( boolean allowsImplicitlySelectedSubtypes) { - return mImmWrapper.mImm.getEnabledInputMethodSubtypeList( - mInputMethodInfoOfThisIme, allowsImplicitlySelectedSubtypes); + return getEnabledInputMethodSubtypeList(mInputMethodInfoOfThisIme, + allowsImplicitlySelectedSubtypes); } public boolean switchToNextInputMethod(final IBinder token, final boolean onlyCurrentIme) { @@ -134,7 +136,7 @@ public final class RichInputMethodManager { final int currentIndex = getSubtypeIndexInList(currentSubtype, enabledSubtypes); if (currentIndex == INDEX_NOT_FOUND) { Log.w(TAG, "Can't find current subtype in enabled subtypes: subtype=" - + SubtypeLocale.getSubtypeDisplayName(currentSubtype)); + + SubtypeLocaleUtils.getSubtypeNameForLogging(currentSubtype)); return false; } final int nextIndex = (currentIndex + 1) % enabledSubtypes.size(); @@ -158,8 +160,8 @@ public final class RichInputMethodManager { return false; } final InputMethodInfo nextImi = getNextNonAuxiliaryIme(currentIndex, enabledImis); - final List<InputMethodSubtype> enabledSubtypes = imm.getEnabledInputMethodSubtypeList( - nextImi, true /* allowsImplicitlySelectedSubtypes */); + final List<InputMethodSubtype> enabledSubtypes = getEnabledInputMethodSubtypeList(nextImi, + true /* allowsImplicitlySelectedSubtypes */); if (enabledSubtypes.isEmpty()) { // The next IME has no subtype. imm.setInputMethod(token, nextImi.getId()); @@ -234,9 +236,8 @@ public final class RichInputMethodManager { public boolean checkIfSubtypeBelongsToImeAndEnabled(final InputMethodInfo imi, final InputMethodSubtype subtype) { - return checkIfSubtypeBelongsToList( - subtype, mImmWrapper.mImm.getEnabledInputMethodSubtypeList( - imi, true /* allowsImplicitlySelectedSubtypes */)); + return checkIfSubtypeBelongsToList(subtype, getEnabledInputMethodSubtypeList(imi, + true /* allowsImplicitlySelectedSubtypes */)); } private static boolean checkIfSubtypeBelongsToList(final InputMethodSubtype subtype, @@ -297,8 +298,7 @@ public final class RichInputMethodManager { for (InputMethodInfo imi : imiList) { // We can return true immediately after we find two or more filtered IMEs. if (filteredImisCount > 1) return true; - final List<InputMethodSubtype> subtypes = - mImmWrapper.mImm.getEnabledInputMethodSubtypeList(imi, true); + final List<InputMethodSubtype> subtypes = getEnabledInputMethodSubtypeList(imi, true); // IMEs that have no subtypes should be counted. if (subtypes.isEmpty()) { ++filteredImisCount; @@ -344,7 +344,7 @@ public final class RichInputMethodManager { final int count = myImi.getSubtypeCount(); for (int i = 0; i < count; i++) { final InputMethodSubtype subtype = myImi.getSubtypeAt(i); - final String layoutName = SubtypeLocale.getKeyboardLayoutSetName(subtype); + final String layoutName = SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype); if (localeString.equals(subtype.getLocale()) && keyboardLayoutSetName.equals(layoutName)) { return subtype; @@ -361,5 +361,26 @@ public final class RichInputMethodManager { public void setAdditionalInputMethodSubtypes(final InputMethodSubtype[] subtypes) { mImmWrapper.mImm.setAdditionalInputMethodSubtypes( mInputMethodInfoOfThisIme.getId(), subtypes); + // Clear the cache so that we go read the subtypes again next time. + clearSubtypeCaches(); + } + + private List<InputMethodSubtype> getEnabledInputMethodSubtypeList(final InputMethodInfo imi, + final boolean allowsImplicitlySelectedSubtypes) { + final HashMap<InputMethodInfo, List<InputMethodSubtype>> cache = + allowsImplicitlySelectedSubtypes + ? mSubtypeListCacheWithImplicitlySelectedSubtypes + : mSubtypeListCacheWithoutImplicitlySelectedSubtypes; + final List<InputMethodSubtype> cachedList = cache.get(imi); + if (null != cachedList) return cachedList; + final List<InputMethodSubtype> result = mImmWrapper.mImm.getEnabledInputMethodSubtypeList( + imi, allowsImplicitlySelectedSubtypes); + cache.put(imi, result); + return result; + } + + public void clearSubtypeCaches() { + mSubtypeListCacheWithImplicitlySelectedSubtypes.clear(); + mSubtypeListCacheWithoutImplicitlySelectedSubtypes.clear(); } } diff --git a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java index 282b5794f..be03d4ae5 100644 --- a/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java +++ b/java/src/com/android/inputmethod/latin/SubtypeSwitcher.java @@ -33,6 +33,7 @@ import android.view.inputmethod.InputMethodSubtype; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.keyboard.KeyboardSwitcher; +import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; import java.util.List; import java.util.Locale; @@ -43,20 +44,23 @@ public final class SubtypeSwitcher { private static final String TAG = SubtypeSwitcher.class.getSimpleName(); private static final SubtypeSwitcher sInstance = new SubtypeSwitcher(); + private /* final */ RichInputMethodManager mRichImm; private /* final */ Resources mResources; private /* final */ ConnectivityManager mConnectivityManager; - /*-----------------------------------------------------------*/ - // Variants which should be changed only by reload functions. - private NeedsToDisplayLanguage mNeedsToDisplayLanguage = new NeedsToDisplayLanguage(); + private final NeedsToDisplayLanguage mNeedsToDisplayLanguage = new NeedsToDisplayLanguage(); private InputMethodInfo mShortcutInputMethodInfo; private InputMethodSubtype mShortcutSubtype; private InputMethodSubtype mNoLanguageSubtype; - /*-----------------------------------------------------------*/ - private boolean mIsNetworkConnected; + // Dummy no language QWERTY subtype. See {@link R.xml.method}. + private static final InputMethodSubtype DUMMY_NO_LANGUAGE_SUBTYPE = new InputMethodSubtype( + R.string.subtype_no_language_qwerty, R.drawable.ic_subtype_keyboard, "zz", "keyboard", + "KeyboardLayoutSet=qwerty,AsciiCapable,EnabledWhenDefaultIsNotAsciiCapable", + false /* isAuxiliary */, false /* overridesImplicitlyEnabledSubtype */); + static final class NeedsToDisplayLanguage { private int mEnabledSubtypeCount; private boolean mIsSystemLanguageSameAsInputLanguage; @@ -79,7 +83,7 @@ public final class SubtypeSwitcher { } public static void init(final Context context) { - SubtypeLocale.init(context); + SubtypeLocaleUtils.init(context); RichInputMethodManager.init(context); sInstance.initialize(context); } @@ -96,11 +100,6 @@ public final class SubtypeSwitcher { mRichImm = RichInputMethodManager.getInstance(); mConnectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); - mNoLanguageSubtype = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( - SubtypeLocale.NO_LANGUAGE, SubtypeLocale.QWERTY); - if (mNoLanguageSubtype == null) { - throw new RuntimeException("Can't find no lanugage with QWERTY subtype"); - } final NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); mIsNetworkConnected = (info != null && info.isConnected()); @@ -155,10 +154,11 @@ public final class SubtypeSwitcher { // Update the current subtype. LatinIME.onCurrentInputMethodSubtypeChanged calls this function. public void onSubtypeChanged(final InputMethodSubtype newSubtype) { if (DBG) { - Log.w(TAG, "onSubtypeChanged: " + SubtypeLocale.getSubtypeDisplayName(newSubtype)); + Log.w(TAG, "onSubtypeChanged: " + + SubtypeLocaleUtils.getSubtypeNameForLogging(newSubtype)); } - final Locale newLocale = SubtypeLocale.getSubtypeLocale(newSubtype); + final Locale newLocale = SubtypeLocaleUtils.getSubtypeLocale(newSubtype); final Locale systemLocale = mResources.getConfiguration().locale; final boolean sameLocale = systemLocale.equals(newLocale); final boolean sameLanguage = systemLocale.getLanguage().equals(newLocale.getLanguage()); @@ -234,7 +234,7 @@ public final class SubtypeSwitcher { ////////////////////////////////// public boolean needsToDisplayLanguage(final Locale keyboardLocale) { - if (keyboardLocale.toString().equals(SubtypeLocale.NO_LANGUAGE)) { + if (keyboardLocale.toString().equals(SubtypeLocaleUtils.NO_LANGUAGE)) { return true; } if (!keyboardLocale.equals(getCurrentSubtypeLocale())) { @@ -251,14 +251,24 @@ public final class SubtypeSwitcher { public Locale getCurrentSubtypeLocale() { if (null != sForcedLocaleForTesting) return sForcedLocaleForTesting; - return SubtypeLocale.getSubtypeLocale(getCurrentSubtype()); + return SubtypeLocaleUtils.getSubtypeLocale(getCurrentSubtype()); } public InputMethodSubtype getCurrentSubtype() { - return mRichImm.getCurrentInputMethodSubtype(mNoLanguageSubtype); + return mRichImm.getCurrentInputMethodSubtype(getNoLanguageSubtype()); } public InputMethodSubtype getNoLanguageSubtype() { - return mNoLanguageSubtype; + if (mNoLanguageSubtype == null) { + mNoLanguageSubtype = mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( + SubtypeLocaleUtils.NO_LANGUAGE, SubtypeLocaleUtils.QWERTY); + } + if (mNoLanguageSubtype != null) { + return mNoLanguageSubtype; + } + Log.w(TAG, "Can't find no lanugage with QWERTY subtype"); + Log.w(TAG, "No input method subtype found; return dummy subtype: " + + DUMMY_NO_LANGUAGE_SUBTYPE); + return DUMMY_NO_LANGUAGE_SUBTYPE; } } diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java index dc9bef22a..c2fdcb552 100644 --- a/java/src/com/android/inputmethod/latin/Suggest.java +++ b/java/src/com/android/inputmethod/latin/Suggest.java @@ -17,13 +17,21 @@ package com.android.inputmethod.latin; import android.content.Context; +import android.preference.PreferenceManager; import android.text.TextUtils; +import android.util.Log; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.keyboard.ProximityInfo; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; +import com.android.inputmethod.latin.personalization.PersonalizationPredictionDictionary; +import com.android.inputmethod.latin.personalization.UserHistoryPredictionDictionary; +import com.android.inputmethod.latin.settings.Settings; +import com.android.inputmethod.latin.utils.AutoCorrectionUtils; +import com.android.inputmethod.latin.utils.BoundedTreeSet; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.StringUtils; -import java.io.File; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; @@ -50,21 +58,22 @@ public final class Suggest { // Close to -2**31 private static final int SUPPRESS_SUGGEST_THRESHOLD = -2000000000; + public static final int MAX_SUGGESTIONS = 18; + public interface SuggestInitializationListener { public void onUpdateMainDictionaryAvailability(boolean isMainDictionaryAvailable); } private static final boolean DBG = LatinImeLogger.sDBG; - private Dictionary mMainDictionary; - private ContactsBinaryDictionary mContactsDict; private final ConcurrentHashMap<String, Dictionary> mDictionaries = CollectionUtils.newConcurrentHashMap(); + private HashSet<String> mOnlyDictionarySetForDebug = null; + private Dictionary mMainDictionary; + private ContactsBinaryDictionary mContactsDict; @UsedForTesting private boolean mIsCurrentlyWaitingForMainDictionary = false; - public static final int MAX_SUGGESTIONS = 18; - private float mAutoCorrectionThreshold; // Locale used for upper- and title-casing words @@ -74,15 +83,22 @@ public final class Suggest { final SuggestInitializationListener listener) { initAsynchronously(context, locale, listener); mLocale = locale; + // initialize a debug flag for the personalization + if (Settings.readUseOnlyPersonalizationDictionaryForDebug( + PreferenceManager.getDefaultSharedPreferences(context))) { + mOnlyDictionarySetForDebug = new HashSet<String>(); + mOnlyDictionarySetForDebug.add(Dictionary.TYPE_PERSONALIZATION); + mOnlyDictionarySetForDebug.add(Dictionary.TYPE_PERSONALIZATION_PREDICTION_IN_JAVA); + } } @UsedForTesting - Suggest(final File dictionary, final long startOffset, final long length, final Locale locale) { - final Dictionary mainDict = DictionaryFactory.createDictionaryForTest(dictionary, - startOffset, length /* useFullEditDistance */, false, locale); + Suggest(final AssetFileAddress[] dictionaryList, final Locale locale) { + final Dictionary mainDict = DictionaryFactory.createDictionaryForTest(dictionaryList, + false /* useFullEditDistance */, locale); mLocale = locale; mMainDictionary = mainDict; - addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_MAIN, mainDict); + addOrReplaceDictionaryInternal(Dictionary.TYPE_MAIN, mainDict); } private void initAsynchronously(final Context context, final Locale locale, @@ -90,6 +106,14 @@ public final class Suggest { resetMainDict(context, locale, listener); } + private void addOrReplaceDictionaryInternal(final String key, final Dictionary dict) { + if (mOnlyDictionarySetForDebug != null && mOnlyDictionarySetForDebug.contains(key)) { + Log.w(TAG, "Ignore add " + key + " dictionary for debug."); + return; + } + addOrReplaceDictionary(mDictionaries, key, dict); + } + private static void addOrReplaceDictionary( final ConcurrentHashMap<String, Dictionary> dictionaries, final String key, final Dictionary dict) { @@ -113,7 +137,7 @@ public final class Suggest { public void run() { final DictionaryCollection newMainDict = DictionaryFactory.createMainDictionaryFromManager(context, locale); - addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_MAIN, newMainDict); + addOrReplaceDictionaryInternal(Dictionary.TYPE_MAIN, newMainDict); mMainDictionary = newMainDict; if (listener != null) { listener.onUpdateMainDictionaryAvailability(hasMainDictionary()); @@ -151,7 +175,7 @@ public final class Suggest { * before the main dictionary, if set. This refers to the system-managed user dictionary. */ public void setUserDictionary(final UserBinaryDictionary userDictionary) { - addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_USER, userDictionary); + addOrReplaceDictionaryInternal(Dictionary.TYPE_USER, userDictionary); } /** @@ -161,11 +185,19 @@ public final class Suggest { */ public void setContactsDictionary(final ContactsBinaryDictionary contactsDictionary) { mContactsDict = contactsDictionary; - addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_CONTACTS, contactsDictionary); + addOrReplaceDictionaryInternal(Dictionary.TYPE_CONTACTS, contactsDictionary); + } + + public void setUserHistoryPredictionDictionary( + final UserHistoryPredictionDictionary userHistoryPredictionDictionary) { + addOrReplaceDictionaryInternal(Dictionary.TYPE_USER_HISTORY, + userHistoryPredictionDictionary); } - public void setUserHistoryDictionary(final UserHistoryDictionary userHistoryDictionary) { - addOrReplaceDictionary(mDictionaries, Dictionary.TYPE_USER_HISTORY, userHistoryDictionary); + public void setPersonalizationPredictionDictionary( + final PersonalizationPredictionDictionary personalizationPredictionDictionary) { + addOrReplaceDictionaryInternal(Dictionary.TYPE_PERSONALIZATION_PREDICTION_IN_JAVA, + personalizationPredictionDictionary); } public void setAutoCorrectionThreshold(float threshold) { @@ -229,7 +261,7 @@ public final class Suggest { // or if it's a 2+ characters non-word (i.e. it's not in the dictionary). final boolean allowsToBeAutoCorrected = (null != whitelistedWord && !whitelistedWord.equals(consideredWord)) - || (consideredWord.length() > 1 && !AutoCorrection.isInTheDictionary(mDictionaries, + || (consideredWord.length() > 1 && !AutoCorrectionUtils.isValidWord(this, consideredWord, wordComposer.isFirstCharCapitalized())); final boolean hasAutoCorrection; @@ -250,7 +282,7 @@ public final class Suggest { // auto-correct. hasAutoCorrection = false; } else { - hasAutoCorrection = AutoCorrection.suggestionExceedsAutoCorrectionThreshold( + hasAutoCorrection = AutoCorrectionUtils.suggestionExceedsAutoCorrectionThreshold( suggestionsSet.first(), consideredWord, mAutoCorrectionThreshold); } @@ -379,7 +411,8 @@ public final class Suggest { typedWord, cur.toString(), cur.mScore); final String scoreInfoString; if (normalizedScore > 0) { - scoreInfoString = String.format("%d (%4.2f)", cur.mScore, normalizedScore); + scoreInfoString = String.format( + Locale.ROOT, "%d (%4.2f)", cur.mScore, normalizedScore); } else { scoreInfoString = Integer.toString(cur.mScore); } diff --git a/java/src/com/android/inputmethod/latin/SuggestedWords.java b/java/src/com/android/inputmethod/latin/SuggestedWords.java index dfddb0ffe..22beaefee 100644 --- a/java/src/com/android/inputmethod/latin/SuggestedWords.java +++ b/java/src/com/android/inputmethod/latin/SuggestedWords.java @@ -19,11 +19,17 @@ package com.android.inputmethod.latin; import android.text.TextUtils; import android.view.inputmethod.CompletionInfo; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.StringUtils; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; public final class SuggestedWords { + public static final int INDEX_OF_TYPED_WORD = 0; + public static final int INDEX_OF_AUTO_CORRECTION = 1; + private static final ArrayList<SuggestedWordInfo> EMPTY_WORD_INFO_LIST = CollectionUtils.newArrayList(0); public static final SuggestedWords EMPTY = new SuggestedWords( @@ -61,12 +67,27 @@ public final class SuggestedWords { return mSuggestedWordInfoList.size(); } - public String getWord(int pos) { - return mSuggestedWordInfoList.get(pos).mWord; + public String getWord(final int index) { + return mSuggestedWordInfoList.get(index).mWord; + } + + public SuggestedWordInfo getInfo(final int index) { + return mSuggestedWordInfoList.get(index); } - public SuggestedWordInfo getInfo(int pos) { - return mSuggestedWordInfoList.get(pos); + public String getDebugString(final int pos) { + if (!LatinImeLogger.sDBG) { + return null; + } + final SuggestedWordInfo wordInfo = getInfo(pos); + if (wordInfo == null) { + return null; + } + final String debugString = wordInfo.getDebugString(); + if (TextUtils.isEmpty(debugString)) { + return null; + } + return debugString; } public boolean willAutoCorrect() { @@ -108,8 +129,8 @@ public final class SuggestedWords { SuggestedWordInfo.KIND_TYPED, Dictionary.TYPE_USER_TYPED)); alreadySeen.add(typedWord.toString()); final int previousSize = previousSuggestions.size(); - for (int pos = 1; pos < previousSize; pos++) { - final SuggestedWordInfo prevWordInfo = previousSuggestions.getInfo(pos); + for (int index = 1; index < previousSize; index++) { + final SuggestedWordInfo prevWordInfo = previousSuggestions.getInfo(index); final String prevWord = prevWordInfo.mWord; // Filter out duplicate suggestion. if (!alreadySeen.contains(prevWord)) { @@ -132,7 +153,10 @@ public final class SuggestedWords { public static final int KIND_APP_DEFINED = 6; // Suggested by the application public static final int KIND_SHORTCUT = 7; // A shortcut public static final int KIND_PREDICTION = 8; // A prediction (== a suggestion with no input) - public static final int KIND_RESUMED = 9; // A resumed suggestion (comes from a span) + // KIND_RESUMED: A resumed suggestion (comes from a span, currently this type is used only + // in java for re-correction) + public static final int KIND_RESUMED = 9; + public static final int KIND_OOV_CORRECTION = 10; // Most probable string correction public static final int KIND_MASK_FLAGS = 0xFFFFFF00; // Mask to get the flags public static final int KIND_FLAG_POSSIBLY_OFFENSIVE = 0x80000000; diff --git a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java index 90f92972a..ed6fefae4 100644 --- a/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java +++ b/java/src/com/android/inputmethod/latin/UserBinaryDictionary.java @@ -28,6 +28,8 @@ import android.provider.UserDictionary.Words; import android.text.TextUtils; import com.android.inputmethod.compat.UserDictionaryCompatUtils; +import com.android.inputmethod.latin.utils.LocaleUtils; +import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; import java.util.Arrays; import java.util.Locale; @@ -75,7 +77,7 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { final boolean alsoUseMoreRestrictiveLocales) { super(context, getFilenameWithLocale(NAME, locale), Dictionary.TYPE_USER); if (null == locale) throw new NullPointerException(); // Catch the error earlier - if (SubtypeLocale.NO_LANGUAGE.equals(locale)) { + if (SubtypeLocaleUtils.NO_LANGUAGE.equals(locale)) { // If we don't have a locale, insert into the "all locales" user dictionary. mLocale = USER_DICTIONARY_ALL_LANGUAGES; } else { @@ -239,7 +241,6 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { private void addWords(final Cursor cursor) { final boolean hasShortcutColumn = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; - clearFusionDictionary(); if (cursor == null) return; if (cursor.moveToFirst()) { final int indexWord = cursor.getColumnIndex(Words.WORD); @@ -266,4 +267,9 @@ public class UserBinaryDictionary extends ExpandableBinaryDictionary { protected boolean hasContentChanged() { return true; } + + @Override + protected boolean needsToReloadBeforeWriting() { + return true; + } } diff --git a/java/src/com/android/inputmethod/latin/Utils.java b/java/src/com/android/inputmethod/latin/Utils.java deleted file mode 100644 index 0f96c54dc..000000000 --- a/java/src/com/android/inputmethod/latin/Utils.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.inputmethod.latin; - -import android.app.Activity; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ActivityInfo; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.inputmethodservice.InputMethodService; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Environment; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Process; -import android.text.TextUtils; -import android.util.Log; - -import com.android.inputmethod.annotations.UsedForTesting; -import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.channels.FileChannel; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -public final class Utils { - private static final String TAG = Utils.class.getSimpleName(); - - private Utils() { - // This utility class is not publicly instantiable. - } - - /** - * Cancel an {@link AsyncTask}. - * - * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this - * task should be interrupted; otherwise, in-progress tasks are allowed - * to complete. - */ - public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) { - if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) { - task.cancel(mayInterruptIfRunning); - } - } - - /* package */ static final class RingCharBuffer { - private static RingCharBuffer sRingCharBuffer = new RingCharBuffer(); - private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC'; - private static final int INVALID_COORDINATE = -2; - /* package */ static final int BUFSIZE = 20; - private InputMethodService mContext; - private boolean mEnabled = false; - private int mEnd = 0; - /* package */ int mLength = 0; - private char[] mCharBuf = new char[BUFSIZE]; - private int[] mXBuf = new int[BUFSIZE]; - private int[] mYBuf = new int[BUFSIZE]; - - private RingCharBuffer() { - // Intentional empty constructor for singleton. - } - @UsedForTesting - public static RingCharBuffer getInstance() { - return sRingCharBuffer; - } - public static RingCharBuffer init(InputMethodService context, boolean enabled, - boolean usabilityStudy) { - if (!(enabled || usabilityStudy)) return null; - sRingCharBuffer.mContext = context; - sRingCharBuffer.mEnabled = true; - UsabilityStudyLogUtils.getInstance().init(context); - return sRingCharBuffer; - } - private static int normalize(int in) { - int ret = in % BUFSIZE; - return ret < 0 ? ret + BUFSIZE : ret; - } - // TODO: accept code points - @UsedForTesting - public void push(char c, int x, int y) { - if (!mEnabled) return; - mCharBuf[mEnd] = c; - mXBuf[mEnd] = x; - mYBuf[mEnd] = y; - mEnd = normalize(mEnd + 1); - if (mLength < BUFSIZE) { - ++mLength; - } - } - public char pop() { - if (mLength < 1) { - return PLACEHOLDER_DELIMITER_CHAR; - } else { - mEnd = normalize(mEnd - 1); - --mLength; - return mCharBuf[mEnd]; - } - } - public char getBackwardNthChar(int n) { - if (mLength <= n || n < 0) { - return PLACEHOLDER_DELIMITER_CHAR; - } else { - return mCharBuf[normalize(mEnd - n - 1)]; - } - } - public int getPreviousX(char c, int back) { - int index = normalize(mEnd - 2 - back); - if (mLength <= back - || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { - return INVALID_COORDINATE; - } else { - return mXBuf[index]; - } - } - public int getPreviousY(char c, int back) { - int index = normalize(mEnd - 2 - back); - if (mLength <= back - || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { - return INVALID_COORDINATE; - } else { - return mYBuf[index]; - } - } - public String getLastWord(int ignoreCharCount) { - StringBuilder sb = new StringBuilder(); - int i = ignoreCharCount; - for (; i < mLength; ++i) { - char c = mCharBuf[normalize(mEnd - 1 - i)]; - if (!((LatinIME)mContext).isWordSeparator(c)) { - break; - } - } - for (; i < mLength; ++i) { - char c = mCharBuf[normalize(mEnd - 1 - i)]; - if (!((LatinIME)mContext).isWordSeparator(c)) { - sb.append(c); - } else { - break; - } - } - return sb.reverse().toString(); - } - public void reset() { - mLength = 0; - } - } - - // Get the current stack trace - public static String getStackTrace(final int limit) { - StringBuilder sb = new StringBuilder(); - try { - throw new RuntimeException(); - } catch (RuntimeException e) { - StackTraceElement[] frames = e.getStackTrace(); - // Start at 1 because the first frame is here and we don't care about it - for (int j = 1; j < frames.length && j < limit + 1; ++j) { - sb.append(frames[j].toString() + "\n"); - } - } - return sb.toString(); - } - - public static String getStackTrace() { - return getStackTrace(Integer.MAX_VALUE - 1); - } - - public static final class UsabilityStudyLogUtils { - // TODO: remove code duplication with ResearchLog class - private static final String USABILITY_TAG = UsabilityStudyLogUtils.class.getSimpleName(); - private static final String FILENAME = "log.txt"; - private final Handler mLoggingHandler; - private File mFile; - private File mDirectory; - private InputMethodService mIms; - private PrintWriter mWriter; - private final Date mDate; - private final SimpleDateFormat mDateFormat; - - private UsabilityStudyLogUtils() { - mDate = new Date(); - mDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss.SSSZ", Locale.US); - - HandlerThread handlerThread = new HandlerThread("UsabilityStudyLogUtils logging task", - Process.THREAD_PRIORITY_BACKGROUND); - handlerThread.start(); - mLoggingHandler = new Handler(handlerThread.getLooper()); - } - - // Initialization-on-demand holder - private static final class OnDemandInitializationHolder { - public static final UsabilityStudyLogUtils sInstance = new UsabilityStudyLogUtils(); - } - - public static UsabilityStudyLogUtils getInstance() { - return OnDemandInitializationHolder.sInstance; - } - - public void init(InputMethodService ims) { - mIms = ims; - mDirectory = ims.getFilesDir(); - } - - private void createLogFileIfNotExist() { - if ((mFile == null || !mFile.exists()) - && (mDirectory != null && mDirectory.exists())) { - try { - mWriter = getPrintWriter(mDirectory, FILENAME, false); - } catch (IOException e) { - Log.e(USABILITY_TAG, "Can't create log file."); - } - } - } - - public static void writeBackSpace(int x, int y) { - UsabilityStudyLogUtils.getInstance().write("<backspace>\t" + x + "\t" + y); - } - - public void writeChar(char c, int x, int y) { - String inputChar = String.valueOf(c); - switch (c) { - case '\n': - inputChar = "<enter>"; - break; - case '\t': - inputChar = "<tab>"; - break; - case ' ': - inputChar = "<space>"; - break; - } - UsabilityStudyLogUtils.getInstance().write(inputChar + "\t" + x + "\t" + y); - LatinImeLogger.onPrintAllUsabilityStudyLogs(); - } - - public void write(final String log) { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - createLogFileIfNotExist(); - final long currentTime = System.currentTimeMillis(); - mDate.setTime(currentTime); - - final String printString = String.format(Locale.US, "%s\t%d\t%s\n", - mDateFormat.format(mDate), currentTime, log); - if (LatinImeLogger.sDBG) { - Log.d(USABILITY_TAG, "Write: " + log); - } - mWriter.print(printString); - } - }); - } - - private synchronized String getBufferedLogs() { - mWriter.flush(); - StringBuilder sb = new StringBuilder(); - BufferedReader br = getBufferedReader(); - String line; - try { - while ((line = br.readLine()) != null) { - sb.append('\n'); - sb.append(line); - } - } catch (IOException e) { - Log.e(USABILITY_TAG, "Can't read log file."); - } finally { - if (LatinImeLogger.sDBG) { - Log.d(USABILITY_TAG, "Got all buffered logs\n" + sb.toString()); - } - try { - br.close(); - } catch (IOException e) { - // ignore. - } - } - return sb.toString(); - } - - public void emailResearcherLogsAll() { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - final Date date = new Date(); - date.setTime(System.currentTimeMillis()); - final String currentDateTimeString = - new SimpleDateFormat("yyyyMMdd-HHmmssZ", Locale.US).format(date); - if (mFile == null) { - Log.w(USABILITY_TAG, "No internal log file found."); - return; - } - if (mIms.checkCallingOrSelfPermission( - android.Manifest.permission.WRITE_EXTERNAL_STORAGE) - != PackageManager.PERMISSION_GRANTED) { - Log.w(USABILITY_TAG, "Doesn't have the permission WRITE_EXTERNAL_STORAGE"); - return; - } - mWriter.flush(); - final String destPath = Environment.getExternalStorageDirectory() - + "/research-" + currentDateTimeString + ".log"; - final File destFile = new File(destPath); - try { - final FileInputStream srcStream = new FileInputStream(mFile); - final FileOutputStream destStream = new FileOutputStream(destFile); - final FileChannel src = srcStream.getChannel(); - final FileChannel dest = destStream.getChannel(); - src.transferTo(0, src.size(), dest); - src.close(); - srcStream.close(); - dest.close(); - destStream.close(); - } catch (FileNotFoundException e1) { - Log.w(USABILITY_TAG, e1); - return; - } catch (IOException e2) { - Log.w(USABILITY_TAG, e2); - return; - } - if (destFile == null || !destFile.exists()) { - Log.w(USABILITY_TAG, "Dest file doesn't exist."); - return; - } - final Intent intent = new Intent(Intent.ACTION_SEND); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - if (LatinImeLogger.sDBG) { - Log.d(USABILITY_TAG, "Destination file URI is " + destFile.toURI()); - } - intent.setType("text/plain"); - intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + destPath)); - intent.putExtra(Intent.EXTRA_SUBJECT, - "[Research Logs] " + currentDateTimeString); - mIms.startActivity(intent); - } - }); - } - - public void printAll() { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - mIms.getCurrentInputConnection().commitText(getBufferedLogs(), 0); - } - }); - } - - public void clearAll() { - mLoggingHandler.post(new Runnable() { - @Override - public void run() { - if (mFile != null && mFile.exists()) { - if (LatinImeLogger.sDBG) { - Log.d(USABILITY_TAG, "Delete log file."); - } - mFile.delete(); - mWriter.close(); - } - } - }); - } - - private BufferedReader getBufferedReader() { - createLogFileIfNotExist(); - try { - return new BufferedReader(new FileReader(mFile)); - } catch (FileNotFoundException e) { - return null; - } - } - - private PrintWriter getPrintWriter( - File dir, String filename, boolean renew) throws IOException { - mFile = new File(dir, filename); - if (mFile.exists()) { - if (renew) { - mFile.delete(); - } - } - return new PrintWriter(new FileOutputStream(mFile), true /* autoFlush */); - } - } - - public static final class Stats { - public static void onNonSeparator(final char code, final int x, - final int y) { - RingCharBuffer.getInstance().push(code, x, y); - LatinImeLogger.logOnInputChar(); - } - - public static void onSeparator(final int code, final int x, final int y) { - // Helper method to log a single code point separator - // TODO: cache this mapping of a code point to a string in a sparse array in StringUtils - onSeparator(new String(new int[]{code}, 0, 1), x, y); - } - - public static void onSeparator(final String separator, final int x, final int y) { - final int length = separator.length(); - for (int i = 0; i < length; i = Character.offsetByCodePoints(separator, i, 1)) { - int codePoint = Character.codePointAt(separator, i); - // TODO: accept code points - RingCharBuffer.getInstance().push((char)codePoint, x, y); - } - LatinImeLogger.logOnInputSeparator(); - } - - public static void onAutoCorrection(final String typedWord, final String correctedWord, - final String separatorString, final WordComposer wordComposer) { - final boolean isBatchMode = wordComposer.isBatchMode(); - if (!isBatchMode && TextUtils.isEmpty(typedWord)) return; - // TODO: this fails when the separator is more than 1 code point long, but - // the backend can't handle it yet. The only case when this happens is with - // smileys and other multi-character keys. - final int codePoint = TextUtils.isEmpty(separatorString) ? Constants.NOT_A_CODE - : separatorString.codePointAt(0); - if (!isBatchMode) { - LatinImeLogger.logOnAutoCorrectionForTyping(typedWord, correctedWord, codePoint); - } else { - if (!TextUtils.isEmpty(correctedWord)) { - // We must make sure that InputPointer contains only the relative timestamps, - // not actual timestamps. - LatinImeLogger.logOnAutoCorrectionForGeometric( - "", correctedWord, codePoint, wordComposer.getInputPointers()); - } - } - } - - public static void onAutoCorrectionCancellation() { - LatinImeLogger.logOnAutoCorrectionCancelled(); - } - } - - public static String getDebugInfo(final SuggestedWords suggestions, final int pos) { - if (!LatinImeLogger.sDBG) return null; - final SuggestedWordInfo wordInfo = suggestions.getInfo(pos); - if (wordInfo == null) return null; - final String info = wordInfo.getDebugString(); - if (TextUtils.isEmpty(info)) return null; - return info; - } - - public static int getAcitivityTitleResId(Context context, Class<? extends Activity> cls) { - final ComponentName cn = new ComponentName(context, cls); - try { - final ActivityInfo ai = context.getPackageManager().getActivityInfo(cn, 0); - if (ai != null) { - return ai.labelRes; - } - } catch (NameNotFoundException e) { - Log.e(TAG, "Failed to get settings activity title res id.", e); - } - return 0; - } - - public static String getVersionName(Context context) { - try { - if (context == null) { - return ""; - } - final String packageName = context.getPackageName(); - PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); - return info.versionName; - } catch (NameNotFoundException e) { - Log.e(TAG, "Could not find version info.", e); - } - return ""; - } -} diff --git a/java/src/com/android/inputmethod/latin/WordComposer.java b/java/src/com/android/inputmethod/latin/WordComposer.java index e078f03f4..a09ca605c 100644 --- a/java/src/com/android/inputmethod/latin/WordComposer.java +++ b/java/src/com/android/inputmethod/latin/WordComposer.java @@ -18,6 +18,7 @@ package com.android.inputmethod.latin; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.Keyboard; +import com.android.inputmethod.latin.utils.StringUtils; import java.util.Arrays; @@ -25,7 +26,7 @@ import java.util.Arrays; * A place to store the currently composing word with information such as adjacent key codes as well */ public final class WordComposer { - private static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH; + private static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH; private static final boolean DBG = LatinImeLogger.sDBG; public static final int CAPS_MODE_OFF = 0; @@ -36,8 +37,16 @@ public final class WordComposer { public static final int CAPS_MODE_AUTO_SHIFTED = 0x5; public static final int CAPS_MODE_AUTO_SHIFT_LOCKED = 0x7; + // An array of code points representing the characters typed so far. + // The array is limited to MAX_WORD_LENGTH code points, but mTypedWord extends past that + // and mCodePointSize can go past that. If mCodePointSize is greater than MAX_WORD_LENGTH, + // this just does not contain the associated code points past MAX_WORD_LENGTH. private int[] mPrimaryKeyCodes; private final InputPointers mInputPointers = new InputPointers(MAX_WORD_LENGTH); + // This is the typed word, as a StringBuilder. This has the same contents as mPrimaryKeyCodes + // but under a StringBuilder representation for ease of use, depending on what is more useful + // at any given time. However this is not limited in size, while mPrimaryKeyCodes is limited + // to MAX_WORD_LENGTH code points. private final StringBuilder mTypedWord; private String mAutoCorrection; private boolean mIsResumed; @@ -55,6 +64,10 @@ public final class WordComposer { private int mDigitsCount; private int mCapitalizedMode; private int mTrailingSingleQuotesCount; + // This is the number of code points entered so far. This is not limited to MAX_WORD_LENGTH. + // In general, this contains the size of mPrimaryKeyCodes, except when this is greater than + // MAX_WORD_LENGTH in which case mPrimaryKeyCodes only contain the first MAX_WORD_LENGTH + // code points. private int mCodePointSize; private int mCursorPositionWithinWord; @@ -192,6 +205,49 @@ public final class WordComposer { return mCursorPositionWithinWord != mCodePointSize; } + /** + * When the cursor is moved by the user, we need to update its position. + * If it falls inside the currently composing word, we don't reset the composition, and + * only update the cursor position. + * + * @param expectedMoveAmount How many java chars to move the cursor. Negative values move + * the cursor backward, positive values move the cursor forward. + * @return true if the cursor is still inside the composing word, false otherwise. + */ + public boolean moveCursorByAndReturnIfInsideComposingWord(final int expectedMoveAmount) { + int actualMoveAmountWithinWord = 0; + int cursorPos = mCursorPositionWithinWord; + final int[] codePoints; + if (mCodePointSize >= MAX_WORD_LENGTH) { + // If we have more than MAX_WORD_LENGTH characters, we don't have everything inside + // mPrimaryKeyCodes. This should be rare enough that we can afford to just compute + // the array on the fly when this happens. + codePoints = StringUtils.toCodePointArray(mTypedWord.toString()); + } else { + codePoints = mPrimaryKeyCodes; + } + if (expectedMoveAmount >= 0) { + // Moving the cursor forward for the expected amount or until the end of the word has + // been reached, whichever comes first. + while (actualMoveAmountWithinWord < expectedMoveAmount && cursorPos < mCodePointSize) { + actualMoveAmountWithinWord += Character.charCount(codePoints[cursorPos]); + ++cursorPos; + } + } else { + // Moving the cursor backward for the expected amount or until the start of the word + // has been reached, whichever comes first. + while (actualMoveAmountWithinWord > expectedMoveAmount && cursorPos > 0) { + --cursorPos; + actualMoveAmountWithinWord -= Character.charCount(codePoints[cursorPos]); + } + } + // If the actual and expected amounts differ, we crossed the start or the end of the word + // so the result would not be inside the composing word. + if (actualMoveAmountWithinWord != expectedMoveAmount) return false; + mCursorPositionWithinWord = cursorPos; + return true; + } + public void setBatchInputPointers(final InputPointers batchPointers) { mInputPointers.set(batchPointers); mIsBatchMode = true; diff --git a/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java b/java/src/com/android/inputmethod/latin/debug/ExternalDictionaryGetterForDebug.java index 9f91639a2..028f78a87 100644 --- a/java/src/com/android/inputmethod/latin/ExternalDictionaryGetterForDebug.java +++ b/java/src/com/android/inputmethod/latin/debug/ExternalDictionaryGetterForDebug.java @@ -14,15 +14,22 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.debug; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; +import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.os.Environment; +import com.android.inputmethod.latin.BinaryDictionaryFileDumper; +import com.android.inputmethod.latin.BinaryDictionaryGetter; +import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.DictionaryInfoUtils; +import com.android.inputmethod.latin.utils.LocaleUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -56,7 +63,7 @@ public class ExternalDictionaryGetterForDebug { if (0 == fileNames.length) { showNoFileDialog(context); } else if (1 == fileNames.length) { - askInstallFile(context, fileNames[0]); + askInstallFile(context, SOURCE_FOLDER, fileNames[0], null /* completeRunnable */); } else { showChooseFileDialog(context, fileNames); } @@ -79,14 +86,19 @@ public class ExternalDictionaryGetterForDebug { .setItems(fileNames, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { - askInstallFile(context, fileNames[which]); + askInstallFile(context, SOURCE_FOLDER, fileNames[which], + null /* completeRunnable */); } }) .create().show(); } - private static void askInstallFile(final Context context, final String fileName) { - final File file = new File(SOURCE_FOLDER, fileName.toString()); + /** + * Shows a dialog which offers the user to install the external dictionary. + */ + public static void askInstallFile(final Context context, final String dirPath, + final String fileName, final Runnable completeRunnable) { + final File file = new File(dirPath, fileName.toString()); final FileHeader header = DictionaryInfoUtils.getDictionaryFileHeaderOrNull(file); final StringBuilder message = new StringBuilder(); final String locale = header.getLocaleString(); @@ -106,12 +118,26 @@ public class ExternalDictionaryGetterForDebug { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); + if (completeRunnable != null) { + completeRunnable.run(); + } } }).setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { installFile(context, file, header); dialog.dismiss(); + if (completeRunnable != null) { + completeRunnable.run(); + } + } + }).setOnCancelListener(new OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + // Canceled by the user by hitting the back key + if (completeRunnable != null) { + completeRunnable.run(); + } } }).create().show(); } diff --git a/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java b/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java index c87a9254d..167c6915c 100644 --- a/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java +++ b/java/src/com/android/inputmethod/latin/makedict/BinaryDictIOUtils.java @@ -181,7 +181,7 @@ public final class BinaryDictIOUtils { final FileHeader header = BinaryDictInputOutput.readHeader(buffer); int wordPos = 0; final int wordLen = word.codePointCount(0, word.length()); - for (int depth = 0; depth < Constants.Dictionary.MAX_WORD_LENGTH; ++depth) { + for (int depth = 0; depth < Constants.DICTIONARY_MAX_WORD_LENGTH; ++depth) { if (wordPos >= wordLen) return FormatSpec.NOT_VALID_WORD; do { @@ -746,7 +746,7 @@ public final class BinaryDictIOUtils { final int[] codePoints = FusionDictionary.getCodePoints(word); final int wordLen = codePoints.length; - for (int depth = 0; depth < Constants.Dictionary.MAX_WORD_LENGTH; ++depth) { + for (int depth = 0; depth < Constants.DICTIONARY_MAX_WORD_LENGTH; ++depth) { if (wordPos >= wordLen) break; nodeOriginAddress = buffer.position(); int nodeParentAddress = -1; @@ -982,6 +982,7 @@ public final class BinaryDictIOUtils { return null; } + private static final int HEADER_READING_BUFFER_SIZE = 16384; /** * Convenience method to read the header of a binary file. * @@ -991,7 +992,6 @@ public final class BinaryDictIOUtils { * @param offset The offset in the file where to start reading the data. * @param length The length of the data file. */ - private static final int HEADER_READING_BUFFER_SIZE = 16384; public static FileHeader getDictionaryFileHeader( final File file, final long offset, final long length) throws FileNotFoundException, IOException, UnsupportedFormatException { diff --git a/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java b/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java index 467f6a053..1b187d85d 100644 --- a/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java +++ b/java/src/com/android/inputmethod/latin/makedict/BinaryDictInputOutput.java @@ -389,7 +389,7 @@ public final class BinaryDictInputOutput { * @param node the node to compute the maximum size of. * @param options file format options. */ - private static void setNodeMaximumSize(final Node node, final FormatOptions options) { + private static void calculateNodeMaximumSize(final Node node, final FormatOptions options) { int size = getGroupCountSize(node); for (CharGroup g : node.mData) { final int groupSize = getCharGroupMaximumSize(g, options); @@ -518,14 +518,56 @@ public final class BinaryDictInputOutput { } /** - * Finds the absolute address of a word in the dictionary. + * Get the offset from a position inside a current node to a target node, during update. * - * @param dict the dictionary in which to search. - * @param word the word we are searching for. - * @return the word address. If it is not found, an exception is thrown. + * If the current node is before the target node, the target node has not been updated yet, + * so we should return the offset from the old position of the current node to the old position + * of the target node. If on the other hand the target is before the current node, it already + * has been updated, so we should return the offset from the new position in the current node + * to the new position in the target node. + * @param currentNode the node containing the CharGroup where the offset will be written + * @param offsetFromStartOfCurrentNode the offset, in bytes, from the start of currentNode + * @param targetNode the target node to get the offset to + * @return the offset to the target node */ - private static int findAddressOfWord(final FusionDictionary dict, final String word) { - return FusionDictionary.findWordInTree(dict.mRoot, word).mCachedAddress; + private static int getOffsetToTargetNodeDuringUpdate(final Node currentNode, + final int offsetFromStartOfCurrentNode, final Node targetNode) { + final boolean isTargetBeforeCurrent = (targetNode.mCachedAddressBeforeUpdate + < currentNode.mCachedAddressBeforeUpdate); + if (isTargetBeforeCurrent) { + return targetNode.mCachedAddressAfterUpdate + - (currentNode.mCachedAddressAfterUpdate + offsetFromStartOfCurrentNode); + } else { + return targetNode.mCachedAddressBeforeUpdate + - (currentNode.mCachedAddressBeforeUpdate + offsetFromStartOfCurrentNode); + } + } + + /** + * Get the offset from a position inside a current node to a target CharGroup, during update. + * @param currentNode the node containing the CharGroup where the offset will be written + * @param offsetFromStartOfCurrentNode the offset, in bytes, from the start of currentNode + * @param targetCharGroup the target CharGroup to get the offset to + * @return the offset to the target CharGroup + */ + // TODO: is there any way to factorize this method with the one above? + private static int getOffsetToTargetCharGroupDuringUpdate(final Node currentNode, + final int offsetFromStartOfCurrentNode, final CharGroup targetCharGroup) { + final int oldOffsetBasePoint = currentNode.mCachedAddressBeforeUpdate + + offsetFromStartOfCurrentNode; + final boolean isTargetBeforeCurrent = (targetCharGroup.mCachedAddressBeforeUpdate + < oldOffsetBasePoint); + // If the target is before the current node, then its address has already been updated. + // We can use the AfterUpdate member, and compare it to our own member after update. + // Otherwise, the AfterUpdate member is not updated yet, so we need to use the BeforeUpdate + // member, and of course we have to compare this to our own address before update. + if (isTargetBeforeCurrent) { + final int newOffsetBasePoint = currentNode.mCachedAddressAfterUpdate + + offsetFromStartOfCurrentNode; + return targetCharGroup.mCachedAddressAfterUpdate - newOffsetBasePoint; + } else { + return targetCharGroup.mCachedAddressBeforeUpdate - oldOffsetBasePoint; + } } /** @@ -548,33 +590,28 @@ public final class BinaryDictInputOutput { boolean changed = false; int size = getGroupCountSize(node); for (CharGroup group : node.mData) { - if (group.mCachedAddress != node.mCachedAddress + size) { + group.mCachedAddressAfterUpdate = node.mCachedAddressAfterUpdate + size; + if (group.mCachedAddressAfterUpdate != group.mCachedAddressBeforeUpdate) { changed = true; - group.mCachedAddress = node.mCachedAddress + size; } int groupSize = getGroupHeaderSize(group, formatOptions); if (group.isTerminal()) groupSize += FormatSpec.GROUP_FREQUENCY_SIZE; if (null == group.mChildren && formatOptions.mSupportsDynamicUpdate) { groupSize += FormatSpec.SIGNED_CHILDREN_ADDRESS_SIZE; } else if (null != group.mChildren) { - final int offsetBasePoint = groupSize + node.mCachedAddress + size; - final int offset = group.mChildren.mCachedAddress - offsetBasePoint; - // assign my address to children's parent address - group.mChildren.mCachedParentAddress = group.mCachedAddress - - group.mChildren.mCachedAddress; if (formatOptions.mSupportsDynamicUpdate) { groupSize += FormatSpec.SIGNED_CHILDREN_ADDRESS_SIZE; } else { - groupSize += getByteSize(offset); + groupSize += getByteSize(getOffsetToTargetNodeDuringUpdate(node, + groupSize + size, group.mChildren)); } } groupSize += getShortcutListSize(group.mShortcutTargets); if (null != group.mBigrams) { for (WeightedString bigram : group.mBigrams) { - final int offsetBasePoint = groupSize + node.mCachedAddress + size - + FormatSpec.GROUP_FLAGS_SIZE; - final int addressOfBigram = findAddressOfWord(dict, bigram.mWord); - final int offset = addressOfBigram - offsetBasePoint; + final int offset = getOffsetToTargetCharGroupDuringUpdate(node, + groupSize + size + FormatSpec.GROUP_FLAGS_SIZE, + FusionDictionary.findWordInTree(dict.mRoot, bigram.mWord)); groupSize += getByteSize(offset) + FormatSpec.GROUP_FLAGS_SIZE; } } @@ -592,35 +629,69 @@ public final class BinaryDictInputOutput { } /** - * Computes the byte size of a list of nodes and updates each node cached position. + * Initializes the cached addresses of nodes from their size. * * @param flatNodes the array of nodes. * @param formatOptions file format options. * @return the byte size of the entire stack. */ - private static int stackNodes(final ArrayList<Node> flatNodes, + private static int initializeNodesCachedAddresses(final ArrayList<Node> flatNodes, final FormatOptions formatOptions) { int nodeOffset = 0; - for (Node n : flatNodes) { - n.mCachedAddress = nodeOffset; + for (final Node n : flatNodes) { + n.mCachedAddressBeforeUpdate = nodeOffset; int groupCountSize = getGroupCountSize(n); int groupOffset = 0; - for (CharGroup g : n.mData) { - g.mCachedAddress = groupCountSize + nodeOffset + groupOffset; + for (final CharGroup g : n.mData) { + g.mCachedAddressBeforeUpdate = g.mCachedAddressAfterUpdate = + groupCountSize + nodeOffset + groupOffset; groupOffset += g.mCachedSize; } final int nodeSize = groupCountSize + groupOffset + (formatOptions.mSupportsDynamicUpdate ? FormatSpec.FORWARD_LINK_ADDRESS_SIZE : 0); - if (nodeSize != n.mCachedSize) { - throw new RuntimeException("Bug : Stored and computed node size differ"); - } nodeOffset += n.mCachedSize; } return nodeOffset; } /** + * Updates the cached addresses of nodes after recomputing their new positions. + * + * @param flatNodes the array of nodes. + */ + private static void updateNodeCachedAddresses(final ArrayList<Node> flatNodes) { + for (final Node n : flatNodes) { + n.mCachedAddressBeforeUpdate = n.mCachedAddressAfterUpdate; + for (final CharGroup g : n.mData) { + g.mCachedAddressBeforeUpdate = g.mCachedAddressAfterUpdate; + } + } + } + + /** + * Compute the cached parent addresses after all has been updated. + * + * The parent addresses are used by some binary formats at write-to-disk time. Not all formats + * need them. In particular, version 2 does not need them, and version 3 does. + * + * @param flatNodes the flat array of nodes to fill in + */ + private static void computeParentAddresses(final ArrayList<Node> flatNodes) { + for (final Node node : flatNodes) { + for (final CharGroup group : node.mData) { + if (null != group.mChildren) { + // Assign my address to children's parent address + // Here BeforeUpdate and AfterUpdate addresses have the same value, so it + // does not matter which we use. + group.mChildren.mCachedParentAddress = group.mCachedAddressAfterUpdate + - group.mChildren.mCachedAddressAfterUpdate; + } + } + } + } + + /** * Compute the addresses and sizes of an ordered node array. * * This method takes a node array and will update its cached address and size values @@ -637,9 +708,9 @@ public final class BinaryDictInputOutput { */ private static ArrayList<Node> computeAddresses(final FusionDictionary dict, final ArrayList<Node> flatNodes, final FormatOptions formatOptions) { - // First get the worst sizes and offsets - for (Node n : flatNodes) setNodeMaximumSize(n, formatOptions); - final int offset = stackNodes(flatNodes, formatOptions); + // First get the worst possible sizes and offsets + for (final Node n : flatNodes) calculateNodeMaximumSize(n, formatOptions); + final int offset = initializeNodesCachedAddresses(flatNodes, formatOptions); MakedictLog.i("Compressing the array addresses. Original size : " + offset); MakedictLog.i("(Recursively seen size : " + offset + ")"); @@ -648,22 +719,28 @@ public final class BinaryDictInputOutput { boolean changesDone = false; do { changesDone = false; - for (Node n : flatNodes) { + int nodeStartOffset = 0; + for (final Node n : flatNodes) { + n.mCachedAddressAfterUpdate = nodeStartOffset; final int oldNodeSize = n.mCachedSize; final boolean changed = computeActualNodeSize(n, dict, formatOptions); final int newNodeSize = n.mCachedSize; if (oldNodeSize < newNodeSize) throw new RuntimeException("Increased size ?!"); + nodeStartOffset += newNodeSize; changesDone |= changed; } - stackNodes(flatNodes, formatOptions); + updateNodeCachedAddresses(flatNodes); ++passes; if (passes > MAX_PASSES) throw new RuntimeException("Too many passes - probably a bug"); } while (changesDone); + if (formatOptions.mSupportsDynamicUpdate) { + computeParentAddresses(flatNodes); + } final Node lastNode = flatNodes.get(flatNodes.size() - 1); MakedictLog.i("Compression complete in " + passes + " passes."); MakedictLog.i("After address compression : " - + (lastNode.mCachedAddress + lastNode.mCachedSize)); + + (lastNode.mCachedAddressAfterUpdate + lastNode.mCachedSize)); return flatNodes; } @@ -681,10 +758,12 @@ public final class BinaryDictInputOutput { private static void checkFlatNodeArray(final ArrayList<Node> array) { int offset = 0; int index = 0; - for (Node n : array) { - if (n.mCachedAddress != offset) { + for (final Node n : array) { + // BeforeUpdate and AfterUpdate addresses are the same here, so it does not matter + // which we use. + if (n.mCachedAddressAfterUpdate != offset) { throw new RuntimeException("Wrong address for node " + index - + " : expected " + offset + ", got " + n.mCachedAddress); + + " : expected " + offset + ", got " + n.mCachedAddressAfterUpdate); } ++index; offset += n.mCachedSize; @@ -926,7 +1005,7 @@ public final class BinaryDictInputOutput { private static int writePlacedNode(final FusionDictionary dict, byte[] buffer, final Node node, final FormatOptions formatOptions) { // TODO: Make the code in common with BinaryDictIOUtils#writeCharGroup - int index = node.mCachedAddress; + int index = node.mCachedAddressAfterUpdate; final int groupCount = node.mData.size(); final int countSize = getGroupCountSize(node); @@ -943,10 +1022,11 @@ public final class BinaryDictInputOutput { } int groupAddress = index; for (int i = 0; i < groupCount; ++i) { - CharGroup group = node.mData.get(i); - if (index != group.mCachedAddress) throw new RuntimeException("Bug: write index is not " - + "the same as the cached address of the group : " - + index + " <> " + group.mCachedAddress); + final CharGroup group = node.mData.get(i); + if (index != group.mCachedAddressAfterUpdate) { + throw new RuntimeException("Bug: write index is not the same as the cached address " + + "of the group : " + index + " <> " + group.mCachedAddressAfterUpdate); + } groupAddress += getGroupHeaderSize(group, formatOptions); // Sanity checks. if (DBG && group.mFrequency > FormatSpec.MAX_TERMINAL_FREQUENCY) { @@ -957,15 +1037,15 @@ public final class BinaryDictInputOutput { if (group.mFrequency >= 0) groupAddress += FormatSpec.GROUP_FREQUENCY_SIZE; final int childrenOffset = null == group.mChildren ? FormatSpec.NO_CHILDREN_ADDRESS - : group.mChildren.mCachedAddress - groupAddress; - byte flags = makeCharGroupFlags(group, groupAddress, childrenOffset, formatOptions); - buffer[index++] = flags; + : group.mChildren.mCachedAddressAfterUpdate - groupAddress; + buffer[index++] = + makeCharGroupFlags(group, groupAddress, childrenOffset, formatOptions); if (parentAddress == FormatSpec.NO_PARENT_ADDRESS) { index = writeParentAddress(buffer, index, parentAddress, formatOptions); } else { - index = writeParentAddress(buffer, index, - parentAddress + (node.mCachedAddress - group.mCachedAddress), + index = writeParentAddress(buffer, index, parentAddress + + (node.mCachedAddressAfterUpdate - group.mCachedAddressAfterUpdate), formatOptions); } @@ -1016,7 +1096,7 @@ public final class BinaryDictInputOutput { final WeightedString bigram = bigramIterator.next(); final CharGroup target = FusionDictionary.findWordInTree(dict.mRoot, bigram.mWord); - final int addressOfBigram = target.mCachedAddress; + final int addressOfBigram = target.mCachedAddressAfterUpdate; final int unigramFrequencyForThisWord = target.mFrequency; ++groupAddress; final int offset = addressOfBigram - groupAddress; @@ -1035,9 +1115,9 @@ public final class BinaryDictInputOutput { = FormatSpec.NO_FORWARD_LINK_ADDRESS; index += FormatSpec.FORWARD_LINK_ADDRESS_SIZE; } - if (index != node.mCachedAddress + node.mCachedSize) throw new RuntimeException( + if (index != node.mCachedAddressAfterUpdate + node.mCachedSize) throw new RuntimeException( "Not the same size : written " - + (index - node.mCachedAddress) + " bytes out of a node that should have " + + (index - node.mCachedAddressAfterUpdate) + " bytes from a node that should have " + node.mCachedSize + " bytes"); return index; } @@ -1057,25 +1137,27 @@ public final class BinaryDictInputOutput { int charGroups = 0; int maxGroups = 0; int maxRuns = 0; - for (Node n : nodes) { + for (final Node n : nodes) { if (maxGroups < n.mData.size()) maxGroups = n.mData.size(); - for (CharGroup cg : n.mData) { + for (final CharGroup cg : n.mData) { ++charGroups; if (cg.mChars.length > maxRuns) maxRuns = cg.mChars.length; if (cg.mFrequency >= 0) { - if (n.mCachedAddress < firstTerminalAddress) - firstTerminalAddress = n.mCachedAddress; - if (n.mCachedAddress > lastTerminalAddress) - lastTerminalAddress = n.mCachedAddress; + if (n.mCachedAddressAfterUpdate < firstTerminalAddress) + firstTerminalAddress = n.mCachedAddressAfterUpdate; + if (n.mCachedAddressAfterUpdate > lastTerminalAddress) + lastTerminalAddress = n.mCachedAddressAfterUpdate; } } - if (n.mCachedAddress + n.mCachedSize > size) size = n.mCachedAddress + n.mCachedSize; + if (n.mCachedAddressAfterUpdate + n.mCachedSize > size) { + size = n.mCachedAddressAfterUpdate + n.mCachedSize; + } } final int[] groupCounts = new int[maxGroups + 1]; final int[] runCounts = new int[maxRuns + 1]; - for (Node n : nodes) { + for (final Node n : nodes) { ++groupCounts[n.mData.size()]; - for (CharGroup cg : n.mData) { + for (final CharGroup cg : n.mData) { ++runCounts[cg.mChars.length]; } } @@ -1185,7 +1267,7 @@ public final class BinaryDictInputOutput { // Create a buffer that matches the final dictionary size. final Node lastNode = flatNodes.get(flatNodes.size() - 1); - final int bufferSize = lastNode.mCachedAddress + lastNode.mCachedSize; + final int bufferSize = lastNode.mCachedAddressAfterUpdate + lastNode.mCachedSize; final byte[] buffer = new byte[bufferSize]; int index = 0; @@ -1564,8 +1646,9 @@ public final class BinaryDictInputOutput { buffer.position() != FormatSpec.NO_FORWARD_LINK_ADDRESS); final Node node = new Node(nodeContents); - node.mCachedAddress = nodeOrigin; - reverseNodeMap.put(node.mCachedAddress, node); + node.mCachedAddressBeforeUpdate = nodeOrigin; + node.mCachedAddressAfterUpdate = nodeOrigin; + reverseNodeMap.put(node.mCachedAddressAfterUpdate, node); return node; } diff --git a/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java b/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java index e1e5e5500..feadcda76 100644 --- a/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java +++ b/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java @@ -167,7 +167,7 @@ public final class FormatSpec { // TODO: Make this value adaptative to content data, store it in the header, and // use it in the reading code. - static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH; + static final int MAX_WORD_LENGTH = Constants.DICTIONARY_MAX_WORD_LENGTH; static final int PARENT_ADDRESS_SIZE = 3; static final int FORWARD_LINK_ADDRESS_SIZE = 3; diff --git a/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java b/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java index 17d281518..118dc22b8 100644 --- a/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java +++ b/java/src/com/android/inputmethod/latin/makedict/FusionDictionary.java @@ -34,6 +34,8 @@ import java.util.LinkedList; public final class FusionDictionary implements Iterable<Word> { private static final boolean DBG = MakedictLog.DBG; + private static int CHARACTER_NOT_FOUND_INDEX = -1; + /** * A node of the dictionary, containing several CharGroups. * @@ -46,7 +48,13 @@ public final class FusionDictionary implements Iterable<Word> { ArrayList<CharGroup> mData; // To help with binary generation int mCachedSize = Integer.MIN_VALUE; - int mCachedAddress = Integer.MIN_VALUE; + // mCachedAddressBefore/AfterUpdate are helpers for binary dictionary generation. They + // always hold the same value except between dictionary address compression, during which + // the update process needs to know about both values at the same time. Updating will + // update the AfterUpdate value, and the code will move them to BeforeUpdate before + // the next update pass. + int mCachedAddressBeforeUpdate = Integer.MIN_VALUE; + int mCachedAddressAfterUpdate = Integer.MIN_VALUE; int mCachedParentAddress = 0; public Node() { @@ -105,9 +113,15 @@ public final class FusionDictionary implements Iterable<Word> { Node mChildren; boolean mIsNotAWord; // Only a shortcut boolean mIsBlacklistEntry; - // The two following members to help with binary generation - int mCachedSize; - int mCachedAddress; + // mCachedSize and mCachedAddressBefore/AfterUpdate are helpers for binary dictionary + // generation. Before and After always hold the same value except during dictionary + // address compression, where the update process needs to know about both values at the + // same time. Updating will update the AfterUpdate value, and the code will move them + // to BeforeUpdate before the next update pass. + // The update process does not need two versions of mCachedSize. + int mCachedSize; // The size, in bytes, of this char group. + int mCachedAddressBeforeUpdate; // The address of this char group (before update) + int mCachedAddressAfterUpdate; // The address of this char group (after update) public CharGroup(final int[] chars, final ArrayList<WeightedString> shortcutTargets, final ArrayList<WeightedString> bigrams, final int frequency, @@ -450,7 +464,7 @@ public final class FusionDictionary implements Iterable<Word> { final ArrayList<WeightedString> shortcutTargets, final boolean isNotAWord, final boolean isBlacklistEntry) { assert(frequency >= 0 && frequency <= 255); - if (word.length >= Constants.Dictionary.MAX_WORD_LENGTH) { + if (word.length >= Constants.DICTIONARY_MAX_WORD_LENGTH) { MakedictLog.w("Ignoring a word that is too long: word.length = " + word.length); return; } @@ -461,7 +475,7 @@ public final class FusionDictionary implements Iterable<Word> { CharGroup currentGroup = null; int differentCharIndex = 0; // Set by the loop to the index of the char that differs int nodeIndex = findIndexOfChar(mRoot, word[charIndex]); - while (CHARACTER_NOT_FOUND != nodeIndex) { + while (CHARACTER_NOT_FOUND_INDEX != nodeIndex) { currentGroup = currentNode.mData.get(nodeIndex); differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex); if (ARRAYS_ARE_EQUAL != differentCharIndex @@ -473,7 +487,7 @@ public final class FusionDictionary implements Iterable<Word> { nodeIndex = findIndexOfChar(currentNode, word[charIndex]); } - if (-1 == nodeIndex) { + if (CHARACTER_NOT_FOUND_INDEX == nodeIndex) { // No node at this point to accept the word. Create one. final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]); final CharGroup newGroup = new CharGroup( @@ -600,20 +614,18 @@ public final class FusionDictionary implements Iterable<Word> { return result >= 0 ? result : -result - 1; } - private static int CHARACTER_NOT_FOUND = -1; - /** * Find the index of a char in a node, if it exists. * * @param node the node to search in. * @param character the character to search for. - * @return the position of the character if it's there, or CHARACTER_NOT_FOUND = -1 else. + * @return the position of the character if it's there, or CHARACTER_NOT_FOUND_INDEX = -1 else. */ private static int findIndexOfChar(final Node node, int character) { final int insertionIndex = findInsertionIndex(node, character); - if (node.mData.size() <= insertionIndex) return CHARACTER_NOT_FOUND; + if (node.mData.size() <= insertionIndex) return CHARACTER_NOT_FOUND_INDEX; return character == node.mData.get(insertionIndex).mChars[0] ? insertionIndex - : CHARACTER_NOT_FOUND; + : CHARACTER_NOT_FOUND_INDEX; } /** @@ -628,7 +640,7 @@ public final class FusionDictionary implements Iterable<Word> { CharGroup currentGroup; do { int indexOfGroup = findIndexOfChar(node, codePoints[index]); - if (CHARACTER_NOT_FOUND == indexOfGroup) return null; + if (CHARACTER_NOT_FOUND_INDEX == indexOfGroup) return null; currentGroup = node.mData.get(indexOfGroup); if (codePoints.length - index < currentGroup.mChars.length) return null; diff --git a/java/src/com/android/inputmethod/latin/personalization/AccountUtils.java b/java/src/com/android/inputmethod/latin/personalization/AccountUtils.java index 93687e193..a446672cb 100644 --- a/java/src/com/android/inputmethod/latin/personalization/AccountUtils.java +++ b/java/src/com/android/inputmethod/latin/personalization/AccountUtils.java @@ -23,6 +23,7 @@ import android.util.Patterns; import java.util.ArrayList; import java.util.List; +import java.util.Locale; public class AccountUtils { private AccountUtils() { @@ -44,4 +45,22 @@ public class AccountUtils { } return retval; } + + /** + * Get all device accounts having specified domain name. + * @param context application context + * @param domain domain name used for filtering + * @return List of account names that contain the specified domain name + */ + public static List<String> getDeviceAccountsWithDomain( + final Context context, final String domain) { + final ArrayList<String> retval = new ArrayList<String>(); + final String atDomain = "@" + domain.toLowerCase(Locale.ROOT); + for (final Account account : getAccounts(context)) { + if (account.name.toLowerCase(Locale.ROOT).endsWith(atDomain)) { + retval.add(account.name); + } + } + return retval; + } } diff --git a/java/src/com/android/inputmethod/latin/UserHistoryDictionary.java b/java/src/com/android/inputmethod/latin/personalization/DynamicPredictionDictionaryBase.java index 528028328..9d041f4eb 100644 --- a/java/src/com/android/inputmethod/latin/UserHistoryDictionary.java +++ b/java/src/com/android/inputmethod/latin/personalization/DynamicPredictionDictionaryBase.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 The Android Open Source Project + * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.personalization; import android.content.Context; import android.content.SharedPreferences; @@ -23,33 +23,40 @@ import android.util.Log; import com.android.inputmethod.annotations.UsedForTesting; import com.android.inputmethod.keyboard.ProximityInfo; +import com.android.inputmethod.latin.Constants; +import com.android.inputmethod.latin.ExpandableDictionary; +import com.android.inputmethod.latin.LatinImeLogger; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.UserHistoryDictIOUtils.BigramDictionaryInterface; -import com.android.inputmethod.latin.UserHistoryDictIOUtils.OnAddWordListener; -import com.android.inputmethod.latin.UserHistoryForgettingCurveUtils.ForgettingCurveParams; +import com.android.inputmethod.latin.WordComposer; import com.android.inputmethod.latin.makedict.FormatSpec.FormatOptions; +import com.android.inputmethod.latin.settings.Settings; +import com.android.inputmethod.latin.utils.ByteArrayWrapper; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils.BigramDictionaryInterface; +import com.android.inputmethod.latin.utils.UserHistoryDictIOUtils.OnAddWordListener; +import com.android.inputmethod.latin.utils.UserHistoryForgettingCurveUtils; +import com.android.inputmethod.latin.utils.UserHistoryForgettingCurveUtils.ForgettingCurveParams; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; -import java.lang.ref.SoftReference; import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** - * Locally gathers stats about the words user types and various other signals like auto-correction - * cancellation or manual picks. This allows the keyboard to adapt to the typist over time. + * This class is a base class of a dictionary for the personalized prediction language model. */ -public final class UserHistoryDictionary extends ExpandableDictionary { - private static final String TAG = UserHistoryDictionary.class.getSimpleName(); - private static final String NAME = UserHistoryDictionary.class.getSimpleName(); +public abstract class DynamicPredictionDictionaryBase extends ExpandableDictionary { + public static void registerUpdateListener(PersonalizationDictionaryUpdateListener listener) { + // TODO: Implement + } + + private static final String TAG = DynamicPredictionDictionaryBase.class.getSimpleName(); public static final boolean DBG_SAVE_RESTORE = false; - public static final boolean DBG_STRESS_TEST = false; - public static final boolean DBG_ALWAYS_WRITE = false; - public static final boolean PROFILE_SAVE_RESTORE = LatinImeLogger.sDBG; + private static final boolean DBG_STRESS_TEST = false; + private static final boolean PROFILE_SAVE_RESTORE = LatinImeLogger.sDBG; private static final FormatOptions VERSION3 = new FormatOptions(3, true /* supportsDynamicUpdate */); @@ -58,14 +65,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary { private static final int FREQUENCY_FOR_TYPED = 2; /** Maximum number of pairs. Pruning will start when databases goes above this number. */ - public static final int MAX_HISTORY_BIGRAMS = 10000; - - /** - * When it hits maximum bigram pair, it will delete until you are left with - * only (sMaxHistoryBigrams - sDeleteHistoryBigrams) pairs. - * Do not keep this number small to avoid deleting too often. - */ - public static final int DELETE_HISTORY_BIGRAMS = 1000; + private static final int MAX_HISTORY_BIGRAMS = 10000; /** Locale for which this user history dictionary is storing words */ private final String mLocale; @@ -78,30 +78,9 @@ public final class UserHistoryDictionary extends ExpandableDictionary { // Should always be false except when we use this class for test @UsedForTesting boolean isTest = false; - private static final ConcurrentHashMap<String, SoftReference<UserHistoryDictionary>> - sLangDictCache = CollectionUtils.newConcurrentHashMap(); - - public static synchronized UserHistoryDictionary getInstance( - final Context context, final String locale, final SharedPreferences sp) { - if (sLangDictCache.containsKey(locale)) { - final SoftReference<UserHistoryDictionary> ref = sLangDictCache.get(locale); - final UserHistoryDictionary dict = ref == null ? null : ref.get(); - if (dict != null) { - if (PROFILE_SAVE_RESTORE) { - Log.w(TAG, "Use cached UserHistoryDictionary for " + locale); - } - return dict; - } - } - final UserHistoryDictionary dict = - new UserHistoryDictionary(context, locale, sp); - sLangDictCache.put(locale, new SoftReference<UserHistoryDictionary>(dict)); - return dict; - } - - private UserHistoryDictionary(final Context context, final String locale, - final SharedPreferences sp) { - super(context, Dictionary.TYPE_USER_HISTORY); + /* package */ DynamicPredictionDictionaryBase(final Context context, final String locale, + final SharedPreferences sp, final String dictionaryType) { + super(context, dictionaryType); mLocale = locale; mPrefs = sp; if (mLocale != null && mLocale.length() > 1) { @@ -116,8 +95,8 @@ public final class UserHistoryDictionary extends ExpandableDictionary { // Also, the database is written to somewhat frequently, so it needs to be kept alive // throughout the life of the process. // mOpenHelper.close(); - // Ignore close because we cache UserHistoryDictionary for each language. See getInstance() - // above. + // Ignore close because we cache PersonalizationPredictionDictionary for each language. + // See getInstance() above. // super.close(); } @@ -147,8 +126,8 @@ public final class UserHistoryDictionary extends ExpandableDictionary { * The second word may not be null (a NullPointerException would be thrown). */ public int addToUserHistory(final String word1, final String word2, final boolean isValid) { - if (word2.length() >= Constants.Dictionary.MAX_WORD_LENGTH || - (word1 != null && word1.length() >= Constants.Dictionary.MAX_WORD_LENGTH)) { + if (word2.length() >= Constants.DICTIONARY_MAX_WORD_LENGTH || + (word1 != null && word1.length() >= Constants.DICTIONARY_MAX_WORD_LENGTH)) { return -1; } if (mBigramListLock.tryLock()) { @@ -198,7 +177,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary { } @Override - public void loadDictionaryAsync() { + public final void loadDictionaryAsync() { // This must be run on non-main thread mBigramListLock.lock(); try { @@ -208,48 +187,47 @@ public final class UserHistoryDictionary extends ExpandableDictionary { } } - private int profTotal; - private void loadDictionaryAsyncLocked() { + final int[] profTotalCount = { 0 }; + final String locale = getLocale(); if (DBG_STRESS_TEST) { try { - Log.w(TAG, "Start stress in loading: " + mLocale); + Log.w(TAG, "Start stress in loading: " + locale); Thread.sleep(15000); Log.w(TAG, "End stress in loading"); } catch (InterruptedException e) { } } - final long last = Settings.readLastUserHistoryWriteTime(mPrefs, mLocale); + final long last = Settings.readLastUserHistoryWriteTime(mPrefs, locale); final boolean initializing = last == 0; final long now = System.currentTimeMillis(); - profTotal = 0; - final String fileName = NAME + "." + mLocale + ".dict"; + final String fileName = getDictionaryFileName(); final ExpandableDictionary dictionary = this; final OnAddWordListener listener = new OnAddWordListener() { @Override public void setUnigram(final String word, final String shortcutTarget, final int frequency) { - profTotal++; if (DBG_SAVE_RESTORE) { Log.d(TAG, "load unigram: " + word + "," + frequency); } dictionary.addWord(word, shortcutTarget, frequency); - mBigramList.addBigram(null, word, (byte)frequency); + ++profTotalCount[0]; + addToBigramListLocked(null, word, (byte)frequency); } @Override public void setBigram(final String word1, final String word2, final int frequency) { - if (word1.length() < Constants.Dictionary.MAX_WORD_LENGTH - && word2.length() < Constants.Dictionary.MAX_WORD_LENGTH) { - profTotal++; + if (word1.length() < Constants.DICTIONARY_MAX_WORD_LENGTH + && word2.length() < Constants.DICTIONARY_MAX_WORD_LENGTH) { if (DBG_SAVE_RESTORE) { Log.d(TAG, "load bigram: " + word1 + "," + word2 + "," + frequency); } + ++profTotalCount[0]; dictionary.setBigramAndGetFrequency( word1, word2, initializing ? new ForgettingCurveParams(true) : new ForgettingCurveParams(frequency, now, last)); } - mBigramList.addBigram(word1, word2, (byte)frequency); + addToBigramListLocked(word1, word2, (byte)frequency); } }; @@ -261,7 +239,7 @@ public final class UserHistoryDictionary extends ExpandableDictionary { inStream = new FileInputStream(file); inStream.read(buffer); UserHistoryDictIOUtils.readDictionaryBinary( - new UserHistoryDictIOUtils.ByteArrayWrapper(buffer), listener); + new ByteArrayWrapper(buffer), listener); } catch (FileNotFoundException e) { // This is an expected condition: we don't have a user history dictionary for this // language yet. It will be created sometime later. @@ -278,11 +256,21 @@ public final class UserHistoryDictionary extends ExpandableDictionary { if (PROFILE_SAVE_RESTORE) { final long diff = System.currentTimeMillis() - now; Log.d(TAG, "PROF: Load UserHistoryDictionary: " - + mLocale + ", " + diff + "ms. load " + profTotal + "entries."); + + locale + ", " + diff + "ms. load " + profTotalCount[0] + "entries."); } } } + protected abstract String getDictionaryFileName(); + + protected String getLocale() { + return mLocale; + } + + private void addToBigramListLocked(String word0, String word1, byte fcValue) { + mBigramList.addBigram(word0, word1, fcValue); + } + /** * Async task to write pending words to the binarydicts. */ @@ -291,16 +279,16 @@ public final class UserHistoryDictionary extends ExpandableDictionary { private final UserHistoryDictionaryBigramList mBigramList; private final boolean mAddLevel0Bigrams; private final String mLocale; - private final UserHistoryDictionary mUserHistoryDictionary; + private final DynamicPredictionDictionaryBase mDynamicPredictionDictionary; private final SharedPreferences mPrefs; private final Context mContext; public UpdateBinaryTask(final UserHistoryDictionaryBigramList pendingWrites, - final String locale, final UserHistoryDictionary dict, + final String locale, final DynamicPredictionDictionaryBase dict, final SharedPreferences prefs, final Context context) { mBigramList = pendingWrites; mLocale = locale; - mUserHistoryDictionary = dict; + mDynamicPredictionDictionary = dict; mPrefs = prefs; mContext = context; mAddLevel0Bigrams = mBigramList.size() <= MAX_HISTORY_BIGRAMS; @@ -308,16 +296,20 @@ public final class UserHistoryDictionary extends ExpandableDictionary { @Override protected Void doInBackground(final Void... v) { - if (mUserHistoryDictionary.isTest) { + if (mDynamicPredictionDictionary.isTest) { // If isTest == true, wait until the lock is released. - mUserHistoryDictionary.mBigramListLock.lock(); + mDynamicPredictionDictionary.mBigramListLock.lock(); + try { + doWriteTaskLocked(); + } finally { + mDynamicPredictionDictionary.mBigramListLock.unlock(); + } + } else if (mDynamicPredictionDictionary.mBigramListLock.tryLock()) { try { doWriteTaskLocked(); } finally { - mUserHistoryDictionary.mBigramListLock.unlock(); + mDynamicPredictionDictionary.mBigramListLock.unlock(); } - } else if (mUserHistoryDictionary.mBigramListLock.tryLock()) { - doWriteTaskLocked(); } return null; } @@ -334,7 +326,8 @@ public final class UserHistoryDictionary extends ExpandableDictionary { } final long now = PROFILE_SAVE_RESTORE ? System.currentTimeMillis() : 0; - final String fileName = NAME + "." + mLocale + ".dict"; + final String fileName = + mDynamicPredictionDictionary.getDictionaryFileName(); final File file = new File(mContext.getFilesDir(), fileName); FileOutputStream out = null; @@ -370,7 +363,8 @@ public final class UserHistoryDictionary extends ExpandableDictionary { freq = FREQUENCY_FOR_TYPED; final byte prevFc = mBigramList.getBigrams(word1).get(word2); } else { // bigram - final NextWord nw = mUserHistoryDictionary.getBigramWord(word1, word2); + final NextWord nw = + mDynamicPredictionDictionary.getBigramWord(word1, word2); if (nw != null) { final ForgettingCurveParams fcp = nw.getFcParams(); final byte prevFc = mBigramList.getBigrams(word1).get(word2); @@ -395,7 +389,8 @@ public final class UserHistoryDictionary extends ExpandableDictionary { } @UsedForTesting - void forceAddWordForTest(final String word1, final String word2, final boolean isValid) { + /* package for test */ void forceAddWordForTest( + final String word1, final String word2, final boolean isValid) { mBigramListLock.lock(); try { addToUserHistory(word1, word2, isValid); diff --git a/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java new file mode 100644 index 000000000..19554d639 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionary.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.personalization; + +import com.android.inputmethod.latin.Dictionary; +import com.android.inputmethod.latin.ExpandableBinaryDictionary; + +import android.content.Context; + +/** + * This class is a dictionary for the personalized language model that uses binary dictionary. + */ +public class PersonalizationDictionary extends ExpandableBinaryDictionary { + private static final String NAME = "personalization"; + + public static void registerUpdateListener(PersonalizationDictionaryUpdateListener listener) { + // TODO: Implement + } + + /** Locale for which this user history dictionary is storing words */ + private final String mLocale; + + // Singleton + private PersonalizationDictionary(final Context context, final String locale) { + super(context, getFilenameWithLocale(NAME, locale), Dictionary.TYPE_PERSONALIZATION); + mLocale = locale; + } + + @Override + protected void loadDictionaryAsync() { + // TODO: Implement + } + + @Override + protected boolean hasContentChanged() { + // TODO: Implement + return false; + } + + @Override + protected boolean needsToReloadBeforeWriting() { + // TODO: Implement + return false; + } + + // TODO: Implement +} diff --git a/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionaryHelper.java b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionaryHelper.java new file mode 100644 index 000000000..9f013df1c --- /dev/null +++ b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionaryHelper.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.personalization; + +import com.android.inputmethod.latin.utils.CollectionUtils; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +import java.lang.ref.SoftReference; +import java.util.concurrent.ConcurrentHashMap; + +public class PersonalizationDictionaryHelper { + private static final String TAG = PersonalizationDictionaryHelper.class.getSimpleName(); + private static final boolean DEBUG = false; + + private static final ConcurrentHashMap<String, SoftReference<UserHistoryPredictionDictionary>> + sLangUserHistoryDictCache = CollectionUtils.newConcurrentHashMap(); + + private static final ConcurrentHashMap<String, + SoftReference<PersonalizationPredictionDictionary>> + sLangPersonalizationDictCache = CollectionUtils.newConcurrentHashMap(); + + public static UserHistoryPredictionDictionary getUserHistoryPredictionDictionary( + final Context context, final String locale, final SharedPreferences sp) { + synchronized (sLangUserHistoryDictCache) { + if (sLangUserHistoryDictCache.containsKey(locale)) { + final SoftReference<UserHistoryPredictionDictionary> ref = + sLangUserHistoryDictCache.get(locale); + final UserHistoryPredictionDictionary dict = ref == null ? null : ref.get(); + if (dict != null) { + if (DEBUG) { + Log.w(TAG, "Use cached UserHistoryPredictionDictionary for " + locale); + } + return dict; + } + } + final UserHistoryPredictionDictionary dict = + new UserHistoryPredictionDictionary(context, locale, sp); + sLangUserHistoryDictCache.put( + locale, new SoftReference<UserHistoryPredictionDictionary>(dict)); + return dict; + } + } + + public static PersonalizationPredictionDictionary getPersonalizationPredictionDictionary( + final Context context, final String locale, final SharedPreferences sp) { + synchronized (sLangPersonalizationDictCache) { + if (sLangPersonalizationDictCache.containsKey(locale)) { + final SoftReference<PersonalizationPredictionDictionary> ref = + sLangPersonalizationDictCache.get(locale); + final PersonalizationPredictionDictionary dict = ref == null ? null : ref.get(); + if (dict != null) { + if (DEBUG) { + Log.w(TAG, "Use cached PersonalizationPredictionDictionary for " + locale); + } + return dict; + } + } + final PersonalizationPredictionDictionary dict = + new PersonalizationPredictionDictionary(context, locale, sp); + sLangPersonalizationDictCache.put( + locale, new SoftReference<PersonalizationPredictionDictionary>(dict)); + return dict; + } + } +} diff --git a/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionaryUpdateListener.java b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionaryUpdateListener.java new file mode 100644 index 000000000..c78e5a95b --- /dev/null +++ b/java/src/com/android/inputmethod/latin/personalization/PersonalizationDictionaryUpdateListener.java @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.personalization; + +public interface PersonalizationDictionaryUpdateListener { + // TODO: Implement +} diff --git a/java/src/com/android/inputmethod/latin/personalization/PersonalizationPredictionDictionary.java b/java/src/com/android/inputmethod/latin/personalization/PersonalizationPredictionDictionary.java new file mode 100644 index 000000000..955bd2762 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/personalization/PersonalizationPredictionDictionary.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.personalization; + +import com.android.inputmethod.latin.Dictionary; + +import android.content.Context; +import android.content.SharedPreferences; + +public class PersonalizationPredictionDictionary extends DynamicPredictionDictionaryBase { + private static final String NAME = PersonalizationPredictionDictionary.class.getSimpleName(); + + /* package */ PersonalizationPredictionDictionary(final Context context, final String locale, + final SharedPreferences sp) { + super(context, locale, sp, Dictionary.TYPE_PERSONALIZATION_PREDICTION_IN_JAVA); + } + + @Override + protected String getDictionaryFileName() { + return NAME + "." + getLocale() + ".dict"; + } +} diff --git a/java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java b/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryBigramList.java index 316f09603..f21db25a6 100644 --- a/java/src/com/android/inputmethod/latin/UserHistoryDictionaryBigramList.java +++ b/java/src/com/android/inputmethod/latin/personalization/UserHistoryDictionaryBigramList.java @@ -14,11 +14,12 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.personalization; import android.util.Log; import com.android.inputmethod.annotations.UsedForTesting; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.util.HashMap; import java.util.Set; @@ -52,7 +53,7 @@ public final class UserHistoryDictionaryBigramList { * Called when loaded from the SQL DB. */ public void addBigram(String word1, String word2, byte fcValue) { - if (UserHistoryDictionary.DBG_SAVE_RESTORE) { + if (UserHistoryPredictionDictionary.DBG_SAVE_RESTORE) { Log.d(TAG, "--- add bigram: " + word1 + ", " + word2 + ", " + fcValue); } final HashMap<String, Byte> map; @@ -72,7 +73,7 @@ public final class UserHistoryDictionaryBigramList { * Called when inserted to the SQL DB. */ public void updateBigram(String word1, String word2, byte fcValue) { - if (UserHistoryDictionary.DBG_SAVE_RESTORE) { + if (UserHistoryPredictionDictionary.DBG_SAVE_RESTORE) { Log.d(TAG, "--- update bigram: " + word1 + ", " + word2 + ", " + fcValue); } final HashMap<String, Byte> map; diff --git a/java/src/com/android/inputmethod/latin/personalization/UserHistoryPredictionDictionary.java b/java/src/com/android/inputmethod/latin/personalization/UserHistoryPredictionDictionary.java new file mode 100644 index 000000000..d11784454 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/personalization/UserHistoryPredictionDictionary.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.personalization; + +import com.android.inputmethod.latin.Dictionary; + +import android.content.Context; +import android.content.SharedPreferences; + +/** + * Locally gathers stats about the words user types and various other signals like auto-correction + * cancellation or manual picks. This allows the keyboard to adapt to the typist over time. + */ +public class UserHistoryPredictionDictionary extends DynamicPredictionDictionaryBase { + private static final String NAME = UserHistoryPredictionDictionary.class.getSimpleName(); + /* package */ UserHistoryPredictionDictionary(final Context context, final String locale, + final SharedPreferences sp) { + super(context, locale, sp, Dictionary.TYPE_USER_HISTORY); + } + + @Override + protected String getDictionaryFileName() { + return NAME + "." + getLocale() + ".dict"; + } +} diff --git a/java/src/com/android/inputmethod/latin/settings/AdditionalFeaturesSettingUtils.java b/java/src/com/android/inputmethod/latin/settings/AdditionalFeaturesSettingUtils.java new file mode 100644 index 000000000..139f5e290 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/settings/AdditionalFeaturesSettingUtils.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.settings; + +import android.content.Context; +import android.content.SharedPreferences; + +import com.android.inputmethodcommon.InputMethodSettingsFragment; + +/** + * Utility class for managing additional features settings. + */ +public class AdditionalFeaturesSettingUtils { + public static final int ADDITIONAL_FEATURES_SETTINGS_SIZE = 0; + + private AdditionalFeaturesSettingUtils() { + // This utility class is not publicly instantiable. + } + + public static void addAdditionalFeaturesPreferences( + final Context context, final InputMethodSettingsFragment settingsFragment) { + // do nothing. + } + + public static void readAdditionalFeaturesPreferencesIntoArray( + final SharedPreferences prefs, final int[] additionalFeaturesPreferences) { + // do nothing. + } + + public static int[] getAdditionalNativeSuggestOptions() { + return Settings.getInstance().getCurrent().mAdditionalFeaturesSettingValues; + } +} diff --git a/java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java b/java/src/com/android/inputmethod/latin/settings/AdditionalSubtypeSettings.java index ff5e33949..4bf524cbb 100644 --- a/java/src/com/android/inputmethod/latin/AdditionalSubtypeSettings.java +++ b/java/src/com/android/inputmethod/latin/settings/AdditionalSubtypeSettings.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.ASCII_CAPABLE; @@ -44,6 +44,13 @@ import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.Toast; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.RichInputMethodManager; +import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.IntentUtils; +import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; + import java.util.ArrayList; import java.util.TreeSet; @@ -71,7 +78,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { public SubtypeLocaleItem(final String localeString) { this(localeString, - SubtypeLocale.getSubtypeLocaleDisplayNameInSystemLocale(localeString)); + SubtypeLocaleUtils.getSubtypeLocaleDisplayNameInSystemLocale(localeString)); } @Override @@ -102,7 +109,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { if (DEBUG_SUBTYPE_ID) { android.util.Log.d(TAG, String.format("%-6s 0x%08x %11d %s", subtype.getLocale(), subtype.hashCode(), subtype.hashCode(), - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype))); + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype))); } if (subtype.containsExtraValueKey(ASCII_CAPABLE)) { items.add(createItem(context, subtype.getLocale())); @@ -114,7 +121,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { public static SubtypeLocaleItem createItem(final Context context, final String localeString) { - if (localeString.equals(SubtypeLocale.NO_LANGUAGE)) { + if (localeString.equals(SubtypeLocaleUtils.NO_LANGUAGE)) { final String displayName = context.getString(R.string.subtype_no_language); return new SubtypeLocaleItem(localeString, displayName); } else { @@ -125,8 +132,8 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { static final class KeyboardLayoutSetItem extends Pair<String, String> { public KeyboardLayoutSetItem(final InputMethodSubtype subtype) { - super(SubtypeLocale.getKeyboardLayoutSetName(subtype), - SubtypeLocale.getKeyboardLayoutSetDisplayName(subtype)); + super(SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype), + SubtypeLocaleUtils.getKeyboardLayoutSetDisplayName(subtype)); } @Override @@ -141,10 +148,10 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // TODO: Should filter out already existing combinations of locale and layout. - for (final String layout : SubtypeLocale.getPredefinedKeyboardLayoutSet()) { + for (final String layout : SubtypeLocaleUtils.getPredefinedKeyboardLayoutSet()) { // This is a dummy subtype with NO_LANGUAGE, only for display. - final InputMethodSubtype subtype = AdditionalSubtype.createAdditionalSubtype( - SubtypeLocale.NO_LANGUAGE, layout, null); + final InputMethodSubtype subtype = AdditionalSubtypeUtils.createAdditionalSubtype( + SubtypeLocaleUtils.NO_LANGUAGE, layout, null); add(new KeyboardLayoutSetItem(subtype)); } } @@ -205,11 +212,11 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { setKey(KEY_NEW_SUBTYPE); } else { final String displayName = - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype); + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype); setTitle(displayName); setDialogTitle(displayName); setKey(KEY_PREFIX + subtype.getLocale() + "_" - + SubtypeLocale.getKeyboardLayoutSetName(subtype)); + + SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype)); } } @@ -279,7 +286,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { (SubtypeLocaleItem) mSubtypeLocaleSpinner.getSelectedItem(); final KeyboardLayoutSetItem layout = (KeyboardLayoutSetItem) mKeyboardLayoutSetSpinner.getSelectedItem(); - final InputMethodSubtype subtype = AdditionalSubtype.createAdditionalSubtype( + final InputMethodSubtype subtype = AdditionalSubtypeUtils.createAdditionalSubtype( locale.first, layout.first, ASCII_CAPABLE); setSubtype(subtype); notifyChanged(); @@ -497,13 +504,13 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { final Context context = getActivity(); final Resources res = context.getResources(); final String message = res.getString(R.string.custom_input_style_already_exists, - SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype)); + SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype)); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } private InputMethodSubtype findDuplicatedSubtype(final InputMethodSubtype subtype) { final String localeString = subtype.getLocale(); - final String keyboardLayoutSetName = SubtypeLocale.getKeyboardLayoutSetName(subtype); + final String keyboardLayoutSetName = SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype); return mRichImm.findSubtypeByLocaleAndKeyboardLayoutSet( localeString, keyboardLayoutSetName); } @@ -536,7 +543,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { final PreferenceGroup group = getPreferenceScreen(); group.removeAll(); final InputMethodSubtype[] subtypesArray = - AdditionalSubtype.createAdditionalSubtypesArray(prefSubtypes); + AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefSubtypes); for (final InputMethodSubtype subtype : subtypesArray) { final SubtypePreference pref = new SubtypePreference( context, subtype, mSubtypeProxy); @@ -565,7 +572,7 @@ public final class AdditionalSubtypeSettings extends PreferenceFragment { super.onPause(); final String oldSubtypes = Settings.readPrefAdditionalSubtypes(mPrefs, getResources()); final InputMethodSubtype[] subtypes = getSubtypes(); - final String prefSubtypes = AdditionalSubtype.createPrefSubtypes(subtypes); + final String prefSubtypes = AdditionalSubtypeUtils.createPrefSubtypes(subtypes); if (prefSubtypes.equals(oldSubtypes)) { return; } diff --git a/java/src/com/android/inputmethod/latin/DebugSettings.java b/java/src/com/android/inputmethod/latin/settings/DebugSettings.java index 5969a63de..b1cd88729 100644 --- a/java/src/com/android/inputmethod/latin/DebugSettings.java +++ b/java/src/com/android/inputmethod/latin/settings/DebugSettings.java @@ -14,31 +14,31 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; -import android.content.Context; import android.content.SharedPreferences; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.os.Process; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; -import android.util.Log; import com.android.inputmethod.keyboard.KeyboardSwitcher; -import com.android.inputmethod.research.ResearchLogger; +import com.android.inputmethod.latin.LatinImeLogger; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.debug.ExternalDictionaryGetterForDebug; +import com.android.inputmethod.latin.utils.ApplicationUtils; public final class DebugSettings extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { - private static final String TAG = DebugSettings.class.getSimpleName(); public static final String PREF_DEBUG_MODE = "debug_mode"; public static final String PREF_FORCE_NON_DISTINCT_MULTITOUCH = "force_non_distinct_multitouch"; public static final String PREF_USABILITY_STUDY_MODE = "usability_study_mode"; public static final String PREF_STATISTICS_LOGGING = "enable_logging"; + public static final String PREF_USE_ONLY_PERSONALIZATION_DICTIONARY_FOR_DEBUG = + "use_only_personalization_dictionary_for_debug"; private static final String PREF_READ_EXTERNAL_DICTIONARY = "read_external_dictionary"; private static final boolean SHOW_STATISTICS_LOGGING = false; @@ -68,7 +68,7 @@ public final class DebugSettings extends PreferenceFragment } } - PreferenceScreen readExternalDictionary = + final PreferenceScreen readExternalDictionary = (PreferenceScreen) findPreference(PREF_READ_EXTERNAL_DICTIONARY); if (null != readExternalDictionary) { readExternalDictionary.setOnPreferenceClickListener( @@ -113,6 +113,8 @@ public final class DebugSettings extends PreferenceFragment } else if (key.equals(PREF_FORCE_NON_DISTINCT_MULTITOUCH) || key.equals(KeyboardSwitcher.PREF_KEYBOARD_LAYOUT)) { mServiceNeedsRestart = true; + } else if (key.equals(PREF_USE_ONLY_PERSONALIZATION_DICTIONARY_FOR_DEBUG)) { + mServiceNeedsRestart = true; } } @@ -122,7 +124,7 @@ public final class DebugSettings extends PreferenceFragment } boolean isDebugMode = mDebugMode.isChecked(); final String version = getResources().getString( - R.string.version_text, Utils.getVersionName(getActivity())); + R.string.version_text, ApplicationUtils.getVersionName(getActivity())); if (!isDebugMode) { mDebugMode.setTitle(version); mDebugMode.setSummary(""); diff --git a/java/src/com/android/inputmethod/latin/DebugSettingsActivity.java b/java/src/com/android/inputmethod/latin/settings/DebugSettingsActivity.java index e1b5a802e..b499c26b6 100644 --- a/java/src/com/android/inputmethod/latin/DebugSettingsActivity.java +++ b/java/src/com/android/inputmethod/latin/settings/DebugSettingsActivity.java @@ -14,12 +14,14 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceActivity; +import com.android.inputmethod.latin.R; + public final class DebugSettingsActivity extends PreferenceActivity { private static final String DEFAULT_FRAGMENT = DebugSettings.class.getName(); diff --git a/java/src/com/android/inputmethod/latin/settings/NativeSuggestOptions.java b/java/src/com/android/inputmethod/latin/settings/NativeSuggestOptions.java new file mode 100644 index 000000000..878c505bd --- /dev/null +++ b/java/src/com/android/inputmethod/latin/settings/NativeSuggestOptions.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.settings; + +public class NativeSuggestOptions { + // Need to update suggest_options.h when you add, remove or reorder options. + private static final int IS_GESTURE = 0; + private static final int USE_FULL_EDIT_DISTANCE = 1; + private static final int OPTIONS_SIZE = 2; + + private final int[] mOptions = new int[OPTIONS_SIZE + + AdditionalFeaturesSettingUtils.ADDITIONAL_FEATURES_SETTINGS_SIZE]; + + public void setIsGesture(final boolean value) { + setBooleanOption(IS_GESTURE, value); + } + + public void setUseFullEditDistance(final boolean value) { + setBooleanOption(USE_FULL_EDIT_DISTANCE, value); + } + + public void setAdditionalFeaturesOptions(final int[] additionalOptions) { + for (int i = 0; i < additionalOptions.length; i++) { + setIntegerOption(OPTIONS_SIZE + i, additionalOptions[i]); + } + } + + public int[] getOptions() { + return mOptions; + } + + private void setBooleanOption(final int key, final boolean value) { + mOptions[key] = value ? 1 : 0; + } + + private void setIntegerOption(final int key, final int value) { + mOptions[key] = value; + } +} diff --git a/java/src/com/android/inputmethod/latin/SeekBarDialogPreference.java b/java/src/com/android/inputmethod/latin/settings/SeekBarDialogPreference.java index 7c4156c48..802574aa8 100644 --- a/java/src/com/android/inputmethod/latin/SeekBarDialogPreference.java +++ b/java/src/com/android/inputmethod/latin/settings/SeekBarDialogPreference.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import android.app.AlertDialog; import android.content.Context; @@ -26,16 +26,19 @@ import android.view.View; import android.widget.SeekBar; import android.widget.TextView; +import com.android.inputmethod.latin.R; + public final class SeekBarDialogPreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener { public interface ValueProxy { public int readValue(final String key); public int readDefaultValue(final String key); public void writeValue(final int value, final String key); + public void writeDefaultValue(final String key); + public String getValueText(final int value); public void feedbackValue(final int value); } - private final int mValueFormatResId; private final int mMaxValue; private final int mMinValue; private final int mStepValue; @@ -49,7 +52,6 @@ public final class SeekBarDialogPreference extends DialogPreference super(context, attrs); final TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.SeekBarDialogPreference, 0, 0); - mValueFormatResId = a.getResourceId(R.styleable.SeekBarDialogPreference_valueFormatText, 0); mMaxValue = a.getInt(R.styleable.SeekBarDialogPreference_maxValue, 0); mMinValue = a.getInt(R.styleable.SeekBarDialogPreference_minValue, 0); mStepValue = a.getInt(R.styleable.SeekBarDialogPreference_stepValue, 0); @@ -59,15 +61,8 @@ public final class SeekBarDialogPreference extends DialogPreference public void setInterface(final ValueProxy proxy) { mValueProxy = proxy; - setSummary(getValueText(clipValue(proxy.readValue(getKey())))); - } - - private String getValueText(final int value) { - if (mValueFormatResId == 0) { - return Integer.toString(value); - } else { - return getContext().getString(mValueFormatResId, value); - } + final int value = mValueProxy.readValue(getKey()); + setSummary(mValueProxy.getValueText(value)); } @Override @@ -100,16 +95,11 @@ public final class SeekBarDialogPreference extends DialogPreference return clipValue(getValueFromProgress(progress)); } - private void setValue(final int value, final boolean fromUser) { - mValueView.setText(getValueText(value)); - if (!fromUser) { - mSeekBar.setProgress(getProgressFromValue(value)); - } - } - @Override protected void onBindDialogView(final View view) { - setValue(clipValue(mValueProxy.readValue(getKey())), false /* fromUser */); + final int value = mValueProxy.readValue(getKey()); + mValueView.setText(mValueProxy.getValueText(value)); + mSeekBar.setProgress(getProgressFromValue(clipValue(value))); } @Override @@ -122,19 +112,29 @@ public final class SeekBarDialogPreference extends DialogPreference @Override public void onClick(final DialogInterface dialog, final int which) { super.onClick(dialog, which); + final String key = getKey(); if (which == DialogInterface.BUTTON_NEUTRAL) { - setValue(clipValue(mValueProxy.readDefaultValue(getKey())), false /* fromUser */); + final int value = mValueProxy.readDefaultValue(key); + setSummary(mValueProxy.getValueText(value)); + mValueProxy.writeDefaultValue(key); + return; } - if (which != DialogInterface.BUTTON_NEGATIVE) { - setSummary(mValueView.getText()); - mValueProxy.writeValue(getClippedValueFromProgress(mSeekBar.getProgress()), getKey()); + if (which == DialogInterface.BUTTON_POSITIVE) { + final int value = getClippedValueFromProgress(mSeekBar.getProgress()); + setSummary(mValueProxy.getValueText(value)); + mValueProxy.writeValue(value, key); + return; } } @Override public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) { - setValue(getClippedValueFromProgress(progress), fromUser); + final int value = getClippedValueFromProgress(progress); + mValueView.setText(mValueProxy.getValueText(value)); + if (!fromUser) { + mSeekBar.setProgress(getProgressFromValue(value)); + } } @Override diff --git a/java/src/com/android/inputmethod/latin/Settings.java b/java/src/com/android/inputmethod/latin/settings/Settings.java index 9fefb58a6..d432087d3 100644 --- a/java/src/com/android/inputmethod/latin/Settings.java +++ b/java/src/com/android/inputmethod/latin/settings/Settings.java @@ -14,20 +14,30 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.res.Resources; import android.preference.PreferenceManager; +import android.util.Log; -import com.android.inputmethod.latin.LocaleUtils.RunInLocale; +import com.android.inputmethod.latin.AudioAndHapticFeedbackManager; +import com.android.inputmethod.latin.InputAttributes; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; +import com.android.inputmethod.latin.utils.DebugLogUtils; +import com.android.inputmethod.latin.utils.LocaleUtils; +import com.android.inputmethod.latin.utils.ResourceUtils; +import com.android.inputmethod.latin.utils.RunInLocale; import java.util.HashMap; import java.util.Locale; +import java.util.concurrent.locks.ReentrantLock; public final class Settings implements SharedPreferences.OnSharedPreferenceChangeListener { + private static final String TAG = Settings.class.getSimpleName(); // In the same order as xml/prefs.xml public static final String PREF_GENERAL_SETTINGS = "general_settings"; public static final String PREF_AUTO_CAP = "auto_cap"; @@ -85,8 +95,8 @@ public final class Settings implements SharedPreferences.OnSharedPreferenceChang private Resources mRes; private SharedPreferences mPrefs; - private Locale mCurrentLocale; private SettingsValues mSettingsValues; + private final ReentrantLock mSettingsValuesLock = new ReentrantLock(); private static final Settings sInstance = new Settings(); @@ -114,19 +124,34 @@ public final class Settings implements SharedPreferences.OnSharedPreferenceChang @Override public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) { - loadSettings(mCurrentLocale, mSettingsValues.mInputAttributes); + mSettingsValuesLock.lock(); + try { + if (mSettingsValues == null) { + // TODO: Introduce a static function to register this class and ensure that + // loadSettings must be called before "onSharedPreferenceChanged" is called. + Log.w(TAG, "onSharedPreferenceChanged called before loadSettings."); + return; + } + loadSettings(mSettingsValues.mLocale, mSettingsValues.mInputAttributes); + } finally { + mSettingsValuesLock.unlock(); + } } public void loadSettings(final Locale locale, final InputAttributes inputAttributes) { - mCurrentLocale = locale; - final SharedPreferences prefs = mPrefs; - final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { - @Override - protected SettingsValues job(final Resources res) { - return new SettingsValues(prefs, res, inputAttributes); - } - }; - mSettingsValues = job.runInLocale(mRes, locale); + mSettingsValuesLock.lock(); + try { + final SharedPreferences prefs = mPrefs; + final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { + @Override + protected SettingsValues job(final Resources res) { + return new SettingsValues(prefs, locale, res, inputAttributes); + } + }; + mSettingsValues = job.runInLocale(mRes, locale); + } finally { + mSettingsValuesLock.unlock(); + } } // TODO: Remove this method and add proxy method to SettingsValues. @@ -142,8 +167,8 @@ public final class Settings implements SharedPreferences.OnSharedPreferenceChang return mSettingsValues.mWordSeparators; } - public Locale getCurrentLocale() { - return mCurrentLocale; + public boolean isWordSeparator(final int code) { + return mSettingsValues.isWordSeparator(code); } public boolean getBlockPotentiallyOffensive() { @@ -223,7 +248,7 @@ public final class Settings implements SharedPreferences.OnSharedPreferenceChang public static String readPrefAdditionalSubtypes(final SharedPreferences prefs, final Resources res) { - final String predefinedPrefSubtypes = AdditionalSubtype.createPrefSubtypes( + final String predefinedPrefSubtypes = AdditionalSubtypeUtils.createPrefSubtypes( res.getStringArray(R.array.predefined_subtypes)); return prefs.getString(PREF_CUSTOM_INPUT_STYLES, predefinedPrefSubtypes); } @@ -312,4 +337,10 @@ public final class Settings implements SharedPreferences.OnSharedPreferenceChang public static boolean isInternal(final SharedPreferences prefs) { return prefs.getBoolean(Settings.PREF_KEY_IS_INTERNAL, false); } + + public static boolean readUseOnlyPersonalizationDictionaryForDebug( + final SharedPreferences prefs) { + return prefs.getBoolean( + DebugSettings.PREF_USE_ONLY_PERSONALIZATION_DICTIONARY_FOR_DEBUG, false); + } } diff --git a/java/src/com/android/inputmethod/latin/SettingsActivity.java b/java/src/com/android/inputmethod/latin/settings/SettingsActivity.java index 37ac2e35c..6c3818651 100644 --- a/java/src/com/android/inputmethod/latin/SettingsActivity.java +++ b/java/src/com/android/inputmethod/latin/settings/SettingsActivity.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import android.content.Intent; import android.preference.PreferenceActivity; diff --git a/java/src/com/android/inputmethod/latin/SettingsFragment.java b/java/src/com/android/inputmethod/latin/settings/SettingsFragment.java index 835ef7b46..446777704 100644 --- a/java/src/com/android/inputmethod/latin/SettingsFragment.java +++ b/java/src/com/android/inputmethod/latin/settings/SettingsFragment.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import android.app.Activity; import android.app.backup.BackupManager; @@ -25,6 +25,7 @@ import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.media.AudioManager; +import android.os.Build; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; @@ -32,20 +33,33 @@ import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; +import android.util.Log; import android.view.inputmethod.InputMethodSubtype; -import java.util.TreeSet; - import com.android.inputmethod.dictionarypack.DictionarySettingsActivity; +import com.android.inputmethod.latin.AudioAndHapticFeedbackManager; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.SubtypeSwitcher; import com.android.inputmethod.latin.define.ProductionFlag; import com.android.inputmethod.latin.setup.LauncherIconVisibilityManager; import com.android.inputmethod.latin.userdictionary.UserDictionaryList; import com.android.inputmethod.latin.userdictionary.UserDictionarySettings; +import com.android.inputmethod.latin.utils.AdditionalSubtypeUtils; +import com.android.inputmethod.latin.utils.ApplicationUtils; +import com.android.inputmethod.latin.utils.FeedbackUtils; +import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; +import com.android.inputmethod.research.ResearchLogger; import com.android.inputmethodcommon.InputMethodSettingsFragment; +import java.util.TreeSet; + public final class SettingsFragment extends InputMethodSettingsFragment implements SharedPreferences.OnSharedPreferenceChangeListener { - private static final boolean DBG_USE_INTERNAL_USER_DICTIONARY_SETTINGS = false; + private static final String TAG = SettingsFragment.class.getSimpleName(); + private static final boolean DBG_USE_INTERNAL_PERSONAL_DICTIONARY_SETTINGS = false; + private static final boolean USE_INTERNAL_PERSONAL_DICTIONARY_SETTIGS = + DBG_USE_INTERNAL_PERSONAL_DICTIONARY_SETTINGS + || Build.VERSION.SDK_INT <= 18 /* Build.VERSION.JELLY_BEAN_MR2 */; private ListPreference mVoicePreference; private ListPreference mShowCorrectionSuggestionsPreference; @@ -80,7 +94,7 @@ public final class SettingsFragment extends InputMethodSettingsFragment final PreferenceScreen preferenceScreen = getPreferenceScreen(); if (preferenceScreen != null) { preferenceScreen.setTitle( - Utils.getAcitivityTitleResId(getActivity(), SettingsActivity.class)); + ApplicationUtils.getAcitivityTitleResId(getActivity(), SettingsActivity.class)); } final Resources res = getResources(); @@ -90,7 +104,7 @@ public final class SettingsFragment extends InputMethodSettingsFragment // singleton and utility classes may not have been initialized. We have to call // initialization method of these classes here. See {@link LatinIME#onCreate()}. SubtypeSwitcher.init(context); - SubtypeLocale.init(context); + SubtypeLocaleUtils.init(context); AudioAndHapticFeedbackManager.init(context); mVoicePreference = (ListPreference) findPreference(Settings.PREF_VOICE_MODE); @@ -128,7 +142,12 @@ public final class SettingsFragment extends InputMethodSettingsFragment feedbackSettings.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference pref) { - FeedbackUtils.showFeedbackForm(getActivity()); + if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { + // Use development-only feedback mechanism + ResearchLogger.getInstance().presentFeedbackDialogFromSettings(); + } else { + FeedbackUtils.showFeedbackForm(getActivity()); + } return true; } }); @@ -139,6 +158,10 @@ public final class SettingsFragment extends InputMethodSettingsFragment miscSettings.removePreference(aboutSettings); } } + if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { + // The about screen contains items that may be confusing in development-only versions. + miscSettings.removePreference(aboutSettings); + } final boolean showVoiceKeyOption = res.getBoolean( R.bool.config_enable_show_voice_key_option); @@ -190,23 +213,24 @@ public final class SettingsFragment extends InputMethodSettingsFragment final Intent intent = dictionaryLink.getIntent(); intent.setClassName(context.getPackageName(), DictionarySettingsActivity.class.getName()); final int number = context.getPackageManager().queryIntentActivities(intent, 0).size(); - // TODO: The development-only-diagnostic version is not supported by the Dictionary Pack - // Service yet - if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS || 0 >= number) { + if (0 >= number) { textCorrectionGroup.removePreference(dictionaryLink); } final Preference editPersonalDictionary = findPreference(Settings.PREF_EDIT_PERSONAL_DICTIONARY); final Intent editPersonalDictionaryIntent = editPersonalDictionary.getIntent(); - final ResolveInfo ri = context.getPackageManager().resolveActivity( - editPersonalDictionaryIntent, PackageManager.MATCH_DEFAULT_ONLY); - if (DBG_USE_INTERNAL_USER_DICTIONARY_SETTINGS || ri == null) { - updateUserDictionaryPreference(editPersonalDictionary); + final ResolveInfo ri = USE_INTERNAL_PERSONAL_DICTIONARY_SETTIGS ? null + : context.getPackageManager().resolveActivity( + editPersonalDictionaryIntent, PackageManager.MATCH_DEFAULT_ONLY); + if (ri == null) { + overwriteUserDictionaryPreference(editPersonalDictionary); } if (!Settings.readFromBuildConfigIfGestureInputEnabled(res)) { removePreference(Settings.PREF_GESTURE_SETTINGS, getPreferenceScreen()); + } else { + AdditionalFeaturesSettingUtils.addAdditionalFeaturesPreferences(context, this); } setupKeyLongpressTimeoutSettings(prefs, res); @@ -244,7 +268,14 @@ public final class SettingsFragment extends InputMethodSettingsFragment @Override public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) { - (new BackupManager(getActivity())).dataChanged(); + final Activity activity = getActivity(); + if (activity == null) { + // TODO: Introduce a static function to register this class and ensure that + // onCreate must be called before "onSharedPreferenceChanged" is called. + Log.w(TAG, "onSharedPreferenceChanged called before activity starts."); + return; + } + (new BackupManager(activity)).dataChanged(); final Resources res = getResources(); if (key.equals(Settings.PREF_POPUP_ON)) { setPreferenceEnabled(Settings.PREF_KEY_PREVIEW_POPUP_DISMISS_DELAY, @@ -283,11 +314,11 @@ public final class SettingsFragment extends InputMethodSettingsFragment final Resources res = getResources(); final String prefSubtype = Settings.readPrefAdditionalSubtypes(prefs, res); final InputMethodSubtype[] subtypes = - AdditionalSubtype.createAdditionalSubtypesArray(prefSubtype); + AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefSubtype); final StringBuilder styles = new StringBuilder(); for (final InputMethodSubtype subtype : subtypes) { if (styles.length() > 0) styles.append(", "); - styles.append(SubtypeLocale.getSubtypeDisplayNameInSystemLocale(subtype)); + styles.append(SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype)); } customInputStyles.setSummary(styles); } @@ -327,6 +358,11 @@ public final class SettingsFragment extends InputMethodSettingsFragment } @Override + public void writeDefaultValue(final String key) { + sp.edit().remove(key).apply(); + } + + @Override public int readValue(final String key) { return Settings.readKeypressVibrationDuration(sp, res); } @@ -340,6 +376,14 @@ public final class SettingsFragment extends InputMethodSettingsFragment public void feedbackValue(final int value) { AudioAndHapticFeedbackManager.getInstance().vibrate(value); } + + @Override + public String getValueText(final int value) { + if (value < 0) { + return res.getString(R.string.settings_system_default); + } + return res.getString(R.string.abbreviation_unit_milliseconds, value); + } }); } @@ -357,6 +401,11 @@ public final class SettingsFragment extends InputMethodSettingsFragment } @Override + public void writeDefaultValue(final String key) { + sp.edit().remove(key).apply(); + } + + @Override public int readValue(final String key) { return Settings.readKeyLongpressTimeout(sp, res); } @@ -367,6 +416,11 @@ public final class SettingsFragment extends InputMethodSettingsFragment } @Override + public String getValueText(final int value) { + return res.getString(R.string.abbreviation_unit_milliseconds, value); + } + + @Override public void feedbackValue(final int value) {} }); } @@ -395,6 +449,11 @@ public final class SettingsFragment extends InputMethodSettingsFragment } @Override + public void writeDefaultValue(final String key) { + sp.edit().remove(key).apply(); + } + + @Override public int readValue(final String key) { return getPercentageFromValue(Settings.readKeypressSoundVolume(sp, res)); } @@ -405,6 +464,14 @@ public final class SettingsFragment extends InputMethodSettingsFragment } @Override + public String getValueText(final int value) { + if (value < 0) { + return res.getString(R.string.settings_system_default); + } + return Integer.toString(value); + } + + @Override public void feedbackValue(final int value) { am.playSoundEffect( AudioManager.FX_KEYPRESS_STANDARD, getValueFromPercentage(value)); @@ -412,7 +479,7 @@ public final class SettingsFragment extends InputMethodSettingsFragment }); } - private void updateUserDictionaryPreference(Preference userDictionaryPreference) { + private void overwriteUserDictionaryPreference(Preference userDictionaryPreference) { final Activity activity = getActivity(); final TreeSet<String> localeList = UserDictionaryList.getUserDictionaryLocalesSet(activity); if (null == localeList) { diff --git a/java/src/com/android/inputmethod/latin/SettingsValues.java b/java/src/com/android/inputmethod/latin/settings/SettingsValues.java index 615b2dfab..8aafb0738 100644 --- a/java/src/com/android/inputmethod/latin/SettingsValues.java +++ b/java/src/com/android/inputmethod/latin/settings/SettingsValues.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.settings; import android.content.SharedPreferences; import android.content.res.Configuration; @@ -23,14 +23,24 @@ import android.util.Log; import android.view.inputmethod.EditorInfo; import com.android.inputmethod.keyboard.internal.KeySpecParser; +import com.android.inputmethod.latin.Dictionary; +import com.android.inputmethod.latin.InputAttributes; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.RichInputMethodManager; +import com.android.inputmethod.latin.SubtypeSwitcher; +import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.InputTypeUtils; +import com.android.inputmethod.latin.utils.StringUtils; import java.util.ArrayList; import java.util.Arrays; +import java.util.Locale; /** * When you call the constructor of this class, you may want to change the current system locale by - * using {@link LocaleUtils.RunInLocale}. + * using {@link com.android.inputmethod.latin.utils.RunInLocale}. */ public final class SettingsValues { private static final String TAG = SettingsValues.class.getSimpleName(); @@ -65,6 +75,7 @@ public final class SettingsValues { public final boolean mGestureFloatingPreviewTextEnabled; public final boolean mSlidingKeyInputPreviewEnabled; public final int mKeyLongpressTimeout; + public final Locale mLocale; // From the input box public final InputAttributes mInputAttributes; @@ -80,11 +91,16 @@ public final class SettingsValues { private final boolean mVoiceKeyEnabled; private final boolean mVoiceKeyOnMain; + // Setting values for additional features + public final int[] mAdditionalFeaturesSettingValues = + new int[AdditionalFeaturesSettingUtils.ADDITIONAL_FEATURES_SETTINGS_SIZE]; + // Debug settings public final boolean mIsInternal; - public SettingsValues(final SharedPreferences prefs, final Resources res, + public SettingsValues(final SharedPreferences prefs, final Locale locale, final Resources res, final InputAttributes inputAttributes) { + mLocale = locale; // Get the resources mDelayUpdateOldSuggestions = res.getInteger(R.integer.config_delay_update_old_suggestions); mSymbolsPrecededBySpace = @@ -96,7 +112,7 @@ public final class SettingsValues { mWordConnectors = StringUtils.toCodePointArray(res.getString(R.string.symbols_word_connectors)); Arrays.sort(mWordConnectors); - final String[] suggestPuncsSpec = StringUtils.parseCsvString(res.getString( + final String[] suggestPuncsSpec = KeySpecParser.splitKeySpecs(res.getString( R.string.suggested_punctuations)); mSuggestPuncList = createSuggestPuncList(suggestPuncsSpec); mWordSeparators = res.getString(R.string.symbols_word_separators); @@ -149,6 +165,8 @@ public final class SettingsValues { Settings.PREF_SHOW_SUGGESTIONS_SETTING, res.getString(R.string.prefs_suggestion_visibility_default_value)); mSuggestionVisibility = createSuggestionVisibility(res, showSuggestionsSetting); + AdditionalFeaturesSettingUtils.readAdditionalFeaturesPreferencesIntoArray( + prefs, mAdditionalFeaturesSettingValues); mIsInternal = Settings.isInternal(prefs); } diff --git a/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java b/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java index 6a7cd9b6f..050d8d26f 100644 --- a/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java +++ b/java/src/com/android/inputmethod/latin/setup/LauncherIconVisibilityManager.java @@ -25,10 +25,10 @@ import android.content.pm.PackageManager; import android.os.Process; import android.preference.PreferenceManager; import android.util.Log; +import android.view.inputmethod.InputMethodManager; import com.android.inputmethod.compat.IntentCompatUtils; -import com.android.inputmethod.latin.RichInputMethodManager; -import com.android.inputmethod.latin.Settings; +import com.android.inputmethod.latin.settings.Settings; /** * This class detects the {@link Intent#ACTION_MY_PACKAGE_REPLACED} broadcast intent when this IME @@ -65,17 +65,16 @@ public final class LauncherIconVisibilityManager extends BroadcastReceiver { } // The process that hosts this broadcast receiver is invoked and remains alive even after - // 1) the package has been re-installed, 2) the device has been booted, - // 3) a multiuser has been created. + // 1) the package has been re-installed, 2) the device has just booted, + // 3) a new user has been created. // There is no good reason to keep the process alive if this IME isn't a current IME. - final boolean isCurrentImeOfCurrentUser; - if (RichInputMethodManager.isInputMethodManagerValidForUserOfThisProcess(context)) { - RichInputMethodManager.init(context); - isCurrentImeOfCurrentUser = SetupActivity.isThisImeCurrent(context); - } else { - isCurrentImeOfCurrentUser = false; - } - + final InputMethodManager imm = + (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); + // Called to check whether this IME has been triggered by the current user or not + final boolean isInputMethodManagerValidForUserOfThisProcess = + !imm.getInputMethodList().isEmpty(); + final boolean isCurrentImeOfCurrentUser = isInputMethodManagerValidForUserOfThisProcess + && SetupActivity.isThisImeCurrent(context, imm); if (!isCurrentImeOfCurrentUser) { final int myPid = Process.myPid(); Log.i(TAG, "Killing my process: pid=" + myPid); @@ -91,7 +90,7 @@ public final class LauncherIconVisibilityManager extends BroadcastReceiver { } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { Log.i(TAG, "Boot has been completed"); return true; - } else if (IntentCompatUtils.has_ACTION_USER_INITIALIZE(intent)) { + } else if (IntentCompatUtils.is_ACTION_USER_INITIALIZE(action)) { Log.i(TAG, "User initialize"); return true; } diff --git a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java index 8a2de887d..a68f98fe7 100644 --- a/java/src/com/android/inputmethod/latin/setup/SetupActivity.java +++ b/java/src/com/android/inputmethod/latin/setup/SetupActivity.java @@ -24,8 +24,6 @@ import android.provider.Settings; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; -import com.android.inputmethod.latin.RichInputMethodManager; - public final class SetupActivity extends Activity { @Override protected void onCreate(final Bundle savedInstanceState) { @@ -40,17 +38,24 @@ public final class SetupActivity extends Activity { } } + /* + * We may not be able to get our own {@link InputMethodInfo} just after this IME is installed + * because {@link InputMethodManagerService} may not be aware of this IME yet. + * Note: {@link RichInputMethodManager} has similar methods. Here in setup wizard, we can't + * use it for the reason above. + */ + /** * Check if the IME specified by the context is enabled. - * Note that {@link RichInputMethodManager} must have been initialized before calling this - * method. + * CAVEAT: This may cause a round trip IPC. * * @param context package context of the IME to be checked. + * @param imm the {@link InputMethodManager}. * @return true if this IME is enabled. */ - public static boolean isThisImeEnabled(final Context context) { + /* package */ static boolean isThisImeEnabled(final Context context, + final InputMethodManager imm) { final String packageName = context.getPackageName(); - final InputMethodManager imm = RichInputMethodManager.getInstance().getInputMethodManager(); for (final InputMethodInfo imi : imm.getEnabledInputMethodList()) { if (packageName.equals(imi.getPackageName())) { return true; @@ -61,17 +66,36 @@ public final class SetupActivity extends Activity { /** * Check if the IME specified by the context is the current IME. - * Note that {@link RichInputMethodManager} must have been initialized before calling this - * method. + * CAVEAT: This may cause a round trip IPC. * * @param context package context of the IME to be checked. + * @param imm the {@link InputMethodManager}. * @return true if this IME is the current IME. */ - public static boolean isThisImeCurrent(final Context context) { - final InputMethodInfo myImi = - RichInputMethodManager.getInstance().getInputMethodInfoOfThisIme(); + /* package */ static boolean isThisImeCurrent(final Context context, + final InputMethodManager imm) { + final InputMethodInfo imi = getInputMethodInfoOf(context.getPackageName(), imm); final String currentImeId = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD); - return myImi.getId().equals(currentImeId); + return imi != null && imi.getId().equals(currentImeId); + } + + /** + * Get {@link InputMethodInfo} of the IME specified by the package name. + * CAVEAT: This may cause a round trip IPC. + * + * @param packageName package name of the IME. + * @param imm the {@link InputMethodManager}. + * @return the {@link InputMethodInfo} of the IME specified by the <code>packageName</code>, + * or null if not found. + */ + /* package */ static InputMethodInfo getInputMethodInfoOf(final String packageName, + final InputMethodManager imm) { + for (final InputMethodInfo imi : imm.getInputMethodList()) { + if (packageName.equals(imi.getPackageName())) { + return imi; + } + } + return null; } } diff --git a/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java b/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java index 78a6478c6..c4a813c24 100644 --- a/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java +++ b/java/src/com/android/inputmethod/latin/setup/SetupWizardActivity.java @@ -28,17 +28,17 @@ import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodInfo; +import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.VideoView; import com.android.inputmethod.compat.TextViewCompatUtils; import com.android.inputmethod.compat.ViewCompatUtils; -import com.android.inputmethod.latin.CollectionUtils; import com.android.inputmethod.latin.R; -import com.android.inputmethod.latin.RichInputMethodManager; -import com.android.inputmethod.latin.SettingsActivity; -import com.android.inputmethod.latin.StaticInnerHandlerWrapper; +import com.android.inputmethod.latin.settings.SettingsActivity; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.StaticInnerHandlerWrapper; import java.util.ArrayList; @@ -48,6 +48,8 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL private static final boolean ENABLE_WELCOME_VIDEO = true; + private InputMethodManager mImm; + private View mSetupWizard; private View mWelcomeScreen; private View mSetupScreen; @@ -69,15 +71,19 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL private static final int STEP_LAUNCHING_IME_SETTINGS = 4; private static final int STEP_BACK_FROM_IME_SETTINGS = 5; - final SettingsPoolingHandler mHandler = new SettingsPoolingHandler(this); + private SettingsPoolingHandler mHandler; - static final class SettingsPoolingHandler + private static final class SettingsPoolingHandler extends StaticInnerHandlerWrapper<SetupWizardActivity> { private static final int MSG_POLLING_IME_SETTINGS = 0; private static final long IME_SETTINGS_POLLING_INTERVAL = 200; - public SettingsPoolingHandler(final SetupWizardActivity outerInstance) { + private final InputMethodManager mImmInHandler; + + public SettingsPoolingHandler(final SetupWizardActivity outerInstance, + final InputMethodManager imm) { super(outerInstance); + mImmInHandler = imm; } @Override @@ -88,7 +94,7 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL } switch (msg.what) { case MSG_POLLING_IME_SETTINGS: - if (SetupActivity.isThisImeEnabled(setupWizardActivity)) { + if (SetupActivity.isThisImeEnabled(setupWizardActivity, mImmInHandler)) { setupWizardActivity.invokeSetupWizardOfThisIme(); return; } @@ -112,11 +118,12 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL setTheme(android.R.style.Theme_Translucent_NoTitleBar); super.onCreate(savedInstanceState); + mImm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); + mHandler = new SettingsPoolingHandler(this, mImm); + setContentView(R.layout.setup_wizard); mSetupWizard = findViewById(R.id.setup_wizard); - RichInputMethodManager.init(this); - if (savedInstanceState == null) { mStepNumber = determineSetupStepNumberFromLauncher(); } else { @@ -143,11 +150,12 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL R.string.setup_step1_title, R.string.setup_step1_instruction, R.string.setup_step1_finished_instruction, R.drawable.ic_setup_step1, R.string.setup_step1_action); + final SettingsPoolingHandler handler = mHandler; step1.setAction(new Runnable() { @Override public void run() { invokeLanguageAndInputSettings(); - mHandler.startPollingImeSettings(); + handler.startPollingImeSettings(); } }); mSetupStepGroup.addStep(step1); @@ -265,14 +273,15 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL void invokeInputMethodPicker() { // Invoke input method picker. - RichInputMethodManager.getInstance().getInputMethodManager() - .showInputMethodPicker(); + mImm.showInputMethodPicker(); mNeedsToAdjustStepNumberToSystemState = true; } void invokeSubtypeEnablerOfThisIme() { - final InputMethodInfo imi = - RichInputMethodManager.getInstance().getInputMethodInfoOfThisIme(); + final InputMethodInfo imi = SetupActivity.getInputMethodInfoOf(getPackageName(), mImm); + if (imi == null) { + return; + } final Intent intent = new Intent(); intent.setAction(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); @@ -293,10 +302,10 @@ public final class SetupWizardActivity extends Activity implements View.OnClickL private int determineSetupStepNumber() { mHandler.cancelPollingImeSettings(); - if (!SetupActivity.isThisImeEnabled(this)) { + if (!SetupActivity.isThisImeEnabled(this, mImm)) { return STEP_1; } - if (!SetupActivity.isThisImeCurrent(this)) { + if (!SetupActivity.isThisImeCurrent(this, mImm)) { return STEP_2; } return STEP_3; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java index 13fcaf48a..692e7392c 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerService.java @@ -25,17 +25,17 @@ import android.view.textservice.SuggestionsInfo; import com.android.inputmethod.keyboard.KeyboardLayoutSet; import com.android.inputmethod.latin.BinaryDictionary; -import com.android.inputmethod.latin.CollectionUtils; import com.android.inputmethod.latin.ContactsBinaryDictionary; import com.android.inputmethod.latin.Dictionary; import com.android.inputmethod.latin.DictionaryCollection; import com.android.inputmethod.latin.DictionaryFactory; -import com.android.inputmethod.latin.LocaleUtils; import com.android.inputmethod.latin.R; -import com.android.inputmethod.latin.StringUtils; import com.android.inputmethod.latin.SynchronouslyLoadedContactsBinaryDictionary; import com.android.inputmethod.latin.SynchronouslyLoadedUserBinaryDictionary; import com.android.inputmethod.latin.UserBinaryDictionary; +import com.android.inputmethod.latin.utils.CollectionUtils; +import com.android.inputmethod.latin.utils.LocaleUtils; +import com.android.inputmethod.latin.utils.StringUtils; import java.lang.ref.WeakReference; import java.util.ArrayList; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java index 9a1114f7f..ddda52d71 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidSpellCheckerSession.java @@ -23,7 +23,7 @@ import android.view.textservice.SentenceSuggestionsInfo; import android.view.textservice.SuggestionsInfo; import android.view.textservice.TextInfo; -import com.android.inputmethod.latin.CollectionUtils; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.util.ArrayList; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java index 16e9fb77e..6719e98da 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/AndroidWordLevelSpellCheckerSession.java @@ -30,11 +30,11 @@ import android.view.textservice.TextInfo; import com.android.inputmethod.compat.SuggestionsInfoCompatUtils; import com.android.inputmethod.latin.Constants; import com.android.inputmethod.latin.Dictionary; -import com.android.inputmethod.latin.LocaleUtils; -import com.android.inputmethod.latin.StringUtils; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.WordComposer; import com.android.inputmethod.latin.spellcheck.AndroidSpellCheckerService.SuggestionsGatherer; +import com.android.inputmethod.latin.utils.LocaleUtils; +import com.android.inputmethod.latin.utils.StringUtils; import java.util.ArrayList; import java.util.Locale; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java b/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java index a20e09ee8..ac8f68781 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/DictionaryPool.java @@ -19,10 +19,10 @@ package com.android.inputmethod.latin.spellcheck; import android.util.Log; import com.android.inputmethod.keyboard.ProximityInfo; -import com.android.inputmethod.latin.CollectionUtils; import com.android.inputmethod.latin.Dictionary; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import com.android.inputmethod.latin.WordComposer; +import com.android.inputmethod.latin.utils.CollectionUtils; import java.util.ArrayList; import java.util.Locale; diff --git a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java index 5ce9d8e47..999ca775b 100644 --- a/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java +++ b/java/src/com/android/inputmethod/latin/spellcheck/SpellCheckerSettingsFragment.java @@ -21,7 +21,7 @@ import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import com.android.inputmethod.latin.R; -import com.android.inputmethod.latin.Utils; +import com.android.inputmethod.latin.utils.ApplicationUtils; /** * Preference screen. @@ -39,7 +39,7 @@ public final class SpellCheckerSettingsFragment extends PreferenceFragment { addPreferencesFromResource(R.xml.spell_checker_settings); final PreferenceScreen preferenceScreen = getPreferenceScreen(); if (preferenceScreen != null) { - preferenceScreen.setTitle(Utils.getAcitivityTitleResId( + preferenceScreen.setTitle(ApplicationUtils.getAcitivityTitleResId( getActivity(), SpellCheckerSettingsActivity.class)); } } diff --git a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java index 09f81d4c7..e97069dff 100644 --- a/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java +++ b/java/src/com/android/inputmethod/latin/suggestions/MoreSuggestions.java @@ -24,14 +24,13 @@ import android.graphics.drawable.Drawable; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.KeyboardActionListener; -import com.android.inputmethod.keyboard.TypefaceUtils; import com.android.inputmethod.keyboard.internal.KeyboardBuilder; import com.android.inputmethod.keyboard.internal.KeyboardIconsSet; import com.android.inputmethod.keyboard.internal.KeyboardParams; import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.Utils; +import com.android.inputmethod.latin.utils.TypefaceUtils; public final class MoreSuggestions extends Keyboard { public static final int SUGGESTION_CODE_BASE = 1024; @@ -61,7 +60,7 @@ public final class MoreSuggestions extends Keyboard { super(); } - public int layout(final SuggestedWords suggestedWords, final int fromPos, + public int layout(final SuggestedWords suggestedWords, final int fromIndex, final int maxWidth, final int minWidth, final int maxRow, final Paint paint, final Resources res) { clearKeys(); @@ -70,53 +69,54 @@ public final class MoreSuggestions extends Keyboard { final float padding = res.getDimension(R.dimen.more_suggestions_key_horizontal_padding); int row = 0; - int pos = fromPos, rowStartPos = fromPos; + int index = fromIndex; + int rowStartIndex = fromIndex; final int size = Math.min(suggestedWords.size(), SuggestionStripView.MAX_SUGGESTIONS); - while (pos < size) { - final String word = suggestedWords.getWord(pos); + while (index < size) { + final String word = suggestedWords.getWord(index); // TODO: Should take care of text x-scaling. - mWidths[pos] = (int)(TypefaceUtils.getLabelWidth(word, paint) + padding); - final int numColumn = pos - rowStartPos + 1; + mWidths[index] = (int)(TypefaceUtils.getLabelWidth(word, paint) + padding); + final int numColumn = index - rowStartIndex + 1; final int columnWidth = (maxWidth - mDividerWidth * (numColumn - 1)) / numColumn; if (numColumn > MAX_COLUMNS_IN_ROW - || !fitInWidth(rowStartPos, pos + 1, columnWidth)) { + || !fitInWidth(rowStartIndex, index + 1, columnWidth)) { if ((row + 1) >= maxRow) { break; } - mNumColumnsInRow[row] = pos - rowStartPos; - rowStartPos = pos; + mNumColumnsInRow[row] = index - rowStartIndex; + rowStartIndex = index; row++; } - mColumnOrders[pos] = pos - rowStartPos; - mRowNumbers[pos] = row; - pos++; + mColumnOrders[index] = index - rowStartIndex; + mRowNumbers[index] = row; + index++; } - mNumColumnsInRow[row] = pos - rowStartPos; + mNumColumnsInRow[row] = index - rowStartIndex; mNumRows = row + 1; mBaseWidth = mOccupiedWidth = Math.max( - minWidth, calcurateMaxRowWidth(fromPos, pos)); + minWidth, calcurateMaxRowWidth(fromIndex, index)); mBaseHeight = mOccupiedHeight = mNumRows * mDefaultRowHeight + mVerticalGap; - return pos - fromPos; + return index - fromIndex; } - private boolean fitInWidth(final int startPos, final int endPos, final int width) { - for (int pos = startPos; pos < endPos; pos++) { - if (mWidths[pos] > width) + private boolean fitInWidth(final int startIndex, final int endIndex, final int width) { + for (int index = startIndex; index < endIndex; index++) { + if (mWidths[index] > width) return false; } return true; } - private int calcurateMaxRowWidth(final int startPos, final int endPos) { + private int calcurateMaxRowWidth(final int startIndex, final int endIndex) { int maxRowWidth = 0; - int pos = startPos; + int index = startIndex; for (int row = 0; row < mNumRows; row++) { final int numColumnInRow = mNumColumnsInRow[row]; int maxKeyWidth = 0; - while (pos < endPos && mRowNumbers[pos] == row) { - maxKeyWidth = Math.max(maxKeyWidth, mWidths[pos]); - pos++; + while (index < endIndex && mRowNumbers[index] == row) { + maxKeyWidth = Math.max(maxKeyWidth, mWidths[index]); + index++; } maxRowWidth = Math.max(maxRowWidth, maxKeyWidth * numColumnInRow + mDividerWidth * (numColumnInRow - 1)); @@ -130,40 +130,40 @@ public final class MoreSuggestions extends Keyboard { { 2, 0, 1}, }; - public int getNumColumnInRow(final int pos) { - return mNumColumnsInRow[mRowNumbers[pos]]; + public int getNumColumnInRow(final int index) { + return mNumColumnsInRow[mRowNumbers[index]]; } - public int getColumnNumber(final int pos) { - final int columnOrder = mColumnOrders[pos]; - final int numColumn = getNumColumnInRow(pos); + public int getColumnNumber(final int index) { + final int columnOrder = mColumnOrders[index]; + final int numColumn = getNumColumnInRow(index); return COLUMN_ORDER_TO_NUMBER[numColumn - 1][columnOrder]; } - public int getX(final int pos) { - final int columnNumber = getColumnNumber(pos); - return columnNumber * (getWidth(pos) + mDividerWidth); + public int getX(final int index) { + final int columnNumber = getColumnNumber(index); + return columnNumber * (getWidth(index) + mDividerWidth); } - public int getY(final int pos) { - final int row = mRowNumbers[pos]; + public int getY(final int index) { + final int row = mRowNumbers[index]; return (mNumRows -1 - row) * mDefaultRowHeight + mTopPadding; } - public int getWidth(final int pos) { - final int numColumnInRow = getNumColumnInRow(pos); + public int getWidth(final int index) { + final int numColumnInRow = getNumColumnInRow(index); return (mOccupiedWidth - mDividerWidth * (numColumnInRow - 1)) / numColumnInRow; } - public void markAsEdgeKey(final Key key, final int pos) { - final int row = mRowNumbers[pos]; + public void markAsEdgeKey(final Key key, final int index) { + final int row = mRowNumbers[index]; if (row == 0) key.markAsBottomEdge(this); if (row == mNumRows - 1) key.markAsTopEdge(this); final int numColumnInRow = mNumColumnsInRow[row]; - final int column = getColumnNumber(pos); + final int column = getColumnNumber(index); if (column == 0) key.markAsLeftEdge(this); if (column == numColumnInRow - 1) @@ -174,15 +174,15 @@ public final class MoreSuggestions extends Keyboard { public static final class Builder extends KeyboardBuilder<MoreSuggestionsParam> { private final MoreSuggestionsView mPaneView; private SuggestedWords mSuggestedWords; - private int mFromPos; - private int mToPos; + private int mFromIndex; + private int mToIndex; public Builder(final Context context, final MoreSuggestionsView paneView) { super(context, new MoreSuggestionsParam()); mPaneView = paneView; } - public Builder layout(final SuggestedWords suggestedWords, final int fromPos, + public Builder layout(final SuggestedWords suggestedWords, final int fromIndex, final int maxWidth, final int minWidth, final int maxRow, final Keyboard parentKeyboard) { final int xmlId = R.xml.kbd_suggestions_pane_template; @@ -190,10 +190,10 @@ public final class MoreSuggestions extends Keyboard { mParams.mVerticalGap = mParams.mTopPadding = parentKeyboard.mVerticalGap / 2; mPaneView.updateKeyboardGeometry(mParams.mDefaultRowHeight); - final int count = mParams.layout(suggestedWords, fromPos, maxWidth, minWidth, maxRow, + final int count = mParams.layout(suggestedWords, fromIndex, maxWidth, minWidth, maxRow, mPaneView.newLabelPaint(null /* key */), mResources); - mFromPos = fromPos; - mToPos = fromPos + count; + mFromIndex = fromIndex; + mToIndex = fromIndex + count; mSuggestedWords = suggestedWords; return this; } @@ -201,20 +201,20 @@ public final class MoreSuggestions extends Keyboard { @Override public MoreSuggestions build() { final MoreSuggestionsParam params = mParams; - for (int pos = mFromPos; pos < mToPos; pos++) { - final int x = params.getX(pos); - final int y = params.getY(pos); - final int width = params.getWidth(pos); - final String word = mSuggestedWords.getWord(pos); - final String info = Utils.getDebugInfo(mSuggestedWords, pos); - final int index = pos + SUGGESTION_CODE_BASE; + for (int index = mFromIndex; index < mToIndex; index++) { + final int x = params.getX(index); + final int y = params.getY(index); + final int width = params.getWidth(index); + final String word = mSuggestedWords.getWord(index); + final String info = mSuggestedWords.getDebugString(index); + final int indexInMoreSuggestions = index + SUGGESTION_CODE_BASE; final Key key = new Key( - params, word, info, KeyboardIconsSet.ICON_UNDEFINED, index, null, x, y, - width, params.mDefaultRowHeight, 0); - params.markAsEdgeKey(key, pos); + params, word, info, KeyboardIconsSet.ICON_UNDEFINED, indexInMoreSuggestions, + null, x, y, width, params.mDefaultRowHeight, 0); + params.markAsEdgeKey(key, index); params.onAddKey(key); - final int columnNumber = params.getColumnNumber(pos); - final int numColumnInRow = params.getNumColumnInRow(pos); + final int columnNumber = params.getColumnNumber(index); + final int numColumnInRow = params.getNumColumnInRow(index); if (columnNumber < numColumnInRow - 1) { final Divider divider = new Divider(params, params.mDivider, x + width, y, params.mDividerWidth, params.mDefaultRowHeight); diff --git a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java new file mode 100644 index 000000000..1dd04fc4d --- /dev/null +++ b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripLayoutHelper.java @@ -0,0 +1,600 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.suggestions; + +import android.content.Context; +import android.content.res.Resources; +import android.content.res.TypedArray; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.Paint.Align; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.Spanned; +import android.text.TextPaint; +import android.text.TextUtils; +import android.text.style.CharacterStyle; +import android.text.style.StyleSpan; +import android.text.style.UnderlineSpan; +import android.util.AttributeSet; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.android.inputmethod.latin.LatinImeLogger; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.SuggestedWords; +import com.android.inputmethod.latin.utils.AutoCorrectionUtils; +import com.android.inputmethod.latin.utils.ResourceUtils; +import com.android.inputmethod.latin.utils.ViewLayoutUtils; + +import java.util.ArrayList; + +final class SuggestionStripLayoutHelper { + private static final int DEFAULT_SUGGESTIONS_COUNT_IN_STRIP = 3; + private static final float DEFAULT_CENTER_SUGGESTION_PERCENTILE = 0.40f; + private static final int DEFAULT_MAX_MORE_SUGGESTIONS_ROW = 2; + private static final int PUNCTUATIONS_IN_STRIP = 5; + private static final float MIN_TEXT_XSCALE = 0.70f; + + public final int mPadding; + public final int mDividerWidth; + public final int mSuggestionsStripHeight; + public final int mSuggestionsCountInStrip; + public final int mMoreSuggestionsRowHeight; + private int mMaxMoreSuggestionsRow; + public final float mMinMoreSuggestionsWidth; + public final int mMoreSuggestionsBottomGap; + public boolean mMoreSuggestionsAvailable; + + // The index of these {@link ArrayList} is the position in the suggestion strip. The indices + // increase towards the right for LTR scripts and the left for RTL scripts, starting with 0. + // The position of the most important suggestion is in {@link #mCenterPositionInStrip} + private final ArrayList<TextView> mWordViews; + private final ArrayList<View> mDividerViews; + private final ArrayList<TextView> mDebugInfoViews; + + private final int mColorValidTypedWord; + private final int mColorTypedWord; + private final int mColorAutoCorrect; + private final int mColorSuggested; + private final float mAlphaObsoleted; + private final float mCenterSuggestionWeight; + private final int mCenterPositionInStrip; + private final int mTypedWordPositionWhenAutocorrect; + private final Drawable mMoreSuggestionsHint; + private static final String MORE_SUGGESTIONS_HINT = "\u2026"; + private static final String LEFTWARDS_ARROW = "\u2190"; + + private static final CharacterStyle BOLD_SPAN = new StyleSpan(Typeface.BOLD); + private static final CharacterStyle UNDERLINE_SPAN = new UnderlineSpan(); + + private final int mSuggestionStripOption; + // These constants are the flag values of + // {@link R.styleable#SuggestionStripView_suggestionStripOption} attribute. + private static final int AUTO_CORRECT_BOLD = 0x01; + private static final int AUTO_CORRECT_UNDERLINE = 0x02; + private static final int VALID_TYPED_WORD_BOLD = 0x04; + + private final TextView mWordToSaveView; + private final TextView mLeftwardsArrowView; + private final TextView mHintToSaveView; + + public SuggestionStripLayoutHelper(final Context context, final AttributeSet attrs, + final int defStyle, final ArrayList<TextView> wordViews, + final ArrayList<View> dividerViews, final ArrayList<TextView> debugInfoViews) { + mWordViews = wordViews; + mDividerViews = dividerViews; + mDebugInfoViews = debugInfoViews; + + final TextView wordView = wordViews.get(0); + final View dividerView = dividerViews.get(0); + mPadding = wordView.getCompoundPaddingLeft() + wordView.getCompoundPaddingRight(); + dividerView.measure( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + mDividerWidth = dividerView.getMeasuredWidth(); + + final Resources res = wordView.getResources(); + mSuggestionsStripHeight = res.getDimensionPixelSize(R.dimen.suggestions_strip_height); + + final TypedArray a = context.obtainStyledAttributes(attrs, + R.styleable.SuggestionStripView, defStyle, R.style.SuggestionStripViewStyle); + mSuggestionStripOption = a.getInt( + R.styleable.SuggestionStripView_suggestionStripOption, 0); + final float alphaValidTypedWord = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_alphaValidTypedWord, 1.0f); + final float alphaTypedWord = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_alphaTypedWord, 1.0f); + final float alphaAutoCorrect = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_alphaAutoCorrect, 1.0f); + final float alphaSuggested = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_alphaSuggested, 1.0f); + mAlphaObsoleted = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_alphaSuggested, 1.0f); + mColorValidTypedWord = applyAlpha(a.getColor( + R.styleable.SuggestionStripView_colorValidTypedWord, 0), alphaValidTypedWord); + mColorTypedWord = applyAlpha(a.getColor( + R.styleable.SuggestionStripView_colorTypedWord, 0), alphaTypedWord); + mColorAutoCorrect = applyAlpha(a.getColor( + R.styleable.SuggestionStripView_colorAutoCorrect, 0), alphaAutoCorrect); + mColorSuggested = applyAlpha(a.getColor( + R.styleable.SuggestionStripView_colorSuggested, 0), alphaSuggested); + mSuggestionsCountInStrip = a.getInt( + R.styleable.SuggestionStripView_suggestionsCountInStrip, + DEFAULT_SUGGESTIONS_COUNT_IN_STRIP); + mCenterSuggestionWeight = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_centerSuggestionPercentile, + DEFAULT_CENTER_SUGGESTION_PERCENTILE); + mMaxMoreSuggestionsRow = a.getInt( + R.styleable.SuggestionStripView_maxMoreSuggestionsRow, + DEFAULT_MAX_MORE_SUGGESTIONS_ROW); + mMinMoreSuggestionsWidth = ResourceUtils.getFraction(a, + R.styleable.SuggestionStripView_minMoreSuggestionsWidth, 1.0f); + a.recycle(); + + mMoreSuggestionsHint = getMoreSuggestionsHint(res, + res.getDimension(R.dimen.more_suggestions_hint_text_size), mColorAutoCorrect); + mCenterPositionInStrip = mSuggestionsCountInStrip / 2; + // Assuming there are at least three suggestions. Also, note that the suggestions are + // laid out according to script direction, so this is left of the center for LTR scripts + // and right of the center for RTL scripts. + mTypedWordPositionWhenAutocorrect = mCenterPositionInStrip - 1; + mMoreSuggestionsBottomGap = res.getDimensionPixelOffset( + R.dimen.more_suggestions_bottom_gap); + mMoreSuggestionsRowHeight = res.getDimensionPixelSize(R.dimen.more_suggestions_row_height); + + final LayoutInflater inflater = LayoutInflater.from(context); + mWordToSaveView = (TextView)inflater.inflate(R.layout.suggestion_word, null); + mLeftwardsArrowView = (TextView)inflater.inflate(R.layout.hint_add_to_dictionary, null); + mHintToSaveView = (TextView)inflater.inflate(R.layout.hint_add_to_dictionary, null); + } + + public int getMaxMoreSuggestionsRow() { + return mMaxMoreSuggestionsRow; + } + + private int getMoreSuggestionsHeight() { + return mMaxMoreSuggestionsRow * mMoreSuggestionsRowHeight + mMoreSuggestionsBottomGap; + } + + public int setMoreSuggestionsHeight(final int remainingHeight) { + final int currentHeight = getMoreSuggestionsHeight(); + if (currentHeight <= remainingHeight) { + return currentHeight; + } + + mMaxMoreSuggestionsRow = (remainingHeight - mMoreSuggestionsBottomGap) + / mMoreSuggestionsRowHeight; + final int newHeight = getMoreSuggestionsHeight(); + return newHeight; + } + + private static Drawable getMoreSuggestionsHint(final Resources res, final float textSize, + final int color) { + final Paint paint = new Paint(); + paint.setAntiAlias(true); + paint.setTextAlign(Align.CENTER); + paint.setTextSize(textSize); + paint.setColor(color); + final Rect bounds = new Rect(); + paint.getTextBounds(MORE_SUGGESTIONS_HINT, 0, MORE_SUGGESTIONS_HINT.length(), bounds); + final int width = Math.round(bounds.width() + 0.5f); + final int height = Math.round(bounds.height() + 0.5f); + final Bitmap buffer = Bitmap.createBitmap(width, (height * 3 / 2), Bitmap.Config.ARGB_8888); + final Canvas canvas = new Canvas(buffer); + canvas.drawText(MORE_SUGGESTIONS_HINT, width / 2, height, paint); + return new BitmapDrawable(res, buffer); + } + + private CharSequence getStyledSuggestedWord(final SuggestedWords suggestedWords, + final int indexInSuggestedWords) { + if (indexInSuggestedWords >= suggestedWords.size()) { + return null; + } + final String word = suggestedWords.getWord(indexInSuggestedWords); + final boolean isAutoCorrect = indexInSuggestedWords == 1 + && suggestedWords.willAutoCorrect(); + final boolean isTypedWordValid = indexInSuggestedWords == 0 + && suggestedWords.mTypedWordValid; + if (!isAutoCorrect && !isTypedWordValid) { + return word; + } + + final int len = word.length(); + final Spannable spannedWord = new SpannableString(word); + final int option = mSuggestionStripOption; + if ((isAutoCorrect && (option & AUTO_CORRECT_BOLD) != 0) + || (isTypedWordValid && (option & VALID_TYPED_WORD_BOLD) != 0)) { + spannedWord.setSpan(BOLD_SPAN, 0, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + } + if (isAutoCorrect && (option & AUTO_CORRECT_UNDERLINE) != 0) { + spannedWord.setSpan(UNDERLINE_SPAN, 0, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); + } + return spannedWord; + } + + private int getPositionInSuggestionStrip(final int indexInSuggestedWords, + final SuggestedWords suggestedWords) { + final int indexToDisplayMostImportantSuggestion; + final int indexToDisplaySecondMostImportantSuggestion; + if (suggestedWords.willAutoCorrect()) { + indexToDisplayMostImportantSuggestion = SuggestedWords.INDEX_OF_AUTO_CORRECTION; + indexToDisplaySecondMostImportantSuggestion = SuggestedWords.INDEX_OF_TYPED_WORD; + } else { + indexToDisplayMostImportantSuggestion = SuggestedWords.INDEX_OF_TYPED_WORD; + indexToDisplaySecondMostImportantSuggestion = SuggestedWords.INDEX_OF_AUTO_CORRECTION; + } + if (indexInSuggestedWords == indexToDisplayMostImportantSuggestion) { + return mCenterPositionInStrip; + } + if (indexInSuggestedWords == indexToDisplaySecondMostImportantSuggestion) { + return mTypedWordPositionWhenAutocorrect; + } + // If neither of those, the order in the suggestion strip is the same as in SuggestedWords. + return indexInSuggestedWords; + } + + private int getSuggestionTextColor(final int indexInSuggestedWords, + final SuggestedWords suggestedWords) { + final int positionInStrip = + getPositionInSuggestionStrip(indexInSuggestedWords, suggestedWords); + // TODO: Need to revisit this logic with bigram suggestions + final boolean isSuggested = (indexInSuggestedWords != SuggestedWords.INDEX_OF_TYPED_WORD); + + final int color; + if (positionInStrip == mCenterPositionInStrip && suggestedWords.willAutoCorrect()) { + color = mColorAutoCorrect; + } else if (positionInStrip == mCenterPositionInStrip && suggestedWords.mTypedWordValid) { + color = mColorValidTypedWord; + } else if (isSuggested) { + color = mColorSuggested; + } else { + color = mColorTypedWord; + } + if (LatinImeLogger.sDBG && suggestedWords.size() > 1) { + // If we auto-correct, then the autocorrection is in slot 0 and the typed word + // is in slot 1. + if (positionInStrip == mCenterPositionInStrip + && AutoCorrectionUtils.shouldBlockAutoCorrectionBySafetyNet( + suggestedWords.getWord(SuggestedWords.INDEX_OF_AUTO_CORRECTION), + suggestedWords.getWord(SuggestedWords.INDEX_OF_TYPED_WORD))) { + return 0xFFFF0000; + } + } + + if (suggestedWords.mIsObsoleteSuggestions && isSuggested) { + return applyAlpha(color, mAlphaObsoleted); + } + return color; + } + + private static int applyAlpha(final int color, final float alpha) { + final int newAlpha = (int)(Color.alpha(color) * alpha); + return Color.argb(newAlpha, Color.red(color), Color.green(color), Color.blue(color)); + } + + private static void addDivider(final ViewGroup stripView, final View dividerView) { + stripView.addView(dividerView); + final LinearLayout.LayoutParams params = + (LinearLayout.LayoutParams)dividerView.getLayoutParams(); + params.gravity = Gravity.CENTER; + } + + public void layout(final SuggestedWords suggestedWords, final ViewGroup stripView, + final ViewGroup placerView) { + if (suggestedWords.mIsPunctuationSuggestions) { + layoutPunctuationSuggestions(suggestedWords, stripView); + return; + } + + final int countInStrip = mSuggestionsCountInStrip; + setupWordViewsTextAndColor(suggestedWords, countInStrip); + final TextView centerWordView = mWordViews.get(mCenterPositionInStrip); + final int stripWidth = placerView.getWidth(); + final int centerWidth = getSuggestionWidth(mCenterPositionInStrip, stripWidth); + if (getTextScaleX(centerWordView.getText(), centerWidth, centerWordView.getPaint()) + < MIN_TEXT_XSCALE) { + // Layout only the most relevant suggested word at the center of the suggestion strip + // by consolidating all slots in the strip. + mMoreSuggestionsAvailable = (suggestedWords.size() > 1); + layoutWord(mCenterPositionInStrip, stripWidth); + stripView.addView(centerWordView); + setLayoutWeight(centerWordView, 1.0f, ViewGroup.LayoutParams.MATCH_PARENT); + if (SuggestionStripView.DBG) { + layoutDebugInfo(mCenterPositionInStrip, placerView, stripWidth); + } + return; + } + + mMoreSuggestionsAvailable = (suggestedWords.size() > countInStrip); + int x = 0; + for (int positionInStrip = 0; positionInStrip < countInStrip; positionInStrip++) { + if (positionInStrip != 0) { + final View divider = mDividerViews.get(positionInStrip); + // Add divider if this isn't the left most suggestion in suggestions strip. + addDivider(stripView, divider); + x += divider.getMeasuredWidth(); + } + + final int width = getSuggestionWidth(positionInStrip, stripWidth); + final TextView wordView = layoutWord(positionInStrip, width); + stripView.addView(wordView); + setLayoutWeight(wordView, getSuggestionWeight(positionInStrip), + ViewGroup.LayoutParams.MATCH_PARENT); + x += wordView.getMeasuredWidth(); + + if (SuggestionStripView.DBG) { + layoutDebugInfo(positionInStrip, placerView, x); + } + } + } + + /** + * Format appropriately the suggested word in {@link #mWordViews} specified by + * <code>positionInStrip</code>. When the suggested word doesn't exist, the corresponding + * {@link TextView} will be disabled and never respond to user interaction. The suggested word + * may be shrunk or ellipsized to fit in the specified width. + * + * The <code>positionInStrip</code> argument is the index in the suggestion strip. The indices + * increase towards the right for LTR scripts and the left for RTL scripts, starting with 0. + * The position of the most important suggestion is in {@link #mCenterPositionInStrip}. This + * usually doesn't match the index in <code>suggedtedWords</code> -- see + * {@link #getPositionInSuggestionStrip(int,SuggestedWords)}. + * + * @param positionInStrip the position in the suggestion strip. + * @param width the maximum width for layout in pixels. + * @return the {@link TextView} containing the suggested word appropriately formatted. + */ + private TextView layoutWord(final int positionInStrip, final int width) { + final TextView wordView = mWordViews.get(positionInStrip); + final CharSequence word = wordView.getText(); + if (positionInStrip == mCenterPositionInStrip && mMoreSuggestionsAvailable) { + // TODO: This "more suggestions hint" should have a nicely designed icon. + wordView.setCompoundDrawablesWithIntrinsicBounds( + null, null, null, mMoreSuggestionsHint); + // HACK: Align with other TextViews that have no compound drawables. + wordView.setCompoundDrawablePadding(-mMoreSuggestionsHint.getIntrinsicHeight()); + } else { + wordView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); + } + + // Disable this suggestion if the suggestion is null or empty. + wordView.setEnabled(!TextUtils.isEmpty(word)); + final CharSequence text = getEllipsizedText(word, width, wordView.getPaint()); + final float scaleX = wordView.getTextScaleX(); + wordView.setText(text); // TextView.setText() resets text scale x to 1.0. + wordView.setTextScaleX(scaleX); + return wordView; + } + + private void layoutDebugInfo(final int positionInStrip, final ViewGroup placerView, + final int x) { + final TextView debugInfoView = mDebugInfoViews.get(positionInStrip); + final CharSequence debugInfo = debugInfoView.getText(); + if (debugInfo == null) { + return; + } + placerView.addView(debugInfoView); + debugInfoView.measure( + ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); + final int infoWidth = debugInfoView.getMeasuredWidth(); + final int y = debugInfoView.getMeasuredHeight(); + ViewLayoutUtils.placeViewAt( + debugInfoView, x - infoWidth, y, infoWidth, debugInfoView.getMeasuredHeight()); + } + + private int getSuggestionWidth(final int positionInStrip, final int maxWidth) { + final int paddings = mPadding * mSuggestionsCountInStrip; + final int dividers = mDividerWidth * (mSuggestionsCountInStrip - 1); + final int availableWidth = maxWidth - paddings - dividers; + return (int)(availableWidth * getSuggestionWeight(positionInStrip)); + } + + private float getSuggestionWeight(final int positionInStrip) { + if (positionInStrip == mCenterPositionInStrip) { + return mCenterSuggestionWeight; + } + // TODO: Revisit this for cases of 5 or more suggestions + return (1.0f - mCenterSuggestionWeight) / (mSuggestionsCountInStrip - 1); + } + + private void setupWordViewsTextAndColor(final SuggestedWords suggestedWords, + final int countInStrip) { + // Clear all suggestions first + for (int positionInStrip = 0; positionInStrip < countInStrip; ++positionInStrip) { + mWordViews.get(positionInStrip).setText(null); + // Make this inactive for touches in {@link #layoutWord(int,int)}. + if (SuggestionStripView.DBG) { + mDebugInfoViews.get(positionInStrip).setText(null); + } + } + final int count = Math.min(suggestedWords.size(), countInStrip); + for (int indexInSuggestedWords = 0; indexInSuggestedWords < count; + indexInSuggestedWords++) { + final int positionInStrip = + getPositionInSuggestionStrip(indexInSuggestedWords, suggestedWords); + final TextView wordView = mWordViews.get(positionInStrip); + // {@link TextView#getTag()} is used to get the index in suggestedWords at + // {@link SuggestionStripView#onClick(View)}. + wordView.setTag(indexInSuggestedWords); + wordView.setText(getStyledSuggestedWord(suggestedWords, indexInSuggestedWords)); + wordView.setTextColor(getSuggestionTextColor(positionInStrip, suggestedWords)); + if (SuggestionStripView.DBG) { + mDebugInfoViews.get(positionInStrip).setText( + suggestedWords.getDebugString(indexInSuggestedWords)); + } + } + } + + private void layoutPunctuationSuggestions(final SuggestedWords suggestedWords, + final ViewGroup stripView) { + final int countInStrip = Math.min(suggestedWords.size(), PUNCTUATIONS_IN_STRIP); + for (int positionInStrip = 0; positionInStrip < countInStrip; positionInStrip++) { + if (positionInStrip != 0) { + // Add divider if this isn't the left most suggestion in suggestions strip. + addDivider(stripView, mDividerViews.get(positionInStrip)); + } + + final TextView wordView = mWordViews.get(positionInStrip); + wordView.setEnabled(true); + wordView.setTextColor(mColorAutoCorrect); + // {@link TextView#getTag()} is used to get the index in suggestedWords at + // {@link SuggestionStripView#onClick(View)}. + wordView.setTag(positionInStrip); + wordView.setText(suggestedWords.getWord(positionInStrip)); + wordView.setTextScaleX(1.0f); + wordView.setCompoundDrawables(null, null, null, null); + stripView.addView(wordView); + setLayoutWeight(wordView, 1.0f, mSuggestionsStripHeight); + } + mMoreSuggestionsAvailable = (suggestedWords.size() > countInStrip); + } + + public void layoutAddToDictionaryHint(final String word, final ViewGroup stripView, + final int stripWidth, final CharSequence hintText, final OnClickListener listener) { + final int width = stripWidth - mDividerWidth - mPadding * 2; + + final TextView wordView = mWordToSaveView; + wordView.setTextColor(mColorTypedWord); + final int wordWidth = (int)(width * mCenterSuggestionWeight); + final CharSequence text = getEllipsizedText(word, wordWidth, wordView.getPaint()); + final float wordScaleX = wordView.getTextScaleX(); + // {@link TextView#setTag()} is used to hold the word to be added to dictionary. The word + // will be extracted at {@link #getAddToDictionaryWord()}. + wordView.setTag(word); + wordView.setText(text); + wordView.setTextScaleX(wordScaleX); + stripView.addView(wordView); + setLayoutWeight(wordView, mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT); + + stripView.addView(mDividerViews.get(0)); + + final TextView leftArrowView = mLeftwardsArrowView; + leftArrowView.setTextColor(mColorAutoCorrect); + leftArrowView.setText(LEFTWARDS_ARROW); + stripView.addView(leftArrowView); + + final TextView hintView = mHintToSaveView; + hintView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); + hintView.setTextColor(mColorAutoCorrect); + final int hintWidth = width - wordWidth - leftArrowView.getWidth(); + final float hintScaleX = getTextScaleX(hintText, hintWidth, hintView.getPaint()); + hintView.setText(hintText); + hintView.setTextScaleX(hintScaleX); + stripView.addView(hintView); + setLayoutWeight( + hintView, 1.0f - mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT); + + wordView.setOnClickListener(listener); + leftArrowView.setOnClickListener(listener); + hintView.setOnClickListener(listener); + } + + public String getAddToDictionaryWord() { + // String tag is set at + // {@link #layoutAddToDictionaryHint(String,ViewGroup,int,CharSequence,OnClickListener}. + return (String)mWordToSaveView.getTag(); + } + + public boolean isAddToDictionaryShowing(final View v) { + return v == mWordToSaveView || v == mHintToSaveView || v == mLeftwardsArrowView; + } + + private static void setLayoutWeight(final View v, final float weight, final int height) { + final ViewGroup.LayoutParams lp = v.getLayoutParams(); + if (lp instanceof LinearLayout.LayoutParams) { + final LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams)lp; + llp.weight = weight; + llp.width = 0; + llp.height = height; + } + } + + private static float getTextScaleX(final CharSequence text, final int maxWidth, + final TextPaint paint) { + paint.setTextScaleX(1.0f); + final int width = getTextWidth(text, paint); + if (width <= maxWidth) { + return 1.0f; + } + return maxWidth / (float)width; + } + + private static CharSequence getEllipsizedText(final CharSequence text, final int maxWidth, + final TextPaint paint) { + if (text == null) { + return null; + } + final float scaleX = getTextScaleX(text, maxWidth, paint); + if (scaleX >= MIN_TEXT_XSCALE) { + paint.setTextScaleX(scaleX); + return text; + } + + // Note that TextUtils.ellipsize() use text-x-scale as 1.0 if ellipsize is needed. To + // get squeezed and ellipsized text, passes enlarged width (maxWidth / MIN_TEXT_XSCALE). + final CharSequence ellipsized = TextUtils.ellipsize( + text, paint, maxWidth / MIN_TEXT_XSCALE, TextUtils.TruncateAt.MIDDLE); + paint.setTextScaleX(MIN_TEXT_XSCALE); + return ellipsized; + } + + private static int getTextWidth(final CharSequence text, final TextPaint paint) { + if (TextUtils.isEmpty(text)) { + return 0; + } + final Typeface savedTypeface = paint.getTypeface(); + paint.setTypeface(getTextTypeface(text)); + final int len = text.length(); + final float[] widths = new float[len]; + final int count = paint.getTextWidths(text, 0, len, widths); + int width = 0; + for (int i = 0; i < count; i++) { + width += Math.round(widths[i] + 0.5f); + } + paint.setTypeface(savedTypeface); + return width; + } + + private static Typeface getTextTypeface(final CharSequence text) { + if (!(text instanceof SpannableString)) { + return Typeface.DEFAULT; + } + + final SpannableString ss = (SpannableString)text; + final StyleSpan[] styles = ss.getSpans(0, text.length(), StyleSpan.class); + if (styles.length == 0) { + return Typeface.DEFAULT; + } + + if (styles[0].getStyle() == Typeface.BOLD) { + return Typeface.DEFAULT_BOLD; + } + // TODO: BOLD_ITALIC, ITALIC case? + return Typeface.DEFAULT; + } +} diff --git a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java index ad350a02f..497a791d9 100644 --- a/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java +++ b/java/src/com/android/inputmethod/latin/suggestions/SuggestionStripView.java @@ -18,34 +18,14 @@ package com.android.inputmethod.latin.suggestions; import android.content.Context; import android.content.res.Resources; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Paint.Align; -import android.graphics.Rect; -import android.graphics.Typeface; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.text.Spannable; -import android.text.SpannableString; -import android.text.Spanned; -import android.text.TextPaint; -import android.text.TextUtils; -import android.text.style.CharacterStyle; -import android.text.style.StyleSpan; -import android.text.style.UnderlineSpan; import android.util.AttributeSet; import android.view.GestureDetector; -import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.ViewGroup; -import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; @@ -53,18 +33,15 @@ import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.MainKeyboardView; import com.android.inputmethod.keyboard.MoreKeysPanel; -import com.android.inputmethod.keyboard.ViewLayoutUtils; -import com.android.inputmethod.latin.AutoCorrection; -import com.android.inputmethod.latin.CollectionUtils; +import com.android.inputmethod.latin.AudioAndHapticFeedbackManager; import com.android.inputmethod.latin.Constants; import com.android.inputmethod.latin.LatinImeLogger; import com.android.inputmethod.latin.R; -import com.android.inputmethod.latin.ResourceUtils; import com.android.inputmethod.latin.SuggestedWords; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; -import com.android.inputmethod.latin.Utils; import com.android.inputmethod.latin.define.ProductionFlag; import com.android.inputmethod.latin.suggestions.MoreSuggestions.MoreSuggestionsListener; +import com.android.inputmethod.latin.utils.CollectionUtils; import com.android.inputmethod.research.ResearchLogger; import java.util.ArrayList; @@ -88,477 +65,14 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick private final MoreSuggestionsView mMoreSuggestionsView; private final MoreSuggestions.Builder mMoreSuggestionsBuilder; - private final ArrayList<TextView> mWords = CollectionUtils.newArrayList(); - private final ArrayList<TextView> mInfos = CollectionUtils.newArrayList(); - private final ArrayList<View> mDividers = CollectionUtils.newArrayList(); + private final ArrayList<TextView> mWordViews = CollectionUtils.newArrayList(); + private final ArrayList<TextView> mDebugInfoViews = CollectionUtils.newArrayList(); + private final ArrayList<View> mDividerViews = CollectionUtils.newArrayList(); Listener mListener; private SuggestedWords mSuggestedWords = SuggestedWords.EMPTY; - private final SuggestionStripViewParams mParams; - private static final float MIN_TEXT_XSCALE = 0.70f; - - private static final class SuggestionStripViewParams { - private static final int DEFAULT_SUGGESTIONS_COUNT_IN_STRIP = 3; - private static final float DEFAULT_CENTER_SUGGESTION_PERCENTILE = 0.40f; - private static final int DEFAULT_MAX_MORE_SUGGESTIONS_ROW = 2; - private static final int PUNCTUATIONS_IN_STRIP = 5; - - public final int mPadding; - public final int mDividerWidth; - public final int mSuggestionsStripHeight; - public final int mSuggestionsCountInStrip; - public final int mMoreSuggestionsRowHeight; - private int mMaxMoreSuggestionsRow; - public final float mMinMoreSuggestionsWidth; - public final int mMoreSuggestionsBottomGap; - - private final ArrayList<TextView> mWords; - private final ArrayList<View> mDividers; - private final ArrayList<TextView> mInfos; - - private final int mColorValidTypedWord; - private final int mColorTypedWord; - private final int mColorAutoCorrect; - private final int mColorSuggested; - private final float mAlphaObsoleted; - private final float mCenterSuggestionWeight; - private final int mCenterSuggestionIndex; - private final Drawable mMoreSuggestionsHint; - private static final String MORE_SUGGESTIONS_HINT = "\u2026"; - private static final String LEFTWARDS_ARROW = "\u2190"; - - private static final CharacterStyle BOLD_SPAN = new StyleSpan(Typeface.BOLD); - private static final CharacterStyle UNDERLINE_SPAN = new UnderlineSpan(); - private static final int AUTO_CORRECT_BOLD = 0x01; - private static final int AUTO_CORRECT_UNDERLINE = 0x02; - private static final int VALID_TYPED_WORD_BOLD = 0x04; - - private final int mSuggestionStripOption; - - private final ArrayList<CharSequence> mTexts = CollectionUtils.newArrayList(); - - public boolean mMoreSuggestionsAvailable; - - private final TextView mWordToSaveView; - private final TextView mLeftwardsArrowView; - private final TextView mHintToSaveView; - - public SuggestionStripViewParams(final Context context, final AttributeSet attrs, - final int defStyle, final ArrayList<TextView> words, final ArrayList<View> dividers, - final ArrayList<TextView> infos) { - mWords = words; - mDividers = dividers; - mInfos = infos; - - final TextView word = words.get(0); - final View divider = dividers.get(0); - mPadding = word.getCompoundPaddingLeft() + word.getCompoundPaddingRight(); - divider.measure( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - mDividerWidth = divider.getMeasuredWidth(); - - final Resources res = word.getResources(); - mSuggestionsStripHeight = res.getDimensionPixelSize(R.dimen.suggestions_strip_height); - - final TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.SuggestionStripView, defStyle, R.style.SuggestionStripViewStyle); - mSuggestionStripOption = a.getInt( - R.styleable.SuggestionStripView_suggestionStripOption, 0); - final float alphaValidTypedWord = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_alphaValidTypedWord, 1.0f); - final float alphaTypedWord = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_alphaTypedWord, 1.0f); - final float alphaAutoCorrect = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_alphaAutoCorrect, 1.0f); - final float alphaSuggested = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_alphaSuggested, 1.0f); - mAlphaObsoleted = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_alphaSuggested, 1.0f); - mColorValidTypedWord = applyAlpha(a.getColor( - R.styleable.SuggestionStripView_colorValidTypedWord, 0), alphaValidTypedWord); - mColorTypedWord = applyAlpha(a.getColor( - R.styleable.SuggestionStripView_colorTypedWord, 0), alphaTypedWord); - mColorAutoCorrect = applyAlpha(a.getColor( - R.styleable.SuggestionStripView_colorAutoCorrect, 0), alphaAutoCorrect); - mColorSuggested = applyAlpha(a.getColor( - R.styleable.SuggestionStripView_colorSuggested, 0), alphaSuggested); - mSuggestionsCountInStrip = a.getInt( - R.styleable.SuggestionStripView_suggestionsCountInStrip, - DEFAULT_SUGGESTIONS_COUNT_IN_STRIP); - mCenterSuggestionWeight = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_centerSuggestionPercentile, - DEFAULT_CENTER_SUGGESTION_PERCENTILE); - mMaxMoreSuggestionsRow = a.getInt( - R.styleable.SuggestionStripView_maxMoreSuggestionsRow, - DEFAULT_MAX_MORE_SUGGESTIONS_ROW); - mMinMoreSuggestionsWidth = ResourceUtils.getFraction(a, - R.styleable.SuggestionStripView_minMoreSuggestionsWidth, 1.0f); - a.recycle(); - - mMoreSuggestionsHint = getMoreSuggestionsHint(res, - res.getDimension(R.dimen.more_suggestions_hint_text_size), mColorAutoCorrect); - mCenterSuggestionIndex = mSuggestionsCountInStrip / 2; - mMoreSuggestionsBottomGap = res.getDimensionPixelOffset( - R.dimen.more_suggestions_bottom_gap); - mMoreSuggestionsRowHeight = res.getDimensionPixelSize( - R.dimen.more_suggestions_row_height); - - final LayoutInflater inflater = LayoutInflater.from(context); - mWordToSaveView = (TextView)inflater.inflate(R.layout.suggestion_word, null); - mLeftwardsArrowView = (TextView)inflater.inflate(R.layout.hint_add_to_dictionary, null); - mHintToSaveView = (TextView)inflater.inflate(R.layout.hint_add_to_dictionary, null); - } - - public int getMaxMoreSuggestionsRow() { - return mMaxMoreSuggestionsRow; - } - - private int getMoreSuggestionsHeight() { - return mMaxMoreSuggestionsRow * mMoreSuggestionsRowHeight + mMoreSuggestionsBottomGap; - } - - public int setMoreSuggestionsHeight(final int remainingHeight) { - final int currentHeight = getMoreSuggestionsHeight(); - if (currentHeight <= remainingHeight) { - return currentHeight; - } - - mMaxMoreSuggestionsRow = (remainingHeight - mMoreSuggestionsBottomGap) - / mMoreSuggestionsRowHeight; - final int newHeight = getMoreSuggestionsHeight(); - return newHeight; - } - - private static Drawable getMoreSuggestionsHint(final Resources res, final float textSize, - final int color) { - final Paint paint = new Paint(); - paint.setAntiAlias(true); - paint.setTextAlign(Align.CENTER); - paint.setTextSize(textSize); - paint.setColor(color); - final Rect bounds = new Rect(); - paint.getTextBounds(MORE_SUGGESTIONS_HINT, 0, MORE_SUGGESTIONS_HINT.length(), bounds); - final int width = Math.round(bounds.width() + 0.5f); - final int height = Math.round(bounds.height() + 0.5f); - final Bitmap buffer = Bitmap.createBitmap( - width, (height * 3 / 2), Bitmap.Config.ARGB_8888); - final Canvas canvas = new Canvas(buffer); - canvas.drawText(MORE_SUGGESTIONS_HINT, width / 2, height, paint); - return new BitmapDrawable(res, buffer); - } - - private CharSequence getStyledSuggestionWord(final SuggestedWords suggestedWords, - final int pos) { - final String word = suggestedWords.getWord(pos); - final boolean isAutoCorrect = pos == 1 && suggestedWords.willAutoCorrect(); - final boolean isTypedWordValid = pos == 0 && suggestedWords.mTypedWordValid; - if (!isAutoCorrect && !isTypedWordValid) - return word; - - final int len = word.length(); - final Spannable spannedWord = new SpannableString(word); - final int option = mSuggestionStripOption; - if ((isAutoCorrect && (option & AUTO_CORRECT_BOLD) != 0) - || (isTypedWordValid && (option & VALID_TYPED_WORD_BOLD) != 0)) { - spannedWord.setSpan(BOLD_SPAN, 0, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - } - if (isAutoCorrect && (option & AUTO_CORRECT_UNDERLINE) != 0) { - spannedWord.setSpan(UNDERLINE_SPAN, 0, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); - } - return spannedWord; - } - - private int getWordPosition(final int index, final SuggestedWords suggestedWords) { - // TODO: This works for 3 suggestions. Revisit this algorithm when there are 5 or more - // suggestions. - final int centerPos = suggestedWords.willAutoCorrect() ? 1 : 0; - if (index == mCenterSuggestionIndex) { - return centerPos; - } else if (index == centerPos) { - return mCenterSuggestionIndex; - } else { - return index; - } - } - - private int getSuggestionTextColor(final int index, final SuggestedWords suggestedWords, - final int pos) { - // TODO: Need to revisit this logic with bigram suggestions - final boolean isSuggested = (pos != 0); - - final int color; - if (index == mCenterSuggestionIndex && suggestedWords.willAutoCorrect()) { - color = mColorAutoCorrect; - } else if (index == mCenterSuggestionIndex && suggestedWords.mTypedWordValid) { - color = mColorValidTypedWord; - } else if (isSuggested) { - color = mColorSuggested; - } else { - color = mColorTypedWord; - } - if (LatinImeLogger.sDBG && suggestedWords.size() > 1) { - // If we auto-correct, then the autocorrection is in slot 0 and the typed word - // is in slot 1. - if (index == mCenterSuggestionIndex - && AutoCorrection.shouldBlockAutoCorrectionBySafetyNet( - suggestedWords.getWord(1), suggestedWords.getWord(0))) { - return 0xFFFF0000; - } - } - - if (suggestedWords.mIsObsoleteSuggestions && isSuggested) { - return applyAlpha(color, mAlphaObsoleted); - } else { - return color; - } - } - - private static int applyAlpha(final int color, final float alpha) { - final int newAlpha = (int)(Color.alpha(color) * alpha); - return Color.argb(newAlpha, Color.red(color), Color.green(color), Color.blue(color)); - } - - private static void addDivider(final ViewGroup stripView, final View divider) { - stripView.addView(divider); - final LinearLayout.LayoutParams params = - (LinearLayout.LayoutParams)divider.getLayoutParams(); - params.gravity = Gravity.CENTER; - } - - public void layout(final SuggestedWords suggestedWords, final ViewGroup stripView, - final ViewGroup placer, final int stripWidth) { - if (suggestedWords.mIsPunctuationSuggestions) { - layoutPunctuationSuggestions(suggestedWords, stripView); - return; - } - - final int countInStrip = mSuggestionsCountInStrip; - setupTexts(suggestedWords, countInStrip); - mMoreSuggestionsAvailable = (suggestedWords.size() > countInStrip); - int x = 0; - for (int index = 0; index < countInStrip; index++) { - final int pos = getWordPosition(index, suggestedWords); - - if (index != 0) { - final View divider = mDividers.get(pos); - // Add divider if this isn't the left most suggestion in suggestions strip. - addDivider(stripView, divider); - x += divider.getMeasuredWidth(); - } - - final CharSequence styled = mTexts.get(pos); - final TextView word = mWords.get(pos); - if (index == mCenterSuggestionIndex && mMoreSuggestionsAvailable) { - // TODO: This "more suggestions hint" should have nicely designed icon. - word.setCompoundDrawablesWithIntrinsicBounds( - null, null, null, mMoreSuggestionsHint); - // HACK: To align with other TextView that has no compound drawables. - word.setCompoundDrawablePadding(-mMoreSuggestionsHint.getIntrinsicHeight()); - } else { - word.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); - } - - // Disable this suggestion if the suggestion is null or empty. - word.setEnabled(!TextUtils.isEmpty(styled)); - word.setTextColor(getSuggestionTextColor(index, suggestedWords, pos)); - final int width = getSuggestionWidth(index, stripWidth); - final CharSequence text = getEllipsizedText(styled, width, word.getPaint()); - final float scaleX = word.getTextScaleX(); - word.setText(text); // TextView.setText() resets text scale x to 1.0. - word.setTextScaleX(scaleX); - stripView.addView(word); - setLayoutWeight( - word, getSuggestionWeight(index), ViewGroup.LayoutParams.MATCH_PARENT); - x += word.getMeasuredWidth(); - - if (DBG && pos < suggestedWords.size()) { - final String debugInfo = Utils.getDebugInfo(suggestedWords, pos); - if (debugInfo != null) { - final TextView info = mInfos.get(pos); - info.setText(debugInfo); - placer.addView(info); - info.measure(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT); - final int infoWidth = info.getMeasuredWidth(); - final int y = info.getMeasuredHeight(); - ViewLayoutUtils.placeViewAt( - info, x - infoWidth, y, infoWidth, info.getMeasuredHeight()); - } - } - } - } - - private int getSuggestionWidth(final int index, final int maxWidth) { - final int paddings = mPadding * mSuggestionsCountInStrip; - final int dividers = mDividerWidth * (mSuggestionsCountInStrip - 1); - final int availableWidth = maxWidth - paddings - dividers; - return (int)(availableWidth * getSuggestionWeight(index)); - } - - private float getSuggestionWeight(final int index) { - if (index == mCenterSuggestionIndex) { - return mCenterSuggestionWeight; - } else { - // TODO: Revisit this for cases of 5 or more suggestions - return (1.0f - mCenterSuggestionWeight) / (mSuggestionsCountInStrip - 1); - } - } - - private void setupTexts(final SuggestedWords suggestedWords, final int countInStrip) { - mTexts.clear(); - final int count = Math.min(suggestedWords.size(), countInStrip); - for (int pos = 0; pos < count; pos++) { - final CharSequence styled = getStyledSuggestionWord(suggestedWords, pos); - mTexts.add(styled); - } - for (int pos = count; pos < countInStrip; pos++) { - // Make this inactive for touches in layout(). - mTexts.add(null); - } - } - - private void layoutPunctuationSuggestions(final SuggestedWords suggestedWords, - final ViewGroup stripView) { - final int countInStrip = Math.min(suggestedWords.size(), PUNCTUATIONS_IN_STRIP); - for (int index = 0; index < countInStrip; index++) { - if (index != 0) { - // Add divider if this isn't the left most suggestion in suggestions strip. - addDivider(stripView, mDividers.get(index)); - } - - final TextView word = mWords.get(index); - word.setEnabled(true); - word.setTextColor(mColorAutoCorrect); - final String text = suggestedWords.getWord(index); - word.setText(text); - word.setTextScaleX(1.0f); - word.setCompoundDrawables(null, null, null, null); - stripView.addView(word); - setLayoutWeight(word, 1.0f, mSuggestionsStripHeight); - } - mMoreSuggestionsAvailable = false; - } - - public void layoutAddToDictionaryHint(final String word, final ViewGroup stripView, - final int stripWidth, final CharSequence hintText, final OnClickListener listener) { - final int width = stripWidth - mDividerWidth - mPadding * 2; - - final TextView wordView = mWordToSaveView; - wordView.setTextColor(mColorTypedWord); - final int wordWidth = (int)(width * mCenterSuggestionWeight); - final CharSequence text = getEllipsizedText(word, wordWidth, wordView.getPaint()); - final float wordScaleX = wordView.getTextScaleX(); - wordView.setTag(word); - wordView.setText(text); - wordView.setTextScaleX(wordScaleX); - stripView.addView(wordView); - setLayoutWeight(wordView, mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT); - - stripView.addView(mDividers.get(0)); - - final TextView leftArrowView = mLeftwardsArrowView; - leftArrowView.setTextColor(mColorAutoCorrect); - leftArrowView.setText(LEFTWARDS_ARROW); - stripView.addView(leftArrowView); - - final TextView hintView = mHintToSaveView; - hintView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); - hintView.setTextColor(mColorAutoCorrect); - final int hintWidth = width - wordWidth - leftArrowView.getWidth(); - final float hintScaleX = getTextScaleX(hintText, hintWidth, hintView.getPaint()); - hintView.setText(hintText); - hintView.setTextScaleX(hintScaleX); - stripView.addView(hintView); - setLayoutWeight( - hintView, 1.0f - mCenterSuggestionWeight, ViewGroup.LayoutParams.MATCH_PARENT); - - wordView.setOnClickListener(listener); - leftArrowView.setOnClickListener(listener); - hintView.setOnClickListener(listener); - } - - public CharSequence getAddToDictionaryWord() { - return (CharSequence)mWordToSaveView.getTag(); - } - - public boolean isAddToDictionaryShowing(final View v) { - return v == mWordToSaveView || v == mHintToSaveView || v == mLeftwardsArrowView; - } - - private static void setLayoutWeight(final View v, final float weight, final int height) { - final ViewGroup.LayoutParams lp = v.getLayoutParams(); - if (lp instanceof LinearLayout.LayoutParams) { - final LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams)lp; - llp.weight = weight; - llp.width = 0; - llp.height = height; - } - } - - private static float getTextScaleX(final CharSequence text, final int maxWidth, - final TextPaint paint) { - paint.setTextScaleX(1.0f); - final int width = getTextWidth(text, paint); - if (width <= maxWidth) { - return 1.0f; - } - return maxWidth / (float)width; - } - - private static CharSequence getEllipsizedText(final CharSequence text, final int maxWidth, - final TextPaint paint) { - if (text == null) return null; - paint.setTextScaleX(1.0f); - final int width = getTextWidth(text, paint); - if (width <= maxWidth) { - return text; - } - final float scaleX = maxWidth / (float)width; - if (scaleX >= MIN_TEXT_XSCALE) { - paint.setTextScaleX(scaleX); - return text; - } - - // Note that TextUtils.ellipsize() use text-x-scale as 1.0 if ellipsize is needed. To - // get squeezed and ellipsized text, passes enlarged width (maxWidth / MIN_TEXT_XSCALE). - final CharSequence ellipsized = TextUtils.ellipsize( - text, paint, maxWidth / MIN_TEXT_XSCALE, TextUtils.TruncateAt.MIDDLE); - paint.setTextScaleX(MIN_TEXT_XSCALE); - return ellipsized; - } - - private static int getTextWidth(final CharSequence text, final TextPaint paint) { - if (TextUtils.isEmpty(text)) return 0; - final Typeface savedTypeface = paint.getTypeface(); - paint.setTypeface(getTextTypeface(text)); - final int len = text.length(); - final float[] widths = new float[len]; - final int count = paint.getTextWidths(text, 0, len, widths); - int width = 0; - for (int i = 0; i < count; i++) { - width += Math.round(widths[i] + 0.5f); - } - paint.setTypeface(savedTypeface); - return width; - } - - private static Typeface getTextTypeface(final CharSequence text) { - if (!(text instanceof SpannableString)) - return Typeface.DEFAULT; - - final SpannableString ss = (SpannableString)text; - final StyleSpan[] styles = ss.getSpans(0, text.length(), StyleSpan.class); - if (styles.length == 0) - return Typeface.DEFAULT; - - switch (styles[0].getStyle()) { - case Typeface.BOLD: return Typeface.DEFAULT_BOLD; - // TODO: BOLD_ITALIC, ITALIC case? - default: return Typeface.DEFAULT; - } - } - } + private final SuggestionStripLayoutHelper mLayoutHelper; /** * Construct a {@link SuggestionStripView} for showing suggestions to be picked by the user. @@ -579,19 +93,17 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick mSuggestionsStrip = (ViewGroup)findViewById(R.id.suggestions_strip); for (int pos = 0; pos < MAX_SUGGESTIONS; pos++) { final TextView word = (TextView)inflater.inflate(R.layout.suggestion_word, null); - word.setTag(pos); word.setOnClickListener(this); word.setOnLongClickListener(this); - mWords.add(word); + mWordViews.add(word); final View divider = inflater.inflate(R.layout.suggestion_divider, null); - divider.setTag(pos); divider.setOnClickListener(this); - mDividers.add(divider); - mInfos.add((TextView)inflater.inflate(R.layout.suggestion_info, null)); + mDividerViews.add(divider); + mDebugInfoViews.add((TextView)inflater.inflate(R.layout.suggestion_info, null)); } - mParams = new SuggestionStripViewParams( - context, attrs, defStyle, mWords, mDividers, mInfos); + mLayoutHelper = new SuggestionStripLayoutHelper( + context, attrs, defStyle, mWordViews, mDividerViews, mDebugInfoViews); mMoreSuggestionsContainer = inflater.inflate(R.layout.more_suggestions, null); mMoreSuggestionsView = (MoreSuggestionsView)mMoreSuggestionsContainer @@ -617,24 +129,25 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick public void setSuggestions(final SuggestedWords suggestedWords) { clear(); mSuggestedWords = suggestedWords; - mParams.layout(mSuggestedWords, mSuggestionsStrip, this, getWidth()); + mLayoutHelper.layout(mSuggestedWords, mSuggestionsStrip, this); if (ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS) { ResearchLogger.suggestionStripView_setSuggestions(mSuggestedWords); } } public int setMoreSuggestionsHeight(final int remainingHeight) { - return mParams.setMoreSuggestionsHeight(remainingHeight); + return mLayoutHelper.setMoreSuggestionsHeight(remainingHeight); } public boolean isShowingAddToDictionaryHint() { return mSuggestionsStrip.getChildCount() > 0 - && mParams.isAddToDictionaryShowing(mSuggestionsStrip.getChildAt(0)); + && mLayoutHelper.isAddToDictionaryShowing(mSuggestionsStrip.getChildAt(0)); } public void showAddToDictionaryHint(final String word, final CharSequence hintText) { clear(); - mParams.layoutAddToDictionaryHint(word, mSuggestionsStrip, getWidth(), hintText, this); + mLayoutHelper.layoutAddToDictionaryHint( + word, mSuggestionsStrip, getWidth(), hintText, this); } public boolean dismissAddToDictionaryHint() { @@ -649,27 +162,27 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick mSuggestionsStrip.removeAllViews(); removeAllViews(); addView(mSuggestionsStrip); - dismissMoreSuggestions(); + mMoreSuggestionsView.dismissMoreKeysPanel(); } private final MoreSuggestionsListener mMoreSuggestionsListener = new MoreSuggestionsListener() { @Override public void onSuggestionSelected(final int index, final SuggestedWordInfo wordInfo) { mListener.pickSuggestionManually(index, wordInfo); - dismissMoreSuggestions(); + mMoreSuggestionsView.dismissMoreKeysPanel(); } @Override public void onCancelInput() { - dismissMoreSuggestions(); + mMoreSuggestionsView.dismissMoreKeysPanel(); } }; private final MoreKeysPanel.Controller mMoreSuggestionsController = new MoreKeysPanel.Controller() { @Override - public boolean onDismissMoreKeysPanel() { - return mMainKeyboardView.onDismissMoreKeysPanel(); + public void onDismissMoreKeysPanel(final MoreKeysPanel panel) { + mMainKeyboardView.onDismissMoreKeysPanel(panel); } @Override @@ -678,18 +191,15 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick } @Override - public void onCancelMoreKeysPanel() { - dismissMoreSuggestions(); + public void onCancelMoreKeysPanel(final MoreKeysPanel panel) { + mMoreSuggestionsView.dismissMoreKeysPanel(); } }; - boolean dismissMoreSuggestions() { - return mMoreSuggestionsView.dismissMoreKeysPanel(); - } - @Override public boolean onLongClick(final View view) { - KeyboardSwitcher.getInstance().hapticAndAudioFeedback(Constants.NOT_A_CODE); + AudioAndHapticFeedbackManager.getInstance().hapticAndAudioFeedback( + Constants.NOT_A_CODE, this); return showMoreSuggestions(); } @@ -698,30 +208,30 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick if (parentKeyboard == null) { return false; } - final SuggestionStripViewParams params = mParams; - if (!params.mMoreSuggestionsAvailable) { + final SuggestionStripLayoutHelper layoutHelper = mLayoutHelper; + if (!layoutHelper.mMoreSuggestionsAvailable) { return false; } final int stripWidth = getWidth(); final View container = mMoreSuggestionsContainer; final int maxWidth = stripWidth - container.getPaddingLeft() - container.getPaddingRight(); final MoreSuggestions.Builder builder = mMoreSuggestionsBuilder; - builder.layout(mSuggestedWords, params.mSuggestionsCountInStrip, maxWidth, - (int)(maxWidth * params.mMinMoreSuggestionsWidth), - params.getMaxMoreSuggestionsRow(), parentKeyboard); + builder.layout(mSuggestedWords, layoutHelper.mSuggestionsCountInStrip, maxWidth, + (int)(maxWidth * layoutHelper.mMinMoreSuggestionsWidth), + layoutHelper.getMaxMoreSuggestionsRow(), parentKeyboard); mMoreSuggestionsView.setKeyboard(builder.build()); container.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); final MoreKeysPanel moreKeysPanel = mMoreSuggestionsView; final int pointX = stripWidth / 2; - final int pointY = -params.mMoreSuggestionsBottomGap; + final int pointY = -layoutHelper.mMoreSuggestionsBottomGap; moreKeysPanel.showMoreKeysPanel(this, mMoreSuggestionsController, pointX, pointY, mMoreSuggestionsListener); mMoreSuggestionsMode = MORE_SUGGESTIONS_CHECKING_MODAL_OR_SLIDING; mOriginX = mLastX; mOriginY = mLastY; - for (int i = 0; i < params.mSuggestionsCountInStrip; i++) { - mWords.get(i).setPressed(false); + for (int i = 0; i < layoutHelper.mSuggestionsCountInStrip; i++) { + mWordViews.get(i).setPressed(false); } return true; } @@ -791,18 +301,23 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick @Override public void onClick(final View view) { - if (mParams.isAddToDictionaryShowing(view)) { - mListener.addWordToUserDictionary(mParams.getAddToDictionaryWord().toString()); + if (mLayoutHelper.isAddToDictionaryShowing(view)) { + mListener.addWordToUserDictionary(mLayoutHelper.getAddToDictionaryWord()); clear(); return; } final Object tag = view.getTag(); - if (!(tag instanceof Integer)) + // Integer tag is set at + // {@link SuggestionStripLayoutHelper#setupWordViewsTextAndColor(SuggestedWords,int)} and + // {@link SuggestionStripLayoutHelper#layoutPunctuationSuggestions(SuggestedWords,ViewGroup} + if (!(tag instanceof Integer)) { return; + } final int index = (Integer) tag; - if (index >= mSuggestedWords.size()) + if (index >= mSuggestedWords.size()) { return; + } final SuggestedWordInfo wordInfo = mSuggestedWords.getInfo(index); mListener.pickSuggestionManually(index, wordInfo); @@ -811,6 +326,6 @@ public final class SuggestionStripView extends RelativeLayout implements OnClick @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); - dismissMoreSuggestions(); + mMoreSuggestionsView.dismissMoreKeysPanel(); } } diff --git a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordContents.java b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordContents.java index 2b6fda381..21426d1eb 100644 --- a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordContents.java +++ b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordContents.java @@ -16,10 +16,6 @@ package com.android.inputmethod.latin.userdictionary; -import com.android.inputmethod.compat.UserDictionaryCompatUtils; -import com.android.inputmethod.latin.LocaleUtils; -import com.android.inputmethod.latin.R; - import android.app.Activity; import android.content.ContentResolver; import android.content.Context; @@ -30,6 +26,10 @@ import android.text.TextUtils; import android.view.View; import android.widget.EditText; +import com.android.inputmethod.compat.UserDictionaryCompatUtils; +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.utils.LocaleUtils; + import java.util.ArrayList; import java.util.Locale; import java.util.TreeSet; @@ -65,6 +65,8 @@ public class UserDictionaryAddWordContents { private String mLocale; private final String mOldWord; private final String mOldShortcut; + private String mSavedWord; + private String mSavedShortcut; /* package */ UserDictionaryAddWordContents(final View view, final Bundle args) { mWordEditText = (EditText)view.findViewById(R.id.user_dictionary_add_word_text); @@ -76,7 +78,9 @@ public class UserDictionaryAddWordContents { final String word = args.getString(EXTRA_WORD); if (null != word) { mWordEditText.setText(word); - mWordEditText.setSelection(word.length()); + // Use getText in case the edit text modified the text we set. This happens when + // it's too long to be edited. + mWordEditText.setSelection(mWordEditText.getText().length()); } final String shortcut; if (UserDictionarySettings.IS_SHORTCUT_API_SUPPORTED) { @@ -94,6 +98,16 @@ public class UserDictionaryAddWordContents { updateLocale(args.getString(EXTRA_LOCALE)); } + /* package */ UserDictionaryAddWordContents(final View view, + final UserDictionaryAddWordContents oldInstanceToBeEdited) { + mWordEditText = (EditText)view.findViewById(R.id.user_dictionary_add_word_text); + mShortcutEditText = (EditText)view.findViewById(R.id.user_dictionary_add_shortcut); + mMode = MODE_EDIT; + mOldWord = oldInstanceToBeEdited.mSavedWord; + mOldShortcut = oldInstanceToBeEdited.mSavedShortcut; + updateLocale(mLocale); + } + // locale may be null, this means default locale // It may also be the empty string, which means "all locales" /* package */ void updateLocale(final String locale) { @@ -147,6 +161,8 @@ public class UserDictionaryAddWordContents { // If the word is somehow empty, don't insert it. return CODE_CANCEL; } + mSavedWord = newWord; + mSavedShortcut = newShortcut; // If there is no shortcut, and the word already exists in the database, then we // should not insert, because either A. the word exists with no shortcut, in which // case the exact same thing we want to insert is already there, or B. the word @@ -258,4 +274,8 @@ public class UserDictionaryAddWordContents { localesList.add(new LocaleRenderer(activity, null)); // meaning: select another locale return localesList; } + + public String getCurrentUserDictionaryLocale() { + return mLocale; + } } diff --git a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordFragment.java b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordFragment.java index 58c8f266c..4fc132f68 100644 --- a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordFragment.java +++ b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryAddWordFragment.java @@ -57,23 +57,39 @@ public class UserDictionaryAddWordFragment extends Fragment private boolean mIsDeleting = false; @Override - public void onActivityCreated(Bundle savedInstanceState) { + public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setHasOptionsMenu(true); + getActivity().getActionBar().setTitle(R.string.edit_personal_dictionary); + // Keep the instance so that we remember mContents when configuration changes (eg rotation) + setRetainInstance(true); } @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) { + public View onCreateView(final LayoutInflater inflater, final ViewGroup container, + final Bundle savedState) { mRootView = inflater.inflate(R.layout.user_dictionary_add_word_fullscreen, null); mIsDeleting = false; + // If we have a non-null mContents object, it's the old value before a configuration + // change (eg rotation) so we need to use its values. Otherwise, read from the arguments. if (null == mContents) { mContents = new UserDictionaryAddWordContents(mRootView, getArguments()); + } else { + // We create a new mContents object to account for the new situation : a word has + // been added to the user dictionary when we started rotating, and we are now editing + // it. That means in particular if the word undergoes any change, the old version should + // be updated, so the mContents object needs to switch to EDIT mode if it was in + // INSERT mode. + mContents = new UserDictionaryAddWordContents(mRootView, + mContents /* oldInstanceToBeEdited */); } + getActivity().getActionBar().setSubtitle(UserDictionarySettingsUtils.getLocaleDisplayName( + getActivity(), mContents.getCurrentUserDictionaryLocale())); return mRootView; } @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { final MenuItem actionItemAdd = menu.add(0, OPTIONS_MENU_ADD, 0, R.string.user_dict_settings_add_menu_title).setIcon(R.drawable.ic_menu_add); actionItemAdd.setShowAsAction( @@ -87,7 +103,7 @@ public class UserDictionaryAddWordFragment extends Fragment /** * Callback for the framework when a menu option is pressed. * - * @param MenuItem the item that was pressed + * @param item the item that was pressed * @return false to allow normal menu processing to proceed, true to consume it here */ @Override diff --git a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryList.java b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryList.java index 6e64882b6..32c4950da 100644 --- a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryList.java +++ b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionaryList.java @@ -16,10 +16,8 @@ package com.android.inputmethod.latin.userdictionary; -import com.android.inputmethod.latin.LocaleUtils; -import com.android.inputmethod.latin.R; - import android.app.Activity; +import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; @@ -28,7 +26,14 @@ import android.preference.PreferenceFragment; import android.preference.PreferenceGroup; import android.provider.UserDictionary; import android.text.TextUtils; +import android.view.inputmethod.InputMethodInfo; +import android.view.inputmethod.InputMethodManager; +import android.view.inputmethod.InputMethodSubtype; + +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.utils.LocaleUtils; +import java.util.List; import java.util.Locale; import java.util.TreeSet; @@ -52,8 +57,7 @@ public class UserDictionaryList extends PreferenceFragment { final Cursor cursor = activity.managedQuery(UserDictionary.Words.CONTENT_URI, new String[] { UserDictionary.Words.LOCALE }, null, null, null); - final TreeSet<String> localeList = new TreeSet<String>(); - boolean addedAllLocale = false; + final TreeSet<String> localeSet = new TreeSet<String>(); if (null == cursor) { // The user dictionary service is not present or disabled. Return null. return null; @@ -61,20 +65,39 @@ public class UserDictionaryList extends PreferenceFragment { final int columnIndex = cursor.getColumnIndex(UserDictionary.Words.LOCALE); do { final String locale = cursor.getString(columnIndex); - final boolean allLocale = TextUtils.isEmpty(locale); - localeList.add(allLocale ? "" : locale); - if (allLocale) { - addedAllLocale = true; - } + localeSet.add(null != locale ? locale : ""); } while (cursor.moveToNext()); } - if (!UserDictionarySettings.IS_SHORTCUT_API_SUPPORTED && !addedAllLocale) { + if (!UserDictionarySettings.IS_SHORTCUT_API_SUPPORTED) { // For ICS, we need to show "For all languages" in case that the keyboard locale // is different from the system locale - localeList.add(""); + localeSet.add(""); + } + + final InputMethodManager imm = + (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE); + final List<InputMethodInfo> imis = imm.getEnabledInputMethodList(); + for (final InputMethodInfo imi : imis) { + final List<InputMethodSubtype> subtypes = + imm.getEnabledInputMethodSubtypeList( + imi, true /* allowsImplicitlySelectedSubtypes */); + for (InputMethodSubtype subtype : subtypes) { + final String locale = subtype.getLocale(); + if (!TextUtils.isEmpty(locale)) { + localeSet.add(locale); + } + } + } + + // We come here after we have collected locales from existing user dictionary entries and + // enabled subtypes. If we already have the locale-without-country version of the system + // locale, we don't add the system locale to avoid confusion even though it's technically + // correct to add it. + if (!localeSet.contains(Locale.getDefault().getLanguage().toString())) { + localeSet.add(Locale.getDefault().toString()); } - localeList.add(Locale.getDefault().toString()); - return localeList; + + return localeSet; } /** @@ -84,13 +107,19 @@ public class UserDictionaryList extends PreferenceFragment { protected void createUserDictSettings(PreferenceGroup userDictGroup) { final Activity activity = getActivity(); userDictGroup.removeAll(); - final TreeSet<String> localeList = + final TreeSet<String> localeSet = UserDictionaryList.getUserDictionaryLocalesSet(activity); - if (localeList.isEmpty()) { + if (localeSet.size() > 1) { + // Have an "All languages" entry in the languages list if there are two or more active + // languages + localeSet.add(""); + } + + if (localeSet.isEmpty()) { userDictGroup.addPreference(createUserDictionaryPreference(null, activity)); } else { - for (String locale : localeList) { + for (String locale : localeSet) { userDictGroup.addPreference(createUserDictionaryPreference(locale, activity)); } } diff --git a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java index 50dda9663..7571e87c5 100644 --- a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java +++ b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettings.java @@ -1,17 +1,17 @@ -/** - * Copyright (C) 2013 Google Inc. +/* + * Copyright (C) 2013 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy - * of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package com.android.inputmethod.latin.userdictionary; @@ -150,7 +150,9 @@ public class UserDictionarySettings extends ListFragment { listView.setEmptyView(emptyView); setHasOptionsMenu(true); - + // Show the language as a subtitle of the action bar + getActivity().getActionBar().setSubtitle( + UserDictionarySettingsUtils.getLocaleDisplayName(getActivity(), mLocale)); } @SuppressWarnings("deprecation") diff --git a/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettingsUtils.java b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettingsUtils.java new file mode 100644 index 000000000..e58727ec4 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/userdictionary/UserDictionarySettingsUtils.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.userdictionary; + +import com.android.inputmethod.latin.R; +import com.android.inputmethod.latin.utils.LocaleUtils; + +import android.content.Context; +import android.text.TextUtils; + +import java.util.Locale; + +/** + * Utilities of the user dictionary settings + * TODO: We really want to move these utilities to a static library. + */ +public class UserDictionarySettingsUtils { + public static String getLocaleDisplayName(Context context, String localeStr) { + if (TextUtils.isEmpty(localeStr)) { + // CAVEAT: localeStr should not be null because a null locale stands for the system + // locale in UserDictionary.Words.addWord. + return context.getResources().getString(R.string.user_dict_settings_all_languages); + } + final Locale locale = LocaleUtils.constructLocaleFromString(localeStr); + final Locale systemLocale = context.getResources().getConfiguration().locale; + return locale.getDisplayName(systemLocale); + } +} diff --git a/java/src/com/android/inputmethod/latin/AdditionalSubtype.java b/java/src/com/android/inputmethod/latin/utils/AdditionalSubtypeUtils.java index 99b95ea98..215faa0c7 100644 --- a/java/src/com/android/inputmethod/latin/AdditionalSubtype.java +++ b/java/src/com/android/inputmethod/latin/utils/AdditionalSubtypeUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import static com.android.inputmethod.latin.Constants.Subtype.KEYBOARD_MODE; import static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.IS_ADDITIONAL_SUBTYPE; @@ -25,12 +25,14 @@ import android.os.Build; import android.text.TextUtils; import android.view.inputmethod.InputMethodSubtype; +import com.android.inputmethod.latin.R; + import java.util.ArrayList; -public final class AdditionalSubtype { +public final class AdditionalSubtypeUtils { private static final InputMethodSubtype[] EMPTY_SUBTYPE_ARRAY = new InputMethodSubtype[0]; - private AdditionalSubtype() { + private AdditionalSubtypeUtils() { // This utility class is not publicly instantiable. } @@ -46,17 +48,18 @@ public final class AdditionalSubtype { final String layoutExtraValue = KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName; final String layoutDisplayNameExtraValue; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN - && SubtypeLocale.isExceptionalLocale(localeString)) { - final String layoutDisplayName = SubtypeLocale.getKeyboardLayoutSetDisplayName( + && SubtypeLocaleUtils.isExceptionalLocale(localeString)) { + final String layoutDisplayName = SubtypeLocaleUtils.getKeyboardLayoutSetDisplayName( keyboardLayoutSetName); - layoutDisplayNameExtraValue = StringUtils.appendToCsvIfNotExists( + layoutDisplayNameExtraValue = StringUtils.appendToCommaSplittableTextIfNotExists( UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME + "=" + layoutDisplayName, extraValue); } else { layoutDisplayNameExtraValue = extraValue; } - final String additionalSubtypeExtraValue = StringUtils.appendToCsvIfNotExists( - IS_ADDITIONAL_SUBTYPE, layoutDisplayNameExtraValue); - final int nameId = SubtypeLocale.getSubtypeNameId(localeString, keyboardLayoutSetName); + final String additionalSubtypeExtraValue = + StringUtils.appendToCommaSplittableTextIfNotExists( + IS_ADDITIONAL_SUBTYPE, layoutDisplayNameExtraValue); + final int nameId = SubtypeLocaleUtils.getSubtypeNameId(localeString, keyboardLayoutSetName); return new InputMethodSubtype(nameId, R.drawable.ic_subtype_keyboard, localeString, KEYBOARD_MODE, layoutExtraValue + "," + additionalSubtypeExtraValue, false, false); @@ -64,10 +67,11 @@ public final class AdditionalSubtype { public static String getPrefSubtype(final InputMethodSubtype subtype) { final String localeString = subtype.getLocale(); - final String keyboardLayoutSetName = SubtypeLocale.getKeyboardLayoutSetName(subtype); + final String keyboardLayoutSetName = SubtypeLocaleUtils.getKeyboardLayoutSetName(subtype); final String layoutExtraValue = KEYBOARD_LAYOUT_SET + "=" + keyboardLayoutSetName; - final String extraValue = StringUtils.removeFromCsvIfExists(layoutExtraValue, - StringUtils.removeFromCsvIfExists(IS_ADDITIONAL_SUBTYPE, subtype.getExtraValue())); + final String extraValue = StringUtils.removeFromCommaSplittableTextIfExists( + layoutExtraValue, StringUtils.removeFromCommaSplittableTextIfExists( + IS_ADDITIONAL_SUBTYPE, subtype.getExtraValue())); final String basePrefSubtype = localeString + LOCALE_AND_LAYOUT_SEPARATOR + keyboardLayoutSetName; return extraValue.isEmpty() ? basePrefSubtype @@ -94,7 +98,7 @@ public final class AdditionalSubtype { CollectionUtils.newArrayList(prefSubtypeArray.length); for (final String prefSubtype : prefSubtypeArray) { final InputMethodSubtype subtype = createAdditionalSubtype(prefSubtype); - if (subtype.getNameResId() == SubtypeLocale.UNKNOWN_KEYBOARD_LAYOUT) { + if (subtype.getNameResId() == SubtypeLocaleUtils.UNKNOWN_KEYBOARD_LAYOUT) { // Skip unknown keyboard layout subtype. This may happen when predefined keyboard // layout has been removed. continue; diff --git a/java/src/com/android/inputmethod/latin/utils/ApplicationUtils.java b/java/src/com/android/inputmethod/latin/utils/ApplicationUtils.java new file mode 100644 index 000000000..08a2a8c5a --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/ApplicationUtils.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.app.Activity; +import android.content.ComponentName; +import android.content.Context; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager.NameNotFoundException; +import android.util.Log; + +public final class ApplicationUtils { + private static final String TAG = ApplicationUtils.class.getSimpleName(); + + private ApplicationUtils() { + // This utility class is not publicly instantiable. + } + + public static int getAcitivityTitleResId(final Context context, + final Class<? extends Activity> cls) { + final ComponentName cn = new ComponentName(context, cls); + try { + final ActivityInfo ai = context.getPackageManager().getActivityInfo(cn, 0); + if (ai != null) { + return ai.labelRes; + } + } catch (final NameNotFoundException e) { + Log.e(TAG, "Failed to get settings activity title res id.", e); + } + return 0; + } + + /** + * A utility method to get the application's PackageInfo.versionName + * @return the application's PackageInfo.versionName + */ + public static String getVersionName(final Context context) { + try { + if (context == null) { + return ""; + } + final String packageName = context.getPackageName(); + final PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); + return info.versionName; + } catch (final NameNotFoundException e) { + Log.e(TAG, "Could not find version info.", e); + } + return ""; + } +} diff --git a/java/src/com/android/inputmethod/latin/AutoCorrection.java b/java/src/com/android/inputmethod/latin/utils/AutoCorrectionUtils.java index fa35922b0..066c5fd32 100644 --- a/java/src/com/android/inputmethod/latin/AutoCorrection.java +++ b/java/src/com/android/inputmethod/latin/utils/AutoCorrectionUtils.java @@ -14,8 +14,12 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; +import com.android.inputmethod.latin.BinaryDictionary; +import com.android.inputmethod.latin.Dictionary; +import com.android.inputmethod.latin.LatinImeLogger; +import com.android.inputmethod.latin.Suggest; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; import android.text.TextUtils; @@ -23,21 +27,22 @@ import android.util.Log; import java.util.concurrent.ConcurrentHashMap; -public final class AutoCorrection { +public final class AutoCorrectionUtils { private static final boolean DBG = LatinImeLogger.sDBG; - private static final String TAG = AutoCorrection.class.getSimpleName(); + private static final String TAG = AutoCorrectionUtils.class.getSimpleName(); private static final int MINIMUM_SAFETY_NET_CHAR_LENGTH = 4; - private AutoCorrection() { + private AutoCorrectionUtils() { // Purely static class: can't instantiate. } - public static boolean isValidWord(final ConcurrentHashMap<String, Dictionary> dictionaries, - final String word, final boolean ignoreCase) { + public static boolean isValidWord(final Suggest suggest, final String word, + final boolean ignoreCase) { if (TextUtils.isEmpty(word)) { return false; } - final String lowerCasedWord = word.toLowerCase(); + final ConcurrentHashMap<String, Dictionary> dictionaries = suggest.getUnigramDictionaries(); + final String lowerCasedWord = word.toLowerCase(suggest.mLocale); for (final String key : dictionaries.keySet()) { final Dictionary dictionary = dictionaries.get(key); // It's unclear how realistically 'dictionary' can be null, but the monkey is somehow @@ -73,13 +78,6 @@ public final class AutoCorrection { return maxFreq; } - // Returns true if this is in any of the dictionaries. - public static boolean isInTheDictionary( - final ConcurrentHashMap<String, Dictionary> dictionaries, - final String word, final boolean ignoreCase) { - return isValidWord(dictionaries, word, ignoreCase); - } - public static boolean suggestionExceedsAutoCorrectionThreshold( final SuggestedWordInfo suggestion, final String consideredWord, final float autoCorrectionThreshold) { diff --git a/java/src/com/android/inputmethod/latin/utils/Base64Reader.java b/java/src/com/android/inputmethod/latin/utils/Base64Reader.java new file mode 100644 index 000000000..3eca6e744 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/Base64Reader.java @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import com.android.inputmethod.annotations.UsedForTesting; + +import java.io.EOFException; +import java.io.IOException; +import java.io.LineNumberReader; + +@UsedForTesting +public class Base64Reader { + private final LineNumberReader mReader; + + private String mLine; + private int mCharPos; + private int mByteCount; + + @UsedForTesting + public Base64Reader(final LineNumberReader reader) { + mReader = reader; + reset(); + } + + @UsedForTesting + public void reset() { + mLine = null; + mCharPos = 0; + mByteCount = 0; + } + + @UsedForTesting + public int getLineNumber() { + return mReader.getLineNumber(); + } + + @UsedForTesting + public int getByteCount() { + return mByteCount; + } + + private void fillBuffer() throws IOException { + if (mLine == null || mCharPos >= mLine.length()) { + mLine = mReader.readLine(); + mCharPos = 0; + } + if (mLine == null) { + throw new EOFException(); + } + } + + private int peekUint8() throws IOException { + fillBuffer(); + final char c = mLine.charAt(mCharPos); + if (c >= 'A' && c <= 'Z') + return c - 'A' + 0; + if (c >= 'a' && c <= 'z') + return c - 'a' + 26; + if (c >= '0' && c <= '9') + return c - '0' + 52; + if (c == '+') + return 62; + if (c == '/') + return 63; + if (c == '=') + return 0; + throw new RuntimeException("Unknown character '" + c + "' in base64 at line " + + mReader.getLineNumber()); + } + + private int getUint8() throws IOException { + final int value = peekUint8(); + mCharPos++; + return value; + } + + @UsedForTesting + public int readUint8() throws IOException { + final int value1, value2; + switch (mByteCount % 3) { + case 0: + value1 = getUint8() << 2; + value2 = value1 | (peekUint8() >> 4); + break; + case 1: + value1 = (getUint8() & 0x0f) << 4; + value2 = value1 | (peekUint8() >> 2); + break; + default: + value1 = (getUint8() & 0x03) << 6; + value2 = value1 | getUint8(); + break; + } + mByteCount++; + return value2; + } + + @UsedForTesting + public short readInt16() throws IOException { + final int data = readUint8() << 8; + return (short)(data | readUint8()); + } +} diff --git a/java/src/com/android/inputmethod/latin/BoundedTreeSet.java b/java/src/com/android/inputmethod/latin/utils/BoundedTreeSet.java index 489a74ef1..ae1fd3f79 100644 --- a/java/src/com/android/inputmethod/latin/BoundedTreeSet.java +++ b/java/src/com/android/inputmethod/latin/utils/BoundedTreeSet.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; diff --git a/java/src/com/android/inputmethod/latin/utils/ByteArrayWrapper.java b/java/src/com/android/inputmethod/latin/utils/ByteArrayWrapper.java new file mode 100644 index 000000000..1bb27aa2b --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/ByteArrayWrapper.java @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import com.android.inputmethod.latin.makedict.BinaryDictInputOutput.FusionDictionaryBufferInterface; + +/** + * This class provides an implementation for the FusionDictionary buffer interface that is backed + * by a simpled byte array. It allows to create a binary dictionary in memory. + */ +public final class ByteArrayWrapper implements FusionDictionaryBufferInterface { + private byte[] mBuffer; + private int mPosition; + + public ByteArrayWrapper(final byte[] buffer) { + mBuffer = buffer; + mPosition = 0; + } + + @Override + public int readUnsignedByte() { + return mBuffer[mPosition++] & 0xFF; + } + + @Override + public int readUnsignedShort() { + final int retval = readUnsignedByte(); + return (retval << 8) + readUnsignedByte(); + } + + @Override + public int readUnsignedInt24() { + final int retval = readUnsignedShort(); + return (retval << 8) + readUnsignedByte(); + } + + @Override + public int readInt() { + final int retval = readUnsignedShort(); + return (retval << 16) + readUnsignedShort(); + } + + @Override + public int position() { + return mPosition; + } + + @Override + public void position(int position) { + mPosition = position; + } + + @Override + public void put(final byte b) { + mBuffer[mPosition++] = b; + } + + @Override + public int limit() { + return mBuffer.length - 1; + } + + @Override + public int capacity() { + return mBuffer.length; + } +} diff --git a/java/src/com/android/inputmethod/latin/CapsModeUtils.java b/java/src/com/android/inputmethod/latin/utils/CapsModeUtils.java index 4b8d1ac11..2f91c5743 100644 --- a/java/src/com/android/inputmethod/latin/CapsModeUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/CapsModeUtils.java @@ -14,11 +14,14 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.text.InputType; import android.text.TextUtils; +import com.android.inputmethod.latin.Constants; +import com.android.inputmethod.latin.WordComposer; + import java.util.Locale; public final class CapsModeUtils { diff --git a/java/src/com/android/inputmethod/latin/CollectionUtils.java b/java/src/com/android/inputmethod/latin/utils/CollectionUtils.java index a8623cc63..98f0d8b68 100644 --- a/java/src/com/android/inputmethod/latin/CollectionUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/CollectionUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.util.SparseArray; diff --git a/java/src/com/android/inputmethod/latin/CompletionInfoUtils.java b/java/src/com/android/inputmethod/latin/utils/CompletionInfoUtils.java index 792a446c9..5ccf0e079 100644 --- a/java/src/com/android/inputmethod/latin/CompletionInfoUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/CompletionInfoUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.text.TextUtils; import android.view.inputmethod.CompletionInfo; diff --git a/java/src/com/android/inputmethod/latin/CoordinateUtils.java b/java/src/com/android/inputmethod/latin/utils/CoordinateUtils.java index af270e1e4..72f2cd2d9 100644 --- a/java/src/com/android/inputmethod/latin/CoordinateUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/CoordinateUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; public final class CoordinateUtils { private static final int INDEX_X = 0; diff --git a/java/src/com/android/inputmethod/latin/utils/CsvUtils.java b/java/src/com/android/inputmethod/latin/utils/CsvUtils.java new file mode 100644 index 000000000..36b927eea --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/CsvUtils.java @@ -0,0 +1,318 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import com.android.inputmethod.annotations.UsedForTesting; + +import java.util.ArrayList; + +/** + * Utility methods for parsing and serializing Comma-Separated Values. The public APIs of this + * utility class are {@link #split(String)}, {@link #split(int,String)}, {@link #join(String...)}, + * {@link #join(int,String...)}, and {@link #join(int,int[],String...)}. + * + * This class implements CSV parsing and serializing methods conforming to RFC 4180 with an + * exception: + * These methods can't handle new line code escaped in double quotes. + */ +@UsedForTesting +public final class CsvUtils { + private CsvUtils() { + // This utility class is not publicly instantiable. + } + + public static final int SPLIT_FLAGS_NONE = 0x0; + /** + * A flag for {@link #split(int,String)}. If this flag is specified, the method will trim + * spaces around fields before splitting. Note that this behavior doesn't conform to RFC 4180. + */ + public static final int SPLIT_FLAGS_TRIM_SPACES = 0x1; + + public static final int JOIN_FLAGS_NONE = 0x0; + /** + * A flag for {@link #join(int,String...)} and {@link #join(int,int[],String...)}. If this + * flag is specified, these methods surround each field with double quotes before joining. + */ + public static final int JOIN_FLAGS_ALWAYS_QUOTED = 0x1; + /** + * A flag for {@link #join(int,String...)} and {@link #join(int,int[],String...)}. If this + * flag is specified, these methods add an extra space just after the comma separator. Note that + * this behavior doesn't conform to RFC 4180. + */ + public static final int JOIN_FLAGS_EXTRA_SPACE = 0x2; + + // Note that none of these characters match high or low surrogate characters, so we need not + // take care of matching by code point. + private static final char COMMA = ','; + private static final char SPACE = ' '; + private static final char QUOTE = '"'; + + @SuppressWarnings("serial") + public static class CsvParseException extends RuntimeException { + public CsvParseException(final String message) { + super(message); + } + } + + /** + * Find the first non-space character in the text. + * + * @param text the text to be searched. + * @param fromIndex the index to start the search from, inclusive. + * @return the index of the first occurrence of the non-space character in the + * <code>text</code> that is greater than or equal to <code>fromIndex</code>, or the length of + * the <code>text</code> if the character does not occur. + */ + private static int indexOfNonSpace(final String text, final int fromIndex) { + final int length = text.length(); + if (fromIndex < 0 || fromIndex > length) { + throw new IllegalArgumentException("text=" + text + " fromIndex=" + fromIndex); + } + int index = fromIndex; + while (index < length && text.charAt(index) == SPACE) { + index++; + } + return index; + } + + /** + * Find the last non-space character in the text. + * + * @param text the text to be searched. + * @param fromIndex the index to start the search from, exclusive. + * @param toIndex the index to end the search at, inclusive. Usually <code>toIndex</code> + * points a non-space character. + * @return the index of the last occurrence of the non-space character in the + * <code>text</code>, exclusive. It is less than <code>fromIndex</code> and greater than + * <code>toIndex</code>, or <code>toIndex</code> if the character does not occur. + */ + private static int lastIndexOfNonSpace(final String text, final int fromIndex, + final int toIndex) { + if (toIndex < 0 || fromIndex > text.length() || fromIndex < toIndex) { + throw new IllegalArgumentException( + "text=" + text + " fromIndex=" + fromIndex + " toIndex=" + toIndex); + } + int index = fromIndex; + while (index > toIndex && text.charAt(index - 1) == SPACE) { + index--; + } + return index; + } + + /** + * Find the index of a comma separator. The search takes account of quoted fields and escape + * quotes. + * + * @param text the text to be searched. + * @param fromIndex the index to start the search from, inclusive. + * @return the index of the comma separator, exclusive. + */ + private static int indexOfSeparatorComma(final String text, final int fromIndex) { + final int length = text.length(); + if (fromIndex < 0 || fromIndex > length) { + throw new IllegalArgumentException("text=" + text + " fromIndex=" + fromIndex); + } + final boolean isQuoted = (length - fromIndex > 0 && text.charAt(fromIndex) == QUOTE); + for (int index = fromIndex + (isQuoted ? 1 : 0); index < length; index++) { + final char c = text.charAt(index); + if (c == COMMA && !isQuoted) { + return index; + } + if (c == QUOTE) { + final int nextIndex = index + 1; + if (nextIndex < length && text.charAt(nextIndex) == QUOTE) { + // Quoted quote. + index = nextIndex; + continue; + } + // Closing quote. + final int endIndex = text.indexOf(COMMA, nextIndex); + return endIndex < 0 ? length : endIndex; + } + } + return length; + } + + /** + * Removing any enclosing QUOTEs (U+0022), and convert any two consecutive QUOTEs into + * one QUOTE. + * + * @param text the CSV field text that may have enclosing QUOTEs and escaped QUOTE character. + * @return the text that has been removed enclosing quotes and converted two consecutive QUOTEs + * into one QUOTE. + */ + @UsedForTesting + /* private */ static String unescapeField(final String text) { + StringBuilder sb = null; + final int length = text.length(); + final boolean isQuoted = (length > 0 && text.charAt(0) == QUOTE); + int start = isQuoted ? 1 : 0; + int end = start; + while (start <= length && (end = text.indexOf(QUOTE, start)) >= start) { + final int nextIndex = end + 1; + if (nextIndex == length && isQuoted) { + // Closing quote. + break; + } + if (nextIndex < length && text.charAt(nextIndex) == QUOTE) { + if (!isQuoted) { + throw new CsvParseException("Escaped quote in text"); + } + // Quoted quote. + if (sb == null) { + sb = new StringBuilder(); + } + sb.append(text.substring(start, nextIndex)); + start = nextIndex + 1; + } else { + throw new CsvParseException( + isQuoted ? "Raw quote in quoted text" : "Raw quote in text"); + } + } + if (end < 0 && isQuoted) { + throw new CsvParseException("Unterminated quote"); + } + if (end < 0) { + end = length; + } + if (sb != null && start < length) { + sb.append(text.substring(start, end)); + } + return sb == null ? text.substring(start, end) : sb.toString(); + } + + /** + * Split the CSV text into fields. The leading and trailing spaces of the each field can be + * trimmed optionally. + * + * @param splitFlags flags for split behavior. {@link #SPLIT_FLAGS_TRIM_SPACES} will trim + * spaces around each fields. + * @param line the text of CSV fields. + * @return the array of unescaped CVS fields. + * @throws CsvParseException + */ + @UsedForTesting + public static String[] split(final int splitFlags, final String line) throws CsvParseException { + final boolean trimSpaces = (splitFlags & SPLIT_FLAGS_TRIM_SPACES) != 0; + final ArrayList<String> fields = CollectionUtils.newArrayList(); + final int length = line.length(); + int start = 0; + do { + final int csvStart = trimSpaces ? indexOfNonSpace(line, start) : start; + final int end = indexOfSeparatorComma(line, csvStart); + final int csvEnd = trimSpaces ? lastIndexOfNonSpace(line, end, csvStart) : end; + final String csvText = unescapeField(line.substring(csvStart, csvEnd)); + fields.add(csvText); + start = end + 1; + } while (start <= length); + return fields.toArray(new String[fields.size()]); + } + + @UsedForTesting + public static String[] split(final String line) throws CsvParseException { + return split(SPLIT_FLAGS_NONE, line); + } + + /** + * Convert the raw CSV field text to the escaped text. It adds enclosing QUOTEs (U+0022) if the + * raw value contains any QUOTE or comma. Also it converts any QUOTE character into two + * consecutive QUOTE characters. + * + * @param text the raw CSV field text to be escaped. + * @param alwaysQuoted true if the escaped text should always be enclosed by QUOTEs. + * @return the escaped text. + */ + @UsedForTesting + /* private */ static String escapeField(final String text, final boolean alwaysQuoted) { + StringBuilder sb = null; + boolean needsQuoted = alwaysQuoted; + final int length = text.length(); + int indexToBeAppended = 0; + for (int index = indexToBeAppended; index < length; index++) { + final char c = text.charAt(index); + if (c == COMMA) { + needsQuoted = true; + } else if (c == QUOTE) { + needsQuoted = true; + if (sb == null) { + sb = new StringBuilder(); + } + sb.append(text.substring(indexToBeAppended, index)); + indexToBeAppended = index + 1; + sb.append(QUOTE); // escaping quote. + sb.append(QUOTE); // escaped quote. + } + } + if (sb != null && indexToBeAppended < length) { + sb.append(text.substring(indexToBeAppended)); + } + final String escapedText = (sb == null) ? text : sb.toString(); + return needsQuoted ? QUOTE + escapedText + QUOTE : escapedText; + } + + private static final String SPACES = " "; + + private static void padToColumn(final StringBuilder sb, final int column) { + int padding; + while ((padding = column - sb.length()) > 0) { + final String spaces = SPACES.substring(0, Math.min(padding, SPACES.length())); + sb.append(spaces); + } + } + + /** + * Join CSV text fields with comma. The column positions of the fields can be specified + * optionally. Surround each fields with double quotes before joining. + * + * @param joinFlags flags for join behavior. {@link #JOIN_FLAGS_EXTRA_SPACE} will add an extra + * space after each comma separator. {@link #JOIN_FLAGS_ALWAYS_QUOTED} will always add + * surrounding quotes to each element. + * @param columnPositions the array of column positions of the fields. It can be shorter than + * <code>fields</code> or null. Note that specifying the array column positions of the fields + * doesn't conform to RFC 4180. + * @param fields the CSV text fields. + * @return the string of the joined and escaped <code>fields</code>. + */ + @UsedForTesting + public static String join(final int joinFlags, final int columnPositions[], + final String... fields) { + final boolean alwaysQuoted = (joinFlags & JOIN_FLAGS_ALWAYS_QUOTED) != 0; + final String separator = COMMA + ((joinFlags & JOIN_FLAGS_EXTRA_SPACE) != 0 ? " " : ""); + final StringBuilder sb = new StringBuilder(); + for (int index = 0; index < fields.length; index++) { + if (index > 0) { + sb.append(separator); + } + if (columnPositions != null && index < columnPositions.length) { + padToColumn(sb, columnPositions[index]); + } + final String escapedText = escapeField(fields[index], alwaysQuoted); + sb.append(escapedText); + } + return sb.toString(); + } + + @UsedForTesting + public static String join(final int joinFlags, final String... fields) { + return join(joinFlags, null, fields); + } + + @UsedForTesting + public static String join(final String... fields) { + return join(JOIN_FLAGS_NONE, null, fields); + } +} diff --git a/java/src/com/android/inputmethod/latin/utils/DebugLogUtils.java b/java/src/com/android/inputmethod/latin/utils/DebugLogUtils.java new file mode 100644 index 000000000..c4ead0ad1 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/DebugLogUtils.java @@ -0,0 +1,115 @@ +/* + * 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.utils; + +import android.util.Log; + +import com.android.inputmethod.latin.LatinImeLogger; + +/** + * A class for logging and debugging utility methods. + */ +public final class DebugLogUtils { + private final static String TAG = DebugLogUtils.class.getSimpleName(); + private final static boolean sDBG = LatinImeLogger.sDBG; + + /** + * Calls .toString() on its non-null argument or returns "null" + * @param o the object to convert to a string + * @return the result of .toString() or null + */ + public static String s(final Object o) { + return null == o ? "null" : o.toString(); + } + + /** + * Get the string representation of the current stack trace, for debugging purposes. + * @return a readable, carriage-return-separated string for the current stack trace. + */ + public static String getStackTrace() { + return getStackTrace(Integer.MAX_VALUE - 1); + } + + /** + * Get the string representation of the current stack trace, for debugging purposes. + * @param limit the maximum number of stack frames to be returned. + * @return a readable, carriage-return-separated string for the current stack trace. + */ + public static String getStackTrace(final int limit) { + final StringBuilder sb = new StringBuilder(); + try { + throw new RuntimeException(); + } catch (final RuntimeException e) { + final StackTraceElement[] frames = e.getStackTrace(); + // Start at 1 because the first frame is here and we don't care about it + for (int j = 1; j < frames.length && j < limit + 1; ++j) { + sb.append(frames[j].toString() + "\n"); + } + } + return sb.toString(); + } + + /** + * Get the stack trace contained in an exception as a human-readable string. + * @param e the exception + * @return the human-readable stack trace + */ + public static String getStackTrace(final Exception e) { + final StringBuilder sb = new StringBuilder(); + final StackTraceElement[] frames = e.getStackTrace(); + for (int j = 0; j < frames.length; ++j) { + sb.append(frames[j].toString() + "\n"); + } + return sb.toString(); + } + + /** + * Helper log method to ease null-checks and adding spaces. + * + * This sends all arguments to the log, separated by spaces. Any null argument is converted + * to the "null" string. It uses a very visible tag and log level for debugging purposes. + * + * @param args the stuff to send to the log + */ + public static void l(final Object... args) { + if (!sDBG) return; + final StringBuilder sb = new StringBuilder(); + for (final Object o : args) { + sb.append(s(o).toString()); + sb.append(" "); + } + Log.e(TAG, sb.toString()); + } + + /** + * Helper log method to put stuff in red. + * + * This does the same as #l but prints in red + * + * @param args the stuff to send to the log + */ + public static void r(final Object... args) { + if (!sDBG) return; + final StringBuilder sb = new StringBuilder("\u001B[31m"); + for (final Object o : args) { + sb.append(s(o).toString()); + sb.append(" "); + } + sb.append("\u001B[0m"); + Log.e(TAG, sb.toString()); + } +} diff --git a/java/src/com/android/inputmethod/latin/DictionaryInfoUtils.java b/java/src/com/android/inputmethod/latin/utils/DictionaryInfoUtils.java index df7bad8d0..34eccd65b 100644 --- a/java/src/com/android/inputmethod/latin/DictionaryInfoUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/DictionaryInfoUtils.java @@ -14,15 +14,17 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.content.ContentValues; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Resources; -import android.text.format.DateUtils; import android.util.Log; +import com.android.inputmethod.latin.AssetFileAddress; +import com.android.inputmethod.latin.BinaryDictionaryGetter; +import com.android.inputmethod.latin.R; import com.android.inputmethod.latin.makedict.BinaryDictIOUtils; import com.android.inputmethod.latin.makedict.FormatSpec.FileHeader; import com.android.inputmethod.latin.makedict.UnsupportedFormatException; @@ -30,16 +32,16 @@ import com.android.inputmethod.latin.makedict.UnsupportedFormatException; import java.io.File; import java.io.IOException; import java.util.ArrayList; +import java.util.Iterator; import java.util.Locale; +import java.util.concurrent.TimeUnit; /** * This class encapsulates the logic for the Latin-IME side of dictionary information management. */ public class DictionaryInfoUtils { private static final String TAG = DictionaryInfoUtils.class.getSimpleName(); - // This class must be located in the same package as LatinIME.java. - private static final String RESOURCE_PACKAGE_NAME = - DictionaryInfoUtils.class.getPackage().getName(); + private static final String RESOURCE_PACKAGE_NAME = R.class.getPackage().getName(); private static final String DEFAULT_MAIN_DICT = "main"; private static final String MAIN_DICT_PREFIX = "main_"; // 6 digits - unicode is limited to 21 bits @@ -72,8 +74,8 @@ public class DictionaryInfoUtils { values.put(LOCALE_COLUMN, mLocale.toString()); values.put(DESCRIPTION_COLUMN, mDescription); values.put(LOCAL_FILENAME_COLUMN, mFileAddress.mFilename); - values.put(DATE_COLUMN, - new File(mFileAddress.mFilename).lastModified() / DateUtils.SECOND_IN_MILLIS); + values.put(DATE_COLUMN, TimeUnit.MILLISECONDS.toSeconds( + new File(mFileAddress.mFilename).lastModified())); values.put(FILESIZE_COLUMN, mFileAddress.mLength); values.put(VERSION_COLUMN, mVersion); return values; @@ -301,12 +303,14 @@ public class DictionaryInfoUtils { private static void addOrUpdateDictInfo(final ArrayList<DictionaryInfo> dictList, final DictionaryInfo newElement) { - for (final DictionaryInfo info : dictList) { - if (info.mLocale.equals(newElement.mLocale)) { - if (newElement.mVersion <= info.mVersion) { + final Iterator<DictionaryInfo> iter = dictList.iterator(); + while (iter.hasNext()) { + final DictionaryInfo thisDictInfo = iter.next(); + if (thisDictInfo.mLocale.equals(newElement.mLocale)) { + if (newElement.mVersion <= thisDictInfo.mVersion) { return; } - dictList.remove(info); + iter.remove(); } } dictList.add(newElement); diff --git a/java/src/com/android/inputmethod/latin/FeedbackUtils.java b/java/src/com/android/inputmethod/latin/utils/FeedbackUtils.java index 0582763fe..ec7eaf4a0 100644 --- a/java/src/com/android/inputmethod/latin/FeedbackUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/FeedbackUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.content.Context; import android.content.Intent; diff --git a/java/src/com/android/inputmethod/latin/FileTransforms.java b/java/src/com/android/inputmethod/latin/utils/FileTransforms.java index 692f3c7c1..9f4584ec9 100644 --- a/java/src/com/android/inputmethod/latin/FileTransforms.java +++ b/java/src/com/android/inputmethod/latin/utils/FileTransforms.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import java.io.IOException; import java.io.InputStream; diff --git a/java/src/com/android/inputmethod/latin/InputTypeUtils.java b/java/src/com/android/inputmethod/latin/utils/InputTypeUtils.java index 46194f6e4..19cd34011 100644 --- a/java/src/com/android/inputmethod/latin/InputTypeUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/InputTypeUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.text.InputType; import android.view.inputmethod.EditorInfo; diff --git a/java/src/com/android/inputmethod/latin/IntentUtils.java b/java/src/com/android/inputmethod/latin/utils/IntentUtils.java index d175af504..ea0168117 100644 --- a/java/src/com/android/inputmethod/latin/IntentUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/IntentUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.content.Intent; import android.text.TextUtils; diff --git a/java/src/com/android/inputmethod/latin/JniUtils.java b/java/src/com/android/inputmethod/latin/utils/JniUtils.java index 8aedee576..e7fdafaeb 100644 --- a/java/src/com/android/inputmethod/latin/JniUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/JniUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.util.Log; diff --git a/java/src/com/android/inputmethod/latin/utils/LatinImeLoggerUtils.java b/java/src/com/android/inputmethod/latin/utils/LatinImeLoggerUtils.java new file mode 100644 index 000000000..e958a7e71 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/LatinImeLoggerUtils.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.text.TextUtils; + +import com.android.inputmethod.latin.Constants; +import com.android.inputmethod.latin.LatinImeLogger; +import com.android.inputmethod.latin.WordComposer; + +public final class LatinImeLoggerUtils { + private LatinImeLoggerUtils() { + // This utility class is not publicly instantiable. + } + + public static void onNonSeparator(final char code, final int x, final int y) { + UserLogRingCharBuffer.getInstance().push(code, x, y); + LatinImeLogger.logOnInputChar(); + } + + public static void onSeparator(final int code, final int x, final int y) { + // Helper method to log a single code point separator + // TODO: cache this mapping of a code point to a string in a sparse array in StringUtils + onSeparator(new String(new int[]{code}, 0, 1), x, y); + } + + public static void onSeparator(final String separator, final int x, final int y) { + final int length = separator.length(); + for (int i = 0; i < length; i = Character.offsetByCodePoints(separator, i, 1)) { + int codePoint = Character.codePointAt(separator, i); + // TODO: accept code points + UserLogRingCharBuffer.getInstance().push((char)codePoint, x, y); + } + LatinImeLogger.logOnInputSeparator(); + } + + public static void onAutoCorrection(final String typedWord, final String correctedWord, + final String separatorString, final WordComposer wordComposer) { + final boolean isBatchMode = wordComposer.isBatchMode(); + if (!isBatchMode && TextUtils.isEmpty(typedWord)) { + return; + } + // TODO: this fails when the separator is more than 1 code point long, but + // the backend can't handle it yet. The only case when this happens is with + // smileys and other multi-character keys. + final int codePoint = TextUtils.isEmpty(separatorString) ? Constants.NOT_A_CODE + : separatorString.codePointAt(0); + if (!isBatchMode) { + LatinImeLogger.logOnAutoCorrectionForTyping(typedWord, correctedWord, codePoint); + } else { + if (!TextUtils.isEmpty(correctedWord)) { + // We must make sure that InputPointer contains only the relative timestamps, + // not actual timestamps. + LatinImeLogger.logOnAutoCorrectionForGeometric( + "", correctedWord, codePoint, wordComposer.getInputPointers()); + } + } + } + + public static void onAutoCorrectionCancellation() { + LatinImeLogger.logOnAutoCorrectionCancelled(); + } +} diff --git a/java/src/com/android/inputmethod/latin/LocaleUtils.java b/java/src/com/android/inputmethod/latin/utils/LocaleUtils.java index 5fde8158a..22045aa38 100644 --- a/java/src/com/android/inputmethod/latin/LocaleUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/LocaleUtils.java @@ -14,10 +14,8 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; -import android.content.res.Configuration; -import android.content.res.Resources; import android.text.TextUtils; import java.util.HashMap; @@ -148,7 +146,7 @@ public final class LocaleUtils { public static String getMatchLevelSortedString(int matchLevel) { // This works because the match levels are 0~99 (actually 0~30) // Ideally this should use a number of digits equals to the 1og10 of the greater matchLevel - return String.format("%02d", MATCH_LEVEL_MAX - matchLevel); + return String.format(Locale.ROOT, "%02d", MATCH_LEVEL_MAX - matchLevel); } /** @@ -164,39 +162,6 @@ public final class LocaleUtils { return LOCALE_MATCH <= level; } - static final Object sLockForRunInLocale = new Object(); - - public abstract static class RunInLocale<T> { - protected abstract T job(Resources res); - - /** - * Execute {@link #job(Resources)} method in specified system locale exclusively. - * - * @param res the resources to use. Pass current resources. - * @param newLocale the locale to change to - * @return the value returned from {@link #job(Resources)}. - */ - public T runInLocale(final Resources res, final Locale newLocale) { - synchronized (sLockForRunInLocale) { - final Configuration conf = res.getConfiguration(); - final Locale oldLocale = conf.locale; - final boolean needsChange = (newLocale != null && !newLocale.equals(oldLocale)); - try { - if (needsChange) { - conf.locale = newLocale; - res.updateConfiguration(conf, null); - } - return job(res); - } finally { - if (needsChange) { - conf.locale = oldLocale; - res.updateConfiguration(conf, null); - } - } - } - } - } - private static final HashMap<String, Locale> sLocaleCache = CollectionUtils.newHashMap(); /** diff --git a/java/src/com/android/inputmethod/latin/MetadataFileUriGetter.java b/java/src/com/android/inputmethod/latin/utils/MetadataFileUriGetter.java index a98ecc7b6..9ad319da6 100644 --- a/java/src/com/android/inputmethod/latin/MetadataFileUriGetter.java +++ b/java/src/com/android/inputmethod/latin/utils/MetadataFileUriGetter.java @@ -14,7 +14,9 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; + +import com.android.inputmethod.latin.R; import android.content.Context; diff --git a/java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java b/java/src/com/android/inputmethod/latin/utils/PositionalInfoForUserDictPendingAddition.java index a8800007a..1fc7eccc6 100644 --- a/java/src/com/android/inputmethod/latin/PositionalInfoForUserDictPendingAddition.java +++ b/java/src/com/android/inputmethod/latin/utils/PositionalInfoForUserDictPendingAddition.java @@ -14,10 +14,12 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.view.inputmethod.EditorInfo; +import com.android.inputmethod.latin.RichInputConnection; + import java.util.Locale; /** diff --git a/java/src/com/android/inputmethod/latin/RecapitalizeStatus.java b/java/src/com/android/inputmethod/latin/utils/RecapitalizeStatus.java index 8a704ab42..0f5cd80db 100644 --- a/java/src/com/android/inputmethod/latin/RecapitalizeStatus.java +++ b/java/src/com/android/inputmethod/latin/utils/RecapitalizeStatus.java @@ -14,9 +14,7 @@ * the License. */ -package com.android.inputmethod.latin; - -import com.android.inputmethod.latin.StringUtils; +package com.android.inputmethod.latin.utils; import java.util.Locale; @@ -163,7 +161,10 @@ public class RecapitalizeStatus { final int codePoint = mStringBefore.codePointBefore(nonWhitespaceEnd); if (!Character.isWhitespace(codePoint)) break; } - if (0 != nonWhitespaceStart || len != nonWhitespaceEnd) { + // If nonWhitespaceStart >= nonWhitespaceEnd, that means the selection contained only + // whitespace, so we leave it as is. + if ((0 != nonWhitespaceStart || len != nonWhitespaceEnd) + && nonWhitespaceStart < nonWhitespaceEnd) { mCursorEndAfter = mCursorStartBefore + nonWhitespaceEnd; mCursorStartBefore = mCursorStartAfter = mCursorStartBefore + nonWhitespaceStart; mStringAfter = mStringBefore = diff --git a/java/src/com/android/inputmethod/latin/ResizableIntArray.java b/java/src/com/android/inputmethod/latin/utils/ResizableIntArray.java index 691f0602a..4c7739a7a 100644 --- a/java/src/com/android/inputmethod/latin/ResizableIntArray.java +++ b/java/src/com/android/inputmethod/latin/utils/ResizableIntArray.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import java.util.Arrays; diff --git a/java/src/com/android/inputmethod/latin/ResourceUtils.java b/java/src/com/android/inputmethod/latin/utils/ResourceUtils.java index a9fba5348..ffec57548 100644 --- a/java/src/com/android/inputmethod/latin/ResourceUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/ResourceUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.content.res.Resources; import android.content.res.TypedArray; @@ -27,6 +27,7 @@ import com.android.inputmethod.annotations.UsedForTesting; import java.util.ArrayList; import java.util.HashMap; +import java.util.regex.PatternSyntaxException; public final class ResourceUtils { private static final String TAG = ResourceUtils.class.getSimpleName(); @@ -83,22 +84,39 @@ public final class ResourceUtils { return overrideValue; } - final String defaultValue = findDefaultConstant(overrideArray); - // The defaultValue might be an empty string. - if (defaultValue == null) { - Log.w(TAG, "Couldn't find override value nor default value:" - + " resource="+ res.getResourceEntryName(overrideResId) - + " build=" + sBuildKeyValuesDebugString); - } else { - Log.i(TAG, "Found default value:" - + " resource="+ res.getResourceEntryName(overrideResId) - + " build=" + sBuildKeyValuesDebugString - + " default=" + defaultValue); + String defaultValue = null; + try { + defaultValue = findDefaultConstant(overrideArray); + // The defaultValue might be an empty string. + if (defaultValue == null) { + Log.w(TAG, "Couldn't find override value nor default value:" + + " resource="+ res.getResourceEntryName(overrideResId) + + " build=" + sBuildKeyValuesDebugString); + } else { + Log.i(TAG, "Found default value:" + + " resource="+ res.getResourceEntryName(overrideResId) + + " build=" + sBuildKeyValuesDebugString + + " default=" + defaultValue); + } + } catch (final DeviceOverridePatternSyntaxError e) { + Log.w(TAG, "Syntax error, ignored", e); } sDeviceOverrideValueMap.put(key, defaultValue); return defaultValue; } + @SuppressWarnings("serial") + static class DeviceOverridePatternSyntaxError extends Exception { + public DeviceOverridePatternSyntaxError(final String message, final String expression) { + this(message, expression, null); + } + + public DeviceOverridePatternSyntaxError(final String message, final String expression, + final Throwable throwable) { + super(message + ": " + expression, throwable); + } + } + /** * Find the condition that fulfills specified key value pairs from an array of * "condition,constant", and return the corresponding string constant. A condition is @@ -123,10 +141,12 @@ public final class ResourceUtils { if (conditionConstantArray == null || keyValuePairs == null) { return null; } + String foundValue = null; for (final String conditionConstant : conditionConstantArray) { final int posComma = conditionConstant.indexOf(','); if (posComma < 0) { - throw new RuntimeException("Array element has no comma: " + conditionConstant); + Log.w(TAG, "Array element has no comma: " + conditionConstant); + continue; } final String condition = conditionConstant.substring(0, posComma); if (condition.isEmpty()) { @@ -134,44 +154,59 @@ public final class ResourceUtils { // {@link #findConstantForDefault(String[])}. continue; } - if (fulfillsCondition(keyValuePairs, condition)) { - return conditionConstant.substring(posComma + 1); + try { + if (fulfillsCondition(keyValuePairs, condition)) { + // Take first match + if (foundValue == null) { + foundValue = conditionConstant.substring(posComma + 1); + } + // And continue walking through all conditions. + } + } catch (final DeviceOverridePatternSyntaxError e) { + Log.w(TAG, "Syntax error, ignored", e); } } - return null; + return foundValue; } private static boolean fulfillsCondition(final HashMap<String,String> keyValuePairs, - final String condition) { + final String condition) throws DeviceOverridePatternSyntaxError { final String[] patterns = condition.split(":"); // Check all patterns in a condition are true + boolean matchedAll = true; for (final String pattern : patterns) { final int posEqual = pattern.indexOf('='); if (posEqual < 0) { - throw new RuntimeException("Pattern has no '=': " + condition); + throw new DeviceOverridePatternSyntaxError("Pattern has no '='", condition); } final String key = pattern.substring(0, posEqual); final String value = keyValuePairs.get(key); if (value == null) { - throw new RuntimeException("Found unknown key: " + condition); + throw new DeviceOverridePatternSyntaxError("Unknown key", condition); } final String patternRegexpValue = pattern.substring(posEqual + 1); - if (!value.matches(patternRegexpValue)) { - return false; + try { + if (!value.matches(patternRegexpValue)) { + matchedAll = false; + // And continue walking through all patterns. + } + } catch (final PatternSyntaxException e) { + throw new DeviceOverridePatternSyntaxError("Syntax error", condition, e); } } - return true; + return matchedAll; } @UsedForTesting - static String findDefaultConstant(final String[] conditionConstantArray) { + static String findDefaultConstant(final String[] conditionConstantArray) + throws DeviceOverridePatternSyntaxError { if (conditionConstantArray == null) { return null; } for (final String condition : conditionConstantArray) { final int posComma = condition.indexOf(','); if (posComma < 0) { - throw new RuntimeException("Array element has no comma: " + condition); + throw new DeviceOverridePatternSyntaxError("Array element has no comma", condition); } if (posComma == 0) { // condition is empty. return condition.substring(posComma + 1); diff --git a/java/src/com/android/inputmethod/latin/utils/RunInLocale.java b/java/src/com/android/inputmethod/latin/utils/RunInLocale.java new file mode 100644 index 000000000..2c9e3b191 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/RunInLocale.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.content.res.Configuration; +import android.content.res.Resources; + +import java.util.Locale; + +public abstract class RunInLocale<T> { + private static final Object sLockForRunInLocale = new Object(); + + protected abstract T job(final Resources res); + + /** + * Execute {@link #job(Resources)} method in specified system locale exclusively. + * + * @param res the resources to use. + * @param newLocale the locale to change to. + * @return the value returned from {@link #job(Resources)}. + */ + public T runInLocale(final Resources res, final Locale newLocale) { + synchronized (sLockForRunInLocale) { + final Configuration conf = res.getConfiguration(); + final Locale oldLocale = conf.locale; + final boolean needsChange = (newLocale != null && !newLocale.equals(oldLocale)); + try { + if (needsChange) { + conf.locale = newLocale; + res.updateConfiguration(conf, null); + } + return job(res); + } finally { + if (needsChange) { + conf.locale = oldLocale; + res.updateConfiguration(conf, null); + } + } + } + } +} diff --git a/java/src/com/android/inputmethod/latin/StaticInnerHandlerWrapper.java b/java/src/com/android/inputmethod/latin/utils/StaticInnerHandlerWrapper.java index e50af4d2d..44e5d17b4 100644 --- a/java/src/com/android/inputmethod/latin/StaticInnerHandlerWrapper.java +++ b/java/src/com/android/inputmethod/latin/utils/StaticInnerHandlerWrapper.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.os.Handler; import android.os.Looper; diff --git a/java/src/com/android/inputmethod/latin/StringUtils.java b/java/src/com/android/inputmethod/latin/utils/StringUtils.java index ab050d7a3..7406d855a 100644 --- a/java/src/com/android/inputmethod/latin/StringUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/StringUtils.java @@ -14,10 +14,12 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.text.TextUtils; +import com.android.inputmethod.latin.Constants; + import java.util.ArrayList; import java.util.Locale; @@ -35,33 +37,55 @@ public final class StringUtils { return text.codePointCount(0, text.length()); } - public static boolean containsInArray(final String key, final String[] array) { + public static boolean containsInArray(final String text, final String[] array) { for (final String element : array) { - if (key.equals(element)) return true; + if (text.equals(element)) return true; } return false; } - public static boolean containsInCsv(final String key, final String csv) { - if (TextUtils.isEmpty(csv)) return false; - return containsInArray(key, csv.split(",")); + /** + * Comma-Splittable Text is similar to Comma-Separated Values (CSV) but has much simpler syntax. + * Unlike CSV, Comma-Splittable Text has no escaping mechanism, so that the text can't contain + * a comma character in it. + */ + private static final String SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT = ","; + + public static boolean containsInCommaSplittableText(final String text, + final String extraValues) { + if (TextUtils.isEmpty(extraValues)) { + return false; + } + return containsInArray(text, extraValues.split(SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT)); } - public static String appendToCsvIfNotExists(final String key, final String csv) { - if (TextUtils.isEmpty(csv)) return key; - if (containsInCsv(key, csv)) return csv; - return csv + "," + key; + public static String appendToCommaSplittableTextIfNotExists(final String text, + final String extraValues) { + if (TextUtils.isEmpty(extraValues)) { + return text; + } + if (containsInCommaSplittableText(text, extraValues)) { + return extraValues; + } + return extraValues + SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT + text; } - public static String removeFromCsvIfExists(final String key, final String csv) { - if (TextUtils.isEmpty(csv)) return ""; - final String[] elements = csv.split(","); - if (!containsInArray(key, elements)) return csv; + public static String removeFromCommaSplittableTextIfExists(final String text, + final String extraValues) { + if (TextUtils.isEmpty(extraValues)) { + return ""; + } + final String[] elements = extraValues.split(SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT); + if (!containsInArray(text, elements)) { + return extraValues; + } final ArrayList<String> result = CollectionUtils.newArrayList(elements.length - 1); for (final String element : elements) { - if (!key.equals(element)) result.add(element); + if (!text.equals(element)) { + result.add(element); + } } - return TextUtils.join(",", result); + return TextUtils.join(SEPARATOR_FOR_COMMA_SPLITTABLE_TEXT, result); } /** @@ -131,44 +155,6 @@ public final class StringUtils { return codePoints; } - public static String[] parseCsvString(final String text) { - final int size = text.length(); - if (size == 0) { - return null; - } - if (codePointCount(text) == 1) { - return text.codePointAt(0) == Constants.CSV_SEPARATOR ? null : new String[] { text }; - } - - ArrayList<String> list = null; - int start = 0; - for (int pos = 0; pos < size; pos++) { - final char c = text.charAt(pos); - if (c == Constants.CSV_SEPARATOR) { - // Skip empty entry. - if (pos - start > 0) { - if (list == null) { - list = CollectionUtils.newArrayList(); - } - list.add(text.substring(start, pos)); - } - // Skip comma - start = pos + 1; - } else if (c == Constants.CSV_ESCAPE) { - // Skip escape character and escaped character. - pos++; - } - } - final String remain = (size - start > 0) ? text.substring(start) : null; - if (list == null) { - return remain != null ? new String[] { remain } : null; - } - if (remain != null) { - list.add(remain); - } - return list.toArray(new String[list.size()]); - } - // This method assumes the text is not null. For the empty string, it returns CAPITALIZE_NONE. public static int getCapitalizationType(final String text) { // If the first char is not uppercase, then the word is either all lower case or diff --git a/java/src/com/android/inputmethod/latin/SubtypeLocale.java b/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java index 4d88ecc0c..16728092d 100644 --- a/java/src/com/android/inputmethod/latin/SubtypeLocale.java +++ b/java/src/com/android/inputmethod/latin/utils/SubtypeLocaleUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.KEYBOARD_LAYOUT_SET; import static com.android.inputmethod.latin.Constants.Subtype.ExtraValue.UNTRANSLATABLE_STRING_IN_SUBTYPE_NAME; @@ -25,13 +25,14 @@ import android.os.Build; import android.util.Log; import android.view.inputmethod.InputMethodSubtype; -import com.android.inputmethod.latin.LocaleUtils.RunInLocale; +import com.android.inputmethod.latin.DictionaryFactory; +import com.android.inputmethod.latin.R; import java.util.HashMap; import java.util.Locale; -public final class SubtypeLocale { - static final String TAG = SubtypeLocale.class.getSimpleName(); +public final class SubtypeLocaleUtils { + static final String TAG = SubtypeLocaleUtils.class.getSimpleName(); // This class must be located in the same package as LatinIME.java. private static final String RESOURCE_PACKAGE_NAME = DictionaryFactory.class.getPackage().getName(); @@ -69,7 +70,7 @@ public final class SubtypeLocale { private static final HashMap<String, String> sLocaleAndExtraValueToKeyboardLayoutSetMap = CollectionUtils.newHashMap(); - private SubtypeLocale() { + private SubtypeLocaleUtils() { // Intentional empty constructor for utility class. } @@ -217,9 +218,11 @@ public final class SubtypeLocale { return getSubtypeDisplayNameInternal(subtype, displayLocale); } - public static String getSubtypeDisplayName(final InputMethodSubtype subtype) { - final Locale displayLocale = getDisplayLocaleOfSubtypeLocale(subtype.getLocale()); - return getSubtypeDisplayNameInternal(subtype, displayLocale); + public static String getSubtypeNameForLogging(final InputMethodSubtype subtype) { + if (subtype == null) { + return "<null subtype>"; + } + return getSubtypeLocale(subtype) + "/" + getKeyboardLayoutSetName(subtype); } private static String getSubtypeDisplayNameInternal(final InputMethodSubtype subtype, @@ -238,7 +241,7 @@ public final class SubtypeLocale { + " nameResId=" + subtype.getNameResId() + " locale=" + subtype.getLocale() + " extra=" + subtype.getExtraValue() - + "\n" + Utils.getStackTrace()); + + "\n" + DebugLogUtils.getStackTrace()); return ""; } } @@ -284,4 +287,46 @@ public final class SubtypeLocale { } return keyboardLayoutSet; } + + // InputMethodSubtype's display name for spacebar text in its locale. + // isAdditionalSubtype (T=true, F=false) + // locale layout | Short Middle Full + // ------ ------- - ---- --------- ---------------------- + // en_US qwerty F En English English (US) exception + // en_GB qwerty F En English English (UK) exception + // es_US spanish F Es Español Español (EE.UU.) exception + // fr azerty F Fr Français Français + // fr_CA qwerty F Fr Français Français (Canada) + // de qwertz F De Deutsch Deutsch + // zz qwerty F QWERTY QWERTY + // fr qwertz T Fr Français Français + // de qwerty T De Deutsch Deutsch + // en_US azerty T En English English (US) + // zz azerty T AZERTY AZERTY + + // Get InputMethodSubtype's full display name in its locale. + public static String getFullDisplayName(final InputMethodSubtype subtype) { + if (isNoLanguage(subtype)) { + return getKeyboardLayoutSetDisplayName(subtype); + } + return getSubtypeLocaleDisplayName(subtype.getLocale()); + } + + // Get InputMethodSubtype's middle display name in its locale. + public static String getMiddleDisplayName(final InputMethodSubtype subtype) { + if (isNoLanguage(subtype)) { + return getKeyboardLayoutSetDisplayName(subtype); + } + final Locale locale = getSubtypeLocale(subtype); + return getSubtypeLocaleDisplayName(locale.getLanguage()); + } + + // Get InputMethodSubtype's short display name in its locale. + public static String getShortDisplayName(final InputMethodSubtype subtype) { + if (isNoLanguage(subtype)) { + return ""; + } + final Locale locale = getSubtypeLocale(subtype); + return StringUtils.capitalizeFirstCodePoint(locale.getLanguage(), locale); + } } diff --git a/java/src/com/android/inputmethod/latin/TargetPackageInfoGetterTask.java b/java/src/com/android/inputmethod/latin/utils/TargetPackageInfoGetterTask.java index 947b0c586..afbe2ecad 100644 --- a/java/src/com/android/inputmethod/latin/TargetPackageInfoGetterTask.java +++ b/java/src/com/android/inputmethod/latin/utils/TargetPackageInfoGetterTask.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.content.Context; import android.content.pm.PackageInfo; diff --git a/java/src/com/android/inputmethod/latin/utils/TextRange.java b/java/src/com/android/inputmethod/latin/utils/TextRange.java new file mode 100644 index 000000000..5793e4170 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/TextRange.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.text.Spanned; +import android.text.style.SuggestionSpan; + +import java.util.Arrays; + +/** + * Represents a range of text, relative to the current cursor position. + */ +public final class TextRange { + private final CharSequence mTextAtCursor; + private final int mWordAtCursorStartIndex; + private final int mWordAtCursorEndIndex; + private final int mCursorIndex; + + public final CharSequence mWord; + + public int getNumberOfCharsInWordBeforeCursor() { + return mCursorIndex - mWordAtCursorStartIndex; + } + + public int getNumberOfCharsInWordAfterCursor() { + return mWordAtCursorEndIndex - mCursorIndex; + } + + /** + * Gets the suggestion spans that are put squarely on the word, with the exact start + * and end of the span matching the boundaries of the word. + * @return the list of spans. + */ + public SuggestionSpan[] getSuggestionSpansAtWord() { + if (!(mTextAtCursor instanceof Spanned && mWord instanceof Spanned)) { + return new SuggestionSpan[0]; + } + final Spanned text = (Spanned)mTextAtCursor; + // Note: it's fine to pass indices negative or greater than the length of the string + // to the #getSpans() method. The reason we need to get from -1 to +1 is that, the + // spans were cut at the cursor position, and #getSpans(start, end) does not return + // spans that end at `start' or begin at `end'. Consider the following case: + // this| is (The | symbolizes the cursor position + // ---- --- + // In this case, the cursor is in position 4, so the 0~7 span has been split into + // a 0~4 part and a 4~7 part. + // If we called #getSpans(0, 4) in this case, we would only get the part from 0 to 4 + // of the span, and not the part from 4 to 7, so we would not realize the span actually + // extends from 0 to 7. But if we call #getSpans(-1, 5) we'll get both the 0~4 and + // the 4~7 spans and we can merge them accordingly. + // Any span starting more than 1 char away from the word boundaries in any direction + // does not touch the word, so we don't need to consider it. That's why requesting + // -1 ~ +1 is enough. + // Of course this is only relevant if the cursor is at one end of the word. If it's + // in the middle, the -1 and +1 are not necessary, but they are harmless. + final SuggestionSpan[] spans = text.getSpans(mWordAtCursorStartIndex - 1, + mWordAtCursorEndIndex + 1, SuggestionSpan.class); + int readIndex = 0; + int writeIndex = 0; + for (; readIndex < spans.length; ++readIndex) { + final SuggestionSpan span = spans[readIndex]; + // The span may be null, as we null them when we find duplicates. Cf a few lines + // down. + if (null == span) continue; + // Tentative span start and end. This may be modified later if we realize the + // same span is also applied to other parts of the string. + int spanStart = text.getSpanStart(span); + int spanEnd = text.getSpanEnd(span); + for (int i = readIndex + 1; i < spans.length; ++i) { + if (span.equals(spans[i])) { + // We found the same span somewhere else. Read the new extent of this + // span, and adjust our values accordingly. + spanStart = Math.min(spanStart, text.getSpanStart(spans[i])); + spanEnd = Math.max(spanEnd, text.getSpanEnd(spans[i])); + // ...and mark the span as processed. + spans[i] = null; + } + } + if (spanStart == mWordAtCursorStartIndex && spanEnd == mWordAtCursorEndIndex) { + // If the span does not start and stop here, we ignore it. It probably extends + // past the start or end of the word, as happens in missing space correction + // or EasyEditSpans put by voice input. + spans[writeIndex++] = spans[readIndex]; + } + } + return writeIndex == readIndex ? spans : Arrays.copyOfRange(spans, 0, writeIndex); + } + + public TextRange(final CharSequence textAtCursor, final int wordAtCursorStartIndex, + final int wordAtCursorEndIndex, final int cursorIndex) { + if (wordAtCursorStartIndex < 0 || cursorIndex < wordAtCursorStartIndex + || cursorIndex > wordAtCursorEndIndex + || wordAtCursorEndIndex > textAtCursor.length()) { + throw new IndexOutOfBoundsException(); + } + mTextAtCursor = textAtCursor; + mWordAtCursorStartIndex = wordAtCursorStartIndex; + mWordAtCursorEndIndex = wordAtCursorEndIndex; + mCursorIndex = cursorIndex; + mWord = mTextAtCursor.subSequence(mWordAtCursorStartIndex, mWordAtCursorEndIndex); + } +}
\ No newline at end of file diff --git a/java/src/com/android/inputmethod/latin/utils/TypefaceUtils.java b/java/src/com/android/inputmethod/latin/utils/TypefaceUtils.java new file mode 100644 index 000000000..544e4d201 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/TypefaceUtils.java @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.graphics.Paint; +import android.graphics.Rect; +import android.graphics.Typeface; +import android.util.SparseArray; + +public final class TypefaceUtils { + private TypefaceUtils() { + // This utility class is not publicly instantiable. + } + + // This sparse array caches key label text height in pixel indexed by key label text size. + private static final SparseArray<Float> sTextHeightCache = CollectionUtils.newSparseArray(); + // Working variable for the following method. + private static final Rect sTextHeightBounds = new Rect(); + + public static float getCharHeight(final char[] referenceChar, final Paint paint) { + final int key = getCharGeometryCacheKey(referenceChar[0], paint); + synchronized (sTextHeightCache) { + final Float cachedValue = sTextHeightCache.get(key); + if (cachedValue != null) { + return cachedValue; + } + + paint.getTextBounds(referenceChar, 0, 1, sTextHeightBounds); + final float height = sTextHeightBounds.height(); + sTextHeightCache.put(key, height); + return height; + } + } + + // This sparse array caches key label text width in pixel indexed by key label text size. + private static final SparseArray<Float> sTextWidthCache = CollectionUtils.newSparseArray(); + // Working variable for the following method. + private static final Rect sTextWidthBounds = new Rect(); + + public static float getCharWidth(final char[] referenceChar, final Paint paint) { + final int key = getCharGeometryCacheKey(referenceChar[0], paint); + synchronized (sTextWidthCache) { + final Float cachedValue = sTextWidthCache.get(key); + if (cachedValue != null) { + return cachedValue; + } + + paint.getTextBounds(referenceChar, 0, 1, sTextWidthBounds); + final float width = sTextWidthBounds.width(); + sTextWidthCache.put(key, width); + return width; + } + } + + private static int getCharGeometryCacheKey(final char referenceChar, final Paint paint) { + final int labelSize = (int)paint.getTextSize(); + final Typeface face = paint.getTypeface(); + final int codePointOffset = referenceChar << 15; + if (face == Typeface.DEFAULT) { + return codePointOffset + labelSize; + } else if (face == Typeface.DEFAULT_BOLD) { + return codePointOffset + labelSize + 0x1000; + } else if (face == Typeface.MONOSPACE) { + return codePointOffset + labelSize + 0x2000; + } else { + return codePointOffset + labelSize; + } + } + + public static float getLabelWidth(final String label, final Paint paint) { + final Rect textBounds = new Rect(); + paint.getTextBounds(label, 0, label.length(), textBounds); + return textBounds.width(); + } +} diff --git a/java/src/com/android/inputmethod/latin/utils/UsabilityStudyLogUtils.java b/java/src/com/android/inputmethod/latin/utils/UsabilityStudyLogUtils.java new file mode 100644 index 000000000..06826dac0 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/UsabilityStudyLogUtils.java @@ -0,0 +1,293 @@ +/* + * Copyright (C) 2016 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.utils; + +import android.content.Intent; +import android.content.pm.PackageManager; +import android.inputmethodservice.InputMethodService; +import android.net.Uri; +import android.os.Environment; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Process; +import android.util.Log; +import android.view.MotionEvent; + +import com.android.inputmethod.latin.LatinImeLogger; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.channels.FileChannel; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +public final class UsabilityStudyLogUtils { + // TODO: remove code duplication with ResearchLog class + private static final String USABILITY_TAG = UsabilityStudyLogUtils.class.getSimpleName(); + private static final String FILENAME = "log.txt"; + private final Handler mLoggingHandler; + private File mFile; + private File mDirectory; + private InputMethodService mIms; + private PrintWriter mWriter; + private final Date mDate; + private final SimpleDateFormat mDateFormat; + + private UsabilityStudyLogUtils() { + mDate = new Date(); + mDateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss.SSSZ", Locale.US); + + HandlerThread handlerThread = new HandlerThread("UsabilityStudyLogUtils logging task", + Process.THREAD_PRIORITY_BACKGROUND); + handlerThread.start(); + mLoggingHandler = new Handler(handlerThread.getLooper()); + } + + // Initialization-on-demand holder + private static final class OnDemandInitializationHolder { + public static final UsabilityStudyLogUtils sInstance = new UsabilityStudyLogUtils(); + } + + public static UsabilityStudyLogUtils getInstance() { + return OnDemandInitializationHolder.sInstance; + } + + public void init(final InputMethodService ims) { + mIms = ims; + mDirectory = ims.getFilesDir(); + } + + private void createLogFileIfNotExist() { + if ((mFile == null || !mFile.exists()) + && (mDirectory != null && mDirectory.exists())) { + try { + mWriter = getPrintWriter(mDirectory, FILENAME, false); + } catch (final IOException e) { + Log.e(USABILITY_TAG, "Can't create log file."); + } + } + } + + public static void writeBackSpace(final int x, final int y) { + UsabilityStudyLogUtils.getInstance().write("<backspace>\t" + x + "\t" + y); + } + + public static void writeChar(final char c, final int x, final int y) { + String inputChar = String.valueOf(c); + switch (c) { + case '\n': + inputChar = "<enter>"; + break; + case '\t': + inputChar = "<tab>"; + break; + case ' ': + inputChar = "<space>"; + break; + } + UsabilityStudyLogUtils.getInstance().write(inputChar + "\t" + x + "\t" + y); + LatinImeLogger.onPrintAllUsabilityStudyLogs(); + } + + public static void writeMotionEvent(final MotionEvent me) { + final int action = me.getActionMasked(); + final long eventTime = me.getEventTime(); + final int pointerCount = me.getPointerCount(); + for (int index = 0; index < pointerCount; index++) { + final int id = me.getPointerId(index); + final int x = (int)me.getX(index); + final int y = (int)me.getY(index); + final float size = me.getSize(index); + final float pressure = me.getPressure(index); + + final String eventTag; + switch (action) { + case MotionEvent.ACTION_UP: + eventTag = "[Up]"; + break; + case MotionEvent.ACTION_DOWN: + eventTag = "[Down]"; + break; + case MotionEvent.ACTION_POINTER_UP: + eventTag = "[PointerUp]"; + break; + case MotionEvent.ACTION_POINTER_DOWN: + eventTag = "[PointerDown]"; + break; + case MotionEvent.ACTION_MOVE: + eventTag = "[Move]"; + break; + default: + eventTag = "[Action" + action + "]"; + break; + } + getInstance().write(eventTag + eventTime + "," + id + "," + x + "," + y + "," + size + + "," + pressure); + } + } + + public void write(final String log) { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + createLogFileIfNotExist(); + final long currentTime = System.currentTimeMillis(); + mDate.setTime(currentTime); + + final String printString = String.format(Locale.US, "%s\t%d\t%s\n", + mDateFormat.format(mDate), currentTime, log); + if (LatinImeLogger.sDBG) { + Log.d(USABILITY_TAG, "Write: " + log); + } + mWriter.print(printString); + } + }); + } + + private synchronized String getBufferedLogs() { + mWriter.flush(); + final StringBuilder sb = new StringBuilder(); + final BufferedReader br = getBufferedReader(); + String line; + try { + while ((line = br.readLine()) != null) { + sb.append('\n'); + sb.append(line); + } + } catch (final IOException e) { + Log.e(USABILITY_TAG, "Can't read log file."); + } finally { + if (LatinImeLogger.sDBG) { + Log.d(USABILITY_TAG, "Got all buffered logs\n" + sb.toString()); + } + try { + br.close(); + } catch (final IOException e) { + // ignore. + } + } + return sb.toString(); + } + + public void emailResearcherLogsAll() { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + final Date date = new Date(); + date.setTime(System.currentTimeMillis()); + final String currentDateTimeString = + new SimpleDateFormat("yyyyMMdd-HHmmssZ", Locale.US).format(date); + if (mFile == null) { + Log.w(USABILITY_TAG, "No internal log file found."); + return; + } + if (mIms.checkCallingOrSelfPermission( + android.Manifest.permission.WRITE_EXTERNAL_STORAGE) + != PackageManager.PERMISSION_GRANTED) { + Log.w(USABILITY_TAG, "Doesn't have the permission WRITE_EXTERNAL_STORAGE"); + return; + } + mWriter.flush(); + final String destPath = Environment.getExternalStorageDirectory() + + "/research-" + currentDateTimeString + ".log"; + final File destFile = new File(destPath); + try { + final FileInputStream srcStream = new FileInputStream(mFile); + final FileOutputStream destStream = new FileOutputStream(destFile); + final FileChannel src = srcStream.getChannel(); + final FileChannel dest = destStream.getChannel(); + src.transferTo(0, src.size(), dest); + src.close(); + srcStream.close(); + dest.close(); + destStream.close(); + } catch (final FileNotFoundException e1) { + Log.w(USABILITY_TAG, e1); + return; + } catch (final IOException e2) { + Log.w(USABILITY_TAG, e2); + return; + } + if (!destFile.exists()) { + Log.w(USABILITY_TAG, "Dest file doesn't exist."); + return; + } + final Intent intent = new Intent(Intent.ACTION_SEND); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + if (LatinImeLogger.sDBG) { + Log.d(USABILITY_TAG, "Destination file URI is " + destFile.toURI()); + } + intent.setType("text/plain"); + intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + destPath)); + intent.putExtra(Intent.EXTRA_SUBJECT, + "[Research Logs] " + currentDateTimeString); + mIms.startActivity(intent); + } + }); + } + + public void printAll() { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + mIms.getCurrentInputConnection().commitText(getBufferedLogs(), 0); + } + }); + } + + public void clearAll() { + mLoggingHandler.post(new Runnable() { + @Override + public void run() { + if (mFile != null && mFile.exists()) { + if (LatinImeLogger.sDBG) { + Log.d(USABILITY_TAG, "Delete log file."); + } + mFile.delete(); + mWriter.close(); + } + } + }); + } + + private BufferedReader getBufferedReader() { + createLogFileIfNotExist(); + try { + return new BufferedReader(new FileReader(mFile)); + } catch (final FileNotFoundException e) { + return null; + } + } + + private PrintWriter getPrintWriter(final File dir, final String filename, + final boolean renew) throws IOException { + mFile = new File(dir, filename); + if (mFile.exists()) { + if (renew) { + mFile.delete(); + } + } + return new PrintWriter(new FileOutputStream(mFile), true /* autoFlush */); + } +} diff --git a/java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java b/java/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtils.java index 10931555e..d02f7187e 100644 --- a/java/src/com/android/inputmethod/latin/UserHistoryDictIOUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/UserHistoryDictIOUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.util.Log; @@ -27,6 +27,7 @@ import com.android.inputmethod.latin.makedict.FusionDictionary; import com.android.inputmethod.latin.makedict.FusionDictionary.Node; import com.android.inputmethod.latin.makedict.PendingAttribute; import com.android.inputmethod.latin.makedict.UnsupportedFormatException; +import com.android.inputmethod.latin.personalization.UserHistoryDictionaryBigramList; import java.io.IOException; import java.io.OutputStream; @@ -53,64 +54,6 @@ public final class UserHistoryDictIOUtils { public int getFrequency(final String word1, final String word2); } - public static final class ByteArrayWrapper implements FusionDictionaryBufferInterface { - private byte[] mBuffer; - private int mPosition; - - public ByteArrayWrapper(final byte[] buffer) { - mBuffer = buffer; - mPosition = 0; - } - - @Override - public int readUnsignedByte() { - return mBuffer[mPosition++] & 0xFF; - } - - @Override - public int readUnsignedShort() { - final int retval = readUnsignedByte(); - return (retval << 8) + readUnsignedByte(); - } - - @Override - public int readUnsignedInt24() { - final int retval = readUnsignedShort(); - return (retval << 8) + readUnsignedByte(); - } - - @Override - public int readInt() { - final int retval = readUnsignedShort(); - return (retval << 16) + readUnsignedShort(); - } - - @Override - public int position() { - return mPosition; - } - - @Override - public void position(int position) { - mPosition = position; - } - - @Override - public void put(final byte b) { - mBuffer[mPosition++] = b; - } - - @Override - public int limit() { - return mBuffer.length - 1; - } - - @Override - public int capacity() { - return mBuffer.length; - } - } - /** * Writes dictionary to file. */ diff --git a/java/src/com/android/inputmethod/latin/UserHistoryForgettingCurveUtils.java b/java/src/com/android/inputmethod/latin/utils/UserHistoryForgettingCurveUtils.java index 9053d709b..713a45bda 100644 --- a/java/src/com/android/inputmethod/latin/UserHistoryForgettingCurveUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/UserHistoryForgettingCurveUtils.java @@ -14,11 +14,12 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; -import android.text.format.DateUtils; import android.util.Log; +import java.util.concurrent.TimeUnit; + public final class UserHistoryForgettingCurveUtils { private static final String TAG = UserHistoryForgettingCurveUtils.class.getSimpleName(); private static final boolean DEBUG = false; @@ -27,8 +28,8 @@ public final class UserHistoryForgettingCurveUtils { private static final int FC_LEVEL_MAX = 3; /* package */ static final int ELAPSED_TIME_MAX = 15; private static final int ELAPSED_TIME_INTERVAL_HOURS = 6; - private static final long ELAPSED_TIME_INTERVAL_MILLIS = ELAPSED_TIME_INTERVAL_HOURS - * DateUtils.HOUR_IN_MILLIS; + private static final long ELAPSED_TIME_INTERVAL_MILLIS = + TimeUnit.HOURS.toMillis(ELAPSED_TIME_INTERVAL_HOURS); private static final int HALF_LIFE_HOURS = 48; private static final int MAX_PUSH_ELAPSED = (FC_LEVEL_MAX + 1) * (ELAPSED_TIME_MAX + 1); diff --git a/java/src/com/android/inputmethod/latin/utils/UserLogRingCharBuffer.java b/java/src/com/android/inputmethod/latin/utils/UserLogRingCharBuffer.java new file mode 100644 index 000000000..161386e2e --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/UserLogRingCharBuffer.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.inputmethod.latin.utils; + +import android.inputmethodservice.InputMethodService; + +import com.android.inputmethod.annotations.UsedForTesting; +import com.android.inputmethod.latin.settings.Settings; + +public final class UserLogRingCharBuffer { + public /* for test */ static final int BUFSIZE = 20; + public /* for test */ int mLength = 0; + + private static UserLogRingCharBuffer sUserLogRingCharBuffer = new UserLogRingCharBuffer(); + private static final char PLACEHOLDER_DELIMITER_CHAR = '\uFFFC'; + private static final int INVALID_COORDINATE = -2; + private boolean mEnabled = false; + private int mEnd = 0; + private char[] mCharBuf = new char[BUFSIZE]; + private int[] mXBuf = new int[BUFSIZE]; + private int[] mYBuf = new int[BUFSIZE]; + + private UserLogRingCharBuffer() { + // Intentional empty constructor for singleton. + } + + @UsedForTesting + public static UserLogRingCharBuffer getInstance() { + return sUserLogRingCharBuffer; + } + + public static UserLogRingCharBuffer init(final InputMethodService context, + final boolean enabled, final boolean usabilityStudy) { + if (!(enabled || usabilityStudy)) { + return null; + } + sUserLogRingCharBuffer.mEnabled = true; + UsabilityStudyLogUtils.getInstance().init(context); + return sUserLogRingCharBuffer; + } + + private static int normalize(final int in) { + int ret = in % BUFSIZE; + return ret < 0 ? ret + BUFSIZE : ret; + } + + // TODO: accept code points + @UsedForTesting + public void push(final char c, final int x, final int y) { + if (!mEnabled) { + return; + } + mCharBuf[mEnd] = c; + mXBuf[mEnd] = x; + mYBuf[mEnd] = y; + mEnd = normalize(mEnd + 1); + if (mLength < BUFSIZE) { + ++mLength; + } + } + + public char pop() { + if (mLength < 1) { + return PLACEHOLDER_DELIMITER_CHAR; + } + mEnd = normalize(mEnd - 1); + --mLength; + return mCharBuf[mEnd]; + } + + public char getBackwardNthChar(final int n) { + if (mLength <= n || n < 0) { + return PLACEHOLDER_DELIMITER_CHAR; + } + return mCharBuf[normalize(mEnd - n - 1)]; + } + + public int getPreviousX(final char c, final int back) { + final int index = normalize(mEnd - 2 - back); + if (mLength <= back + || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { + return INVALID_COORDINATE; + } + return mXBuf[index]; + } + + public int getPreviousY(final char c, final int back) { + int index = normalize(mEnd - 2 - back); + if (mLength <= back + || Character.toLowerCase(c) != Character.toLowerCase(mCharBuf[index])) { + return INVALID_COORDINATE; + } + return mYBuf[index]; + } + + public String getLastWord(final int ignoreCharCount) { + final StringBuilder sb = new StringBuilder(); + int i = ignoreCharCount; + for (; i < mLength; ++i) { + final char c = mCharBuf[normalize(mEnd - 1 - i)]; + if (!Settings.getInstance().isWordSeparator(c)) { + break; + } + } + for (; i < mLength; ++i) { + char c = mCharBuf[normalize(mEnd - 1 - i)]; + if (!Settings.getInstance().isWordSeparator(c)) { + sb.append(c); + } else { + break; + } + } + return sb.reverse().toString(); + } + + public void reset() { + mLength = 0; + } +} diff --git a/java/src/com/android/inputmethod/latin/utils/ViewLayoutUtils.java b/java/src/com/android/inputmethod/latin/utils/ViewLayoutUtils.java new file mode 100644 index 000000000..f9d853493 --- /dev/null +++ b/java/src/com/android/inputmethod/latin/utils/ViewLayoutUtils.java @@ -0,0 +1,54 @@ +/* + * 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.utils; + +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewGroup.MarginLayoutParams; +import android.widget.FrameLayout; +import android.widget.RelativeLayout; + +public final class ViewLayoutUtils { + private ViewLayoutUtils() { + // This utility class is not publicly instantiable. + } + + public static MarginLayoutParams newLayoutParam(final ViewGroup placer, final int width, + final int height) { + if (placer instanceof FrameLayout) { + return new FrameLayout.LayoutParams(width, height); + } else if (placer instanceof RelativeLayout) { + return new RelativeLayout.LayoutParams(width, height); + } else if (placer == null) { + throw new NullPointerException("placer is null"); + } else { + throw new IllegalArgumentException("placer is neither FrameLayout nor RelativeLayout: " + + placer.getClass().getName()); + } + } + + public static void placeViewAt(final View view, final int x, final int y, final int w, + final int h) { + final ViewGroup.LayoutParams lp = view.getLayoutParams(); + if (lp instanceof MarginLayoutParams) { + final MarginLayoutParams marginLayoutParams = (MarginLayoutParams)lp; + marginLayoutParams.width = w; + marginLayoutParams.height = h; + marginLayoutParams.setMargins(x, y, 0, 0); + } + } +} diff --git a/java/src/com/android/inputmethod/latin/XmlParseUtils.java b/java/src/com/android/inputmethod/latin/utils/XmlParseUtils.java index 48e5ed30a..bdad16652 100644 --- a/java/src/com/android/inputmethod/latin/XmlParseUtils.java +++ b/java/src/com/android/inputmethod/latin/utils/XmlParseUtils.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.android.inputmethod.latin; +package com.android.inputmethod.latin.utils; import android.content.res.TypedArray; |