Home | History | Annotate | Download | only in research
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.inputmethod.research;
     18 
     19 import android.os.SystemClock;
     20 import android.text.TextUtils;
     21 import android.util.JsonWriter;
     22 import android.util.Log;
     23 
     24 import com.android.inputmethod.latin.SuggestedWords;
     25 import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
     26 import com.android.inputmethod.latin.define.ProductionFlag;
     27 
     28 import java.io.IOException;
     29 import java.util.ArrayList;
     30 import java.util.Arrays;
     31 import java.util.List;
     32 import java.util.regex.Pattern;
     33 
     34 /**
     35  * A group of log statements related to each other.
     36  *
     37  * A LogUnit is collection of LogStatements, each of which is generated by at a particular point
     38  * in the code.  (There is no LogStatement class; the data is stored across the instance variables
     39  * here.)  A single LogUnit's statements can correspond to all the calls made while in the same
     40  * composing region, or all the calls between committing the last composing region, and the first
     41  * character of the next composing region.
     42  *
     43  * Individual statements in a log may be marked as potentially private.  If so, then they are only
     44  * published to a ResearchLog if the ResearchLogger determines that publishing the entire LogUnit
     45  * will not violate the user's privacy.  Checks for this may include whether other LogUnits have
     46  * been published recently, or whether the LogUnit contains numbers, etc.
     47  */
     48 public class LogUnit {
     49     private static final String TAG = LogUnit.class.getSimpleName();
     50     private static final boolean DEBUG = false
     51             && ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS_DEBUG;
     52 
     53     private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
     54     private static final String[] EMPTY_STRING_ARRAY = new String[0];
     55 
     56     private final ArrayList<LogStatement> mLogStatementList;
     57     private final ArrayList<Object[]> mValuesList;
     58     // Assume that mTimeList is sorted in increasing order.  Do not insert null values into
     59     // mTimeList.
     60     private final ArrayList<Long> mTimeList;
     61     // Words that this LogUnit generates.  Should be null if the data in the LogUnit does not
     62     // generate a genuine word (i.e. separators alone do not count as a word).  Should never be
     63     // empty.  Note that if the user types spaces explicitly, then normally mWords should contain
     64     // only a single word; it will only contain space-separate multiple words if the user does not
     65     // enter a space, and the system enters one automatically.
     66     private String mWords;
     67     private String[] mWordArray = EMPTY_STRING_ARRAY;
     68     private boolean mMayContainDigit;
     69     private boolean mIsPartOfMegaword;
     70     private boolean mContainsUserDeletions;
     71 
     72     // mCorrectionType indicates whether the word was corrected at all, and if so, the nature of the
     73     // correction.
     74     private int mCorrectionType;
     75     // LogUnits start in this state.  If a word is entered without being corrected, it will have
     76     // this CorrectiontType.
     77     public static final int CORRECTIONTYPE_NO_CORRECTION = 0;
     78     // The LogUnit was corrected manually by the user in an unspecified way.
     79     public static final int CORRECTIONTYPE_CORRECTION = 1;
     80     // The LogUnit was corrected manually by the user to a word not in the list of suggestions of
     81     // the first word typed here.  (Note: this is a heuristic value, it may be incorrect, for
     82     // example, if the user repositions the cursor).
     83     public static final int CORRECTIONTYPE_DIFFERENT_WORD = 2;
     84     // The LogUnit was corrected manually by the user to a word that was in the list of suggestions
     85     // of the first word typed here.  (Again, a heuristic).  It is probably a typo correction.
     86     public static final int CORRECTIONTYPE_TYPO = 3;
     87     // TODO: Rather than just tracking the current state, keep a historical record of the LogUnit's
     88     // state and statistics.  This should include how many times it has been corrected, whether
     89     // other LogUnit edits were done between edits to this LogUnit, etc.  Also track when a LogUnit
     90     // previously contained a word, but was corrected to empty (because it was deleted, and there is
     91     // no known replacement).
     92 
     93     private SuggestedWords mSuggestedWords;
     94 
     95     public LogUnit() {
     96         mLogStatementList = new ArrayList<LogStatement>();
     97         mValuesList = new ArrayList<Object[]>();
     98         mTimeList = new ArrayList<Long>();
     99         mIsPartOfMegaword = false;
    100         mCorrectionType = CORRECTIONTYPE_NO_CORRECTION;
    101         mSuggestedWords = null;
    102     }
    103 
    104     private LogUnit(final ArrayList<LogStatement> logStatementList,
    105             final ArrayList<Object[]> valuesList,
    106             final ArrayList<Long> timeList,
    107             final boolean isPartOfMegaword) {
    108         mLogStatementList = logStatementList;
    109         mValuesList = valuesList;
    110         mTimeList = timeList;
    111         mIsPartOfMegaword = isPartOfMegaword;
    112         mCorrectionType = CORRECTIONTYPE_NO_CORRECTION;
    113         mSuggestedWords = null;
    114     }
    115 
    116     private static final Object[] NULL_VALUES = new Object[0];
    117     /**
    118      * Adds a new log statement.  The time parameter in successive calls to this method must be
    119      * monotonically increasing, or splitByTime() will not work.
    120      */
    121     public void addLogStatement(final LogStatement logStatement, final long time,
    122             Object... values) {
    123         if (values == null) {
    124             values = NULL_VALUES;
    125         }
    126         mLogStatementList.add(logStatement);
    127         mValuesList.add(values);
    128         mTimeList.add(time);
    129     }
    130 
    131     /**
    132      * Publish the contents of this LogUnit to {@code researchLog}.
    133      *
    134      * For each publishable {@code LogStatement}, invoke {@link LogStatement#outputToLocked}.
    135      *
    136      * @param researchLog where to publish the contents of this {@code LogUnit}
    137      * @param canIncludePrivateData whether the private data in this {@code LogUnit} should be
    138      * included
    139      *
    140      * @throws IOException if publication to the log file is not possible
    141      */
    142     public synchronized void publishTo(final ResearchLog researchLog,
    143             final boolean canIncludePrivateData) throws IOException {
    144         // Write out any logStatement that passes the privacy filter.
    145         final int size = mLogStatementList.size();
    146         if (size != 0) {
    147             // Note that jsonWriter is only set to a non-null value if the logUnit start text is
    148             // output and at least one logStatement is output.
    149             JsonWriter jsonWriter = researchLog.getInitializedJsonWriterLocked();
    150             outputLogUnitStart(jsonWriter, canIncludePrivateData);
    151             for (int i = 0; i < size; i++) {
    152                 final LogStatement logStatement = mLogStatementList.get(i);
    153                 if (!canIncludePrivateData && logStatement.isPotentiallyPrivate()) {
    154                     continue;
    155                 }
    156                 if (mIsPartOfMegaword && logStatement.isPotentiallyRevealing()) {
    157                     continue;
    158                 }
    159                 logStatement.outputToLocked(jsonWriter, mTimeList.get(i), mValuesList.get(i));
    160             }
    161             outputLogUnitStop(jsonWriter);
    162         }
    163     }
    164 
    165     private static final String WORD_KEY = "_wo";
    166     private static final String NUM_WORDS_KEY = "_nw";
    167     private static final String CORRECTION_TYPE_KEY = "_corType";
    168     private static final String LOG_UNIT_BEGIN_KEY = "logUnitStart";
    169     private static final String LOG_UNIT_END_KEY = "logUnitEnd";
    170 
    171     final LogStatement LOGSTATEMENT_LOG_UNIT_BEGIN_WITH_PRIVATE_DATA =
    172             new LogStatement(LOG_UNIT_BEGIN_KEY, false /* isPotentiallyPrivate */,
    173                     false /* isPotentiallyRevealing */, WORD_KEY, CORRECTION_TYPE_KEY,
    174                     NUM_WORDS_KEY);
    175     final LogStatement LOGSTATEMENT_LOG_UNIT_BEGIN_WITHOUT_PRIVATE_DATA =
    176             new LogStatement(LOG_UNIT_BEGIN_KEY, false /* isPotentiallyPrivate */,
    177                     false /* isPotentiallyRevealing */, NUM_WORDS_KEY);
    178     private void outputLogUnitStart(final JsonWriter jsonWriter,
    179             final boolean canIncludePrivateData) {
    180         final LogStatement logStatement;
    181         if (canIncludePrivateData) {
    182             LOGSTATEMENT_LOG_UNIT_BEGIN_WITH_PRIVATE_DATA.outputToLocked(jsonWriter,
    183                     SystemClock.uptimeMillis(), getWordsAsString(), getCorrectionType(),
    184                     getNumWords());
    185         } else {
    186             LOGSTATEMENT_LOG_UNIT_BEGIN_WITHOUT_PRIVATE_DATA.outputToLocked(jsonWriter,
    187                     SystemClock.uptimeMillis(), getNumWords());
    188         }
    189     }
    190 
    191     final LogStatement LOGSTATEMENT_LOG_UNIT_END =
    192             new LogStatement(LOG_UNIT_END_KEY, false /* isPotentiallyPrivate */,
    193                     false /* isPotentiallyRevealing */);
    194     private void outputLogUnitStop(final JsonWriter jsonWriter) {
    195         LOGSTATEMENT_LOG_UNIT_END.outputToLocked(jsonWriter, SystemClock.uptimeMillis());
    196     }
    197 
    198     /**
    199      * Mark the current logUnit as containing data to generate {@code newWords}.
    200      *
    201      * If {@code setWord()} was previously called for this LogUnit, then the method will try to
    202      * determine what kind of correction it is, and update its internal state of the correctionType
    203      * accordingly.
    204      *
    205      * @param newWords The words this LogUnit generates.  Caller should not pass null or the empty
    206      * string.
    207      */
    208     public void setWords(final String newWords) {
    209         if (hasOneOrMoreWords()) {
    210             // The word was already set once, and it is now being changed.  See if the new word
    211             // is close to the old word.  If so, then the change is probably a typo correction.
    212             // If not, the user may have decided to enter a different word, so flag it.
    213             if (mSuggestedWords != null) {
    214                 if (isInSuggestedWords(newWords, mSuggestedWords)) {
    215                     mCorrectionType = CORRECTIONTYPE_TYPO;
    216                 } else {
    217                     mCorrectionType = CORRECTIONTYPE_DIFFERENT_WORD;
    218                 }
    219             } else {
    220                 // No suggested words, so it's not clear whether it's a typo or different word.
    221                 // Mark it as a generic correction.
    222                 mCorrectionType = CORRECTIONTYPE_CORRECTION;
    223             }
    224         } else {
    225             mCorrectionType = CORRECTIONTYPE_NO_CORRECTION;
    226         }
    227         mWords = newWords;
    228 
    229         // Update mWordArray
    230         mWordArray = (TextUtils.isEmpty(mWords)) ? EMPTY_STRING_ARRAY
    231                 : WHITESPACE_PATTERN.split(mWords);
    232         if (mWordArray.length > 0 && TextUtils.isEmpty(mWordArray[0])) {
    233             // Empty string at beginning of array.  Must have been whitespace at the start of the
    234             // word.  Remove the empty string.
    235             mWordArray = Arrays.copyOfRange(mWordArray, 1, mWordArray.length);
    236         }
    237     }
    238 
    239     public String getWordsAsString() {
    240         return mWords;
    241     }
    242 
    243     /**
    244      * Retuns the words generated by the data in this LogUnit.
    245      *
    246      * The first word may be an empty string, if the data in the LogUnit started by generating
    247      * whitespace.
    248      *
    249      * @return the array of words. an empty list of there are no words associated with this LogUnit.
    250      */
    251     public String[] getWordsAsStringArray() {
    252         return mWordArray;
    253     }
    254 
    255     public boolean hasOneOrMoreWords() {
    256         return mWordArray.length >= 1;
    257     }
    258 
    259     public int getNumWords() {
    260         return mWordArray.length;
    261     }
    262 
    263     // TODO: Refactor to eliminate getter/setters
    264     public void setMayContainDigit() {
    265         mMayContainDigit = true;
    266     }
    267 
    268     // TODO: Refactor to eliminate getter/setters
    269     public boolean mayContainDigit() {
    270         return mMayContainDigit;
    271     }
    272 
    273     // TODO: Refactor to eliminate getter/setters
    274     public void setContainsUserDeletions() {
    275         mContainsUserDeletions = true;
    276     }
    277 
    278     // TODO: Refactor to eliminate getter/setters
    279     public boolean containsUserDeletions() {
    280         return mContainsUserDeletions;
    281     }
    282 
    283     // TODO: Refactor to eliminate getter/setters
    284     public void setCorrectionType(final int correctionType) {
    285         mCorrectionType = correctionType;
    286     }
    287 
    288     // TODO: Refactor to eliminate getter/setters
    289     public int getCorrectionType() {
    290         return mCorrectionType;
    291     }
    292 
    293     public boolean isEmpty() {
    294         return mLogStatementList.isEmpty();
    295     }
    296 
    297     /**
    298      * Split this logUnit, with all events before maxTime staying in the current logUnit, and all
    299      * events after maxTime going into a new LogUnit that is returned.
    300      */
    301     public LogUnit splitByTime(final long maxTime) {
    302         // Assume that mTimeList is in sorted order.
    303         final int length = mTimeList.size();
    304         // TODO: find time by binary search, e.g. using Collections#binarySearch()
    305         for (int index = 0; index < length; index++) {
    306             if (mTimeList.get(index) > maxTime) {
    307                 final List<LogStatement> laterLogStatements =
    308                         mLogStatementList.subList(index, length);
    309                 final List<Object[]> laterValues = mValuesList.subList(index, length);
    310                 final List<Long> laterTimes = mTimeList.subList(index, length);
    311 
    312                 // Create the LogUnit containing the later logStatements and associated data.
    313                 final LogUnit newLogUnit = new LogUnit(
    314                         new ArrayList<LogStatement>(laterLogStatements),
    315                         new ArrayList<Object[]>(laterValues),
    316                         new ArrayList<Long>(laterTimes),
    317                         true /* isPartOfMegaword */);
    318                 newLogUnit.mWords = null;
    319                 newLogUnit.mMayContainDigit = mMayContainDigit;
    320                 newLogUnit.mContainsUserDeletions = mContainsUserDeletions;
    321 
    322                 // Purge the logStatements and associated data from this LogUnit.
    323                 laterLogStatements.clear();
    324                 laterValues.clear();
    325                 laterTimes.clear();
    326                 mIsPartOfMegaword = true;
    327 
    328                 return newLogUnit;
    329             }
    330         }
    331         return new LogUnit();
    332     }
    333 
    334     public void append(final LogUnit logUnit) {
    335         mLogStatementList.addAll(logUnit.mLogStatementList);
    336         mValuesList.addAll(logUnit.mValuesList);
    337         mTimeList.addAll(logUnit.mTimeList);
    338         mWords = null;
    339         if (logUnit.mWords != null) {
    340             setWords(logUnit.mWords);
    341         }
    342         mMayContainDigit = mMayContainDigit || logUnit.mMayContainDigit;
    343         mContainsUserDeletions = mContainsUserDeletions || logUnit.mContainsUserDeletions;
    344         mIsPartOfMegaword = false;
    345     }
    346 
    347     public SuggestedWords getSuggestions() {
    348         return mSuggestedWords;
    349     }
    350 
    351     /**
    352      * Initialize the suggestions.
    353      *
    354      * Once set to a non-null value, the suggestions may not be changed again.  This is to keep
    355      * track of the list of words that are close to the user's initial effort to type the word.
    356      * Only words that are close to the initial effort are considered typo corrections.
    357      */
    358     public void initializeSuggestions(final SuggestedWords suggestedWords) {
    359         if (mSuggestedWords == null) {
    360             mSuggestedWords = suggestedWords;
    361         }
    362     }
    363 
    364     private static boolean isInSuggestedWords(final String queryWord,
    365             final SuggestedWords suggestedWords) {
    366         if (TextUtils.isEmpty(queryWord)) {
    367             return false;
    368         }
    369         final int size = suggestedWords.size();
    370         for (int i = 0; i < size; i++) {
    371             final SuggestedWordInfo wordInfo = suggestedWords.getInfo(i);
    372             if (queryWord.equals(wordInfo.mWord)) {
    373                 return true;
    374             }
    375         }
    376         return false;
    377     }
    378 
    379     /**
    380      * Remove data associated with selecting the Research button.
    381      *
    382      * A LogUnit will capture all user interactions with the IME, including the "meta-interactions"
    383      * of using the Research button to control the logging (e.g. by starting and stopping recording
    384      * of a test case).  Because meta-interactions should not be part of the normal log, calling
    385      * this method will set a field in the LogStatements of the motion events to indiciate that
    386      * they should be disregarded.
    387      *
    388      * This implementation assumes that the data recorded by the meta-interaction takes the
    389      * form of all events following the first MotionEvent.ACTION_DOWN before the first long-press
    390      * before the last onCodeEvent containing a code matching {@code LogStatement.VALUE_RESEARCH}.
    391      *
    392      * @returns true if data was removed
    393      */
    394     public boolean removeResearchButtonInvocation() {
    395         // This method is designed to be idempotent.
    396 
    397         // First, find last invocation of "research" key
    398         final int indexOfLastResearchKey = findLastIndexContainingKeyValue(
    399                 LogStatement.TYPE_POINTER_TRACKER_CALL_LISTENER_ON_CODE_INPUT,
    400                 LogStatement.KEY_CODE, LogStatement.VALUE_RESEARCH);
    401         if (indexOfLastResearchKey < 0) {
    402             // Could not find invocation of "research" key.  Leave log as is.
    403             if (DEBUG) {
    404                 Log.d(TAG, "Could not find research key");
    405             }
    406             return false;
    407         }
    408 
    409         // Look for the long press that started the invocation of the research key code input.
    410         final int indexOfLastLongPressBeforeResearchKey =
    411                 findLastIndexBefore(LogStatement.TYPE_MAIN_KEYBOARD_VIEW_ON_LONG_PRESS,
    412                         indexOfLastResearchKey);
    413 
    414         // Look for DOWN event preceding the long press
    415         final int indexOfLastDownEventBeforeLongPress =
    416                 findLastIndexContainingKeyValueBefore(LogStatement.TYPE_MOTION_EVENT,
    417                         LogStatement.ACTION, LogStatement.VALUE_DOWN,
    418                         indexOfLastLongPressBeforeResearchKey);
    419 
    420         // Flag all LatinKeyboardViewProcessMotionEvents from the DOWN event to the research key as
    421         // logging-related
    422         final int startingIndex = indexOfLastDownEventBeforeLongPress == -1 ? 0
    423                 : indexOfLastDownEventBeforeLongPress;
    424         for (int index = startingIndex; index < indexOfLastResearchKey; index++) {
    425             final LogStatement logStatement = mLogStatementList.get(index);
    426             final String type = logStatement.getType();
    427             final Object[] values = mValuesList.get(index);
    428             if (type.equals(LogStatement.TYPE_MOTION_EVENT)) {
    429                 logStatement.setValue(LogStatement.KEY_IS_LOGGING_RELATED, values, true);
    430             }
    431         }
    432         return true;
    433     }
    434 
    435     /**
    436      * Find the index of the last LogStatement before {@code startingIndex} of type {@code type}.
    437      *
    438      * @param queryType a String that must be {@code String.equals()} to the LogStatement type
    439      * @param startingIndex the index to start the backward search from.  Must be less than the
    440      * length of mLogStatementList, or an IndexOutOfBoundsException is thrown.  Can be negative,
    441      * in which case -1 is returned.
    442      *
    443      * @return The index of the last LogStatement, -1 if none exists.
    444      */
    445     private int findLastIndexBefore(final String queryType, final int startingIndex) {
    446         return findLastIndexContainingKeyValueBefore(queryType, null, null, startingIndex);
    447     }
    448 
    449     /**
    450      * Find the index of the last LogStatement before {@code startingIndex} of type {@code type}
    451      * containing the given key-value pair.
    452      *
    453      * @param queryType a String that must be {@code String.equals()} to the LogStatement type
    454      * @param queryKey a String that must be {@code String.equals()} to a key in the LogStatement
    455      * @param queryValue an Object that must be {@code String.equals()} to the key's corresponding
    456      * value
    457      *
    458      * @return The index of the last LogStatement, -1 if none exists.
    459      */
    460     private int findLastIndexContainingKeyValue(final String queryType, final String queryKey,
    461             final Object queryValue) {
    462         return findLastIndexContainingKeyValueBefore(queryType, queryKey, queryValue,
    463                 mLogStatementList.size() - 1);
    464     }
    465 
    466     /**
    467      * Find the index of the last LogStatement before {@code startingIndex} of type {@code type}
    468      * containing the given key-value pair.
    469      *
    470      * @param queryType a String that must be {@code String.equals()} to the LogStatement type
    471      * @param queryKey a String that must be {@code String.equals()} to a key in the LogStatement
    472      * @param queryValue an Object that must be {@code String.equals()} to the key's corresponding
    473      * value
    474      * @param startingIndex the index to start the backward search from.  Must be less than the
    475      * length of mLogStatementList, or an IndexOutOfBoundsException is thrown.  Can be negative,
    476      * in which case -1 is returned.
    477      *
    478      * @return The index of the last LogStatement, -1 if none exists.
    479      */
    480     private int findLastIndexContainingKeyValueBefore(final String queryType, final String queryKey,
    481             final Object queryValue, final int startingIndex) {
    482         if (startingIndex < 0) {
    483             return -1;
    484         }
    485         for (int index = startingIndex; index >= 0; index--) {
    486             final LogStatement logStatement = mLogStatementList.get(index);
    487             final String type = logStatement.getType();
    488             if (type.equals(queryType) && (queryKey == null
    489                     || logStatement.containsKeyValuePair(queryKey, queryValue,
    490                             mValuesList.get(index)))) {
    491                 return index;
    492             }
    493         }
    494         return -1;
    495     }
    496 }
    497