aboutsummaryrefslogtreecommitdiffstats
path: root/java/src/com/android/inputmethod/research
diff options
context:
space:
mode:
Diffstat (limited to 'java/src/com/android/inputmethod/research')
-rw-r--r--java/src/com/android/inputmethod/research/FeedbackFragment.java39
-rw-r--r--java/src/com/android/inputmethod/research/FixedLogBuffer.java72
-rw-r--r--java/src/com/android/inputmethod/research/LogUnit.java102
-rw-r--r--java/src/com/android/inputmethod/research/MainLogBuffer.java89
-rw-r--r--java/src/com/android/inputmethod/research/ResearchLog.java86
-rw-r--r--java/src/com/android/inputmethod/research/ResearchLogDirectory.java14
-rw-r--r--java/src/com/android/inputmethod/research/ResearchLogger.java235
-rw-r--r--java/src/com/android/inputmethod/research/UploaderService.java25
8 files changed, 319 insertions, 343 deletions
diff --git a/java/src/com/android/inputmethod/research/FeedbackFragment.java b/java/src/com/android/inputmethod/research/FeedbackFragment.java
index 39f9c87a0..a0738292e 100644
--- a/java/src/com/android/inputmethod/research/FeedbackFragment.java
+++ b/java/src/com/android/inputmethod/research/FeedbackFragment.java
@@ -65,12 +65,10 @@ public class FeedbackFragment extends Fragment implements OnClickListener {
mCancelButton.setOnClickListener(this);
if (savedInstanceState != null) {
- Log.d(TAG, "restoring from savedInstanceState");
restoreState(savedInstanceState);
} else {
final Bundle bundle = getActivity().getIntent().getExtras();
if (bundle != null) {
- Log.d(TAG, "restoring from getArguments()");
restoreState(bundle);
}
}
@@ -81,10 +79,7 @@ public class FeedbackFragment extends Fragment implements OnClickListener {
public void onClick(final View view) {
final ResearchLogger researchLogger = ResearchLogger.getInstance();
if (view == mIncludingUserRecordingCheckBox) {
- if (hasUserRecording()) {
- // Remove the recording
- setHasUserRecording(false);
- } else {
+ if (mIncludingUserRecordingCheckBox.isChecked()) {
final Bundle bundle = new Bundle();
onSaveInstanceState(bundle);
@@ -103,9 +98,9 @@ public class FeedbackFragment extends Fragment implements OnClickListener {
R.string.research_feedback_empty_feedback_error_message,
Toast.LENGTH_LONG).show();
} else {
- final boolean isIncludingAccountName = isIncludingAccountName();
- researchLogger.sendFeedback(feedbackContents,
- false /* isIncludingHistory */, isIncludingAccountName, hasUserRecording());
+ final boolean isIncludingAccountName = mIncludingAccountNameCheckBox.isChecked();
+ researchLogger.sendFeedback(feedbackContents, false /* isIncludingHistory */,
+ isIncludingAccountName, mIncludingUserRecordingCheckBox.isChecked());
getActivity().finish();
researchLogger.setFeedbackDialogBundle(null);
researchLogger.onLeavingSendFeedbackDialog();
@@ -125,29 +120,13 @@ public class FeedbackFragment extends Fragment implements OnClickListener {
final String savedFeedbackString = mEditText.getText().toString();
bundle.putString(KEY_FEEDBACK_STRING, savedFeedbackString);
- bundle.putBoolean(KEY_INCLUDE_ACCOUNT_NAME, isIncludingAccountName());
- bundle.putBoolean(KEY_HAS_USER_RECORDING, hasUserRecording());
+ bundle.putBoolean(KEY_INCLUDE_ACCOUNT_NAME, mIncludingAccountNameCheckBox.isChecked());
+ bundle.putBoolean(KEY_HAS_USER_RECORDING, mIncludingUserRecordingCheckBox.isChecked());
}
- public void restoreState(final Bundle bundle) {
+ private void restoreState(final Bundle bundle) {
mEditText.setText(bundle.getString(KEY_FEEDBACK_STRING));
- setIsIncludingAccountName(bundle.getBoolean(KEY_INCLUDE_ACCOUNT_NAME));
- setHasUserRecording(bundle.getBoolean(KEY_HAS_USER_RECORDING));
- }
-
- private boolean hasUserRecording() {
- return mIncludingUserRecordingCheckBox.isChecked();
- }
-
- private void setHasUserRecording(final boolean hasRecording) {
- mIncludingUserRecordingCheckBox.setChecked(hasRecording);
- }
-
- private boolean isIncludingAccountName() {
- return mIncludingAccountNameCheckBox.isChecked();
- }
-
- private void setIsIncludingAccountName(final boolean isIncludingAccountName) {
- mIncludingAccountNameCheckBox.setChecked(isIncludingAccountName);
+ mIncludingAccountNameCheckBox.setChecked(bundle.getBoolean(KEY_INCLUDE_ACCOUNT_NAME));
+ mIncludingUserRecordingCheckBox.setChecked(bundle.getBoolean(KEY_HAS_USER_RECORDING));
}
}
diff --git a/java/src/com/android/inputmethod/research/FixedLogBuffer.java b/java/src/com/android/inputmethod/research/FixedLogBuffer.java
index 78dc59562..8b64de8ae 100644
--- a/java/src/com/android/inputmethod/research/FixedLogBuffer.java
+++ b/java/src/com/android/inputmethod/research/FixedLogBuffer.java
@@ -51,38 +51,36 @@ public class FixedLogBuffer extends LogBuffer {
mNumActualWords = 0;
}
- protected int getNumActualWords() {
- return mNumActualWords;
- }
-
/**
* Adds a new LogUnit to the front of the LIFO queue, evicting existing LogUnit's
* (oldest first) if word capacity is reached.
*/
@Override
public void shiftIn(final LogUnit newLogUnit) {
- if (!newLogUnit.hasWord()) {
- // This LogUnit isn't a word, so it doesn't count toward the word-limit.
+ if (!newLogUnit.hasOneOrMoreWords()) {
+ // This LogUnit doesn't contain any word, so it doesn't count toward the word-limit.
super.shiftIn(newLogUnit);
return;
}
+ final int numWordsIncoming = newLogUnit.getNumWords();
if (mNumActualWords >= mWordCapacity) {
// Give subclass a chance to handle the buffer full condition by shifting out logUnits.
+ // TODO: Tell onBufferFull() how much space it needs to make to avoid forced eviction.
onBufferFull();
// If still full, evict.
if (mNumActualWords >= mWordCapacity) {
- shiftOutWords(1);
+ shiftOutWords(numWordsIncoming);
}
}
super.shiftIn(newLogUnit);
- mNumActualWords++; // Must be a word, or we wouldn't be here.
+ mNumActualWords += numWordsIncoming;
}
@Override
public LogUnit unshiftIn() {
final LogUnit logUnit = super.unshiftIn();
- if (logUnit != null && logUnit.hasWord()) {
- mNumActualWords--;
+ if (logUnit != null && logUnit.hasOneOrMoreWords()) {
+ mNumActualWords -= logUnit.getNumWords();
}
return logUnit;
}
@@ -113,18 +111,28 @@ public class FixedLogBuffer extends LogBuffer {
@Override
public LogUnit shiftOut() {
final LogUnit logUnit = super.shiftOut();
- if (logUnit != null && logUnit.hasWord()) {
- mNumActualWords--;
+ if (logUnit != null && logUnit.hasOneOrMoreWords()) {
+ mNumActualWords -= logUnit.getNumWords();
}
return logUnit;
}
- protected void shiftOutWords(final int numWords) {
- final int targetNumWords = mNumActualWords - numWords;
- final LinkedList<LogUnit> logUnits = getLogUnits();
- while (mNumActualWords > targetNumWords && !logUnits.isEmpty()) {
- shiftOut();
- }
+ /**
+ * Remove LogUnits from the front of the LogBuffer until {@code numWords} have been removed.
+ *
+ * If there are less than {@code numWords} in the buffer, shifts out all {@code LogUnit}s.
+ *
+ * @param numWords the minimum number of words in {@link LogUnit}s to shift out
+ * @return the number of actual words LogUnit}s shifted out
+ */
+ protected int shiftOutWords(final int numWords) {
+ int numWordsShiftedOut = 0;
+ do {
+ final LogUnit logUnit = shiftOut();
+ if (logUnit == null) break;
+ numWordsShiftedOut += logUnit.getNumWords();
+ } while (numWordsShiftedOut < numWords);
+ return numWordsShiftedOut;
}
public void shiftOutAll() {
@@ -136,27 +144,31 @@ public class FixedLogBuffer extends LogBuffer {
}
/**
- * Returns a list of {@link LogUnit}s at the front of the buffer that have associated words. No
- * more than {@code n} LogUnits will have words associated with them. If there are not enough
- * LogUnits in the buffer to meet the word requirement, returns the all LogUnits.
+ * Returns a list of {@link LogUnit}s at the front of the buffer that have words associated with
+ * them.
+ *
+ * There will be no more than {@code n} words in the returned list. So if 2 words are
+ * requested, and the first LogUnit has 3 words, it is not returned. If 2 words are requested,
+ * and the first LogUnit has only 1 word, and the next LogUnit 2 words, only the first LogUnit
+ * is returned. If the first LogUnit has no words associated with it, and the second LogUnit
+ * has three words, then only the first LogUnit (which has no associated words) is returned. If
+ * there are not enough LogUnits in the buffer to meet the word requirement, then all LogUnits
+ * will be returned.
*
* @param n The maximum number of {@link LogUnit}s with words to return.
* @return The list of the {@link LogUnit}s containing the first n words
*/
public ArrayList<LogUnit> peekAtFirstNWords(int n) {
final LinkedList<LogUnit> logUnits = getLogUnits();
- final int length = logUnits.size();
// Allocate space for n*2 logUnits. There will be at least n, one for each word, and
// there may be additional for punctuation, between-word commands, etc. This should be
// enough that reallocation won't be necessary.
- final ArrayList<LogUnit> list = new ArrayList<LogUnit>(n * 2);
- for (int i = 0; i < length && n > 0; i++) {
- final LogUnit logUnit = logUnits.get(i);
- list.add(logUnit);
- if (logUnit.hasWord()) {
- n--;
- }
+ final ArrayList<LogUnit> resultList = new ArrayList<LogUnit>(n * 2);
+ for (final LogUnit logUnit : logUnits) {
+ n -= logUnit.getNumWords();
+ if (n < 0) break;
+ resultList.add(logUnit);
}
- return list;
+ return resultList;
}
}
diff --git a/java/src/com/android/inputmethod/research/LogUnit.java b/java/src/com/android/inputmethod/research/LogUnit.java
index 1c01675bd..cf1388f46 100644
--- a/java/src/com/android/inputmethod/research/LogUnit.java
+++ b/java/src/com/android/inputmethod/research/LogUnit.java
@@ -26,9 +26,10 @@ import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.define.ProductionFlag;
import java.io.IOException;
-import java.io.StringWriter;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
+import java.util.regex.Pattern;
/**
* A group of log statements related to each other.
@@ -49,27 +50,45 @@ public class LogUnit {
private static final boolean DEBUG = false
&& ProductionFlag.USES_DEVELOPMENT_ONLY_DIAGNOSTICS_DEBUG;
+ private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
+ private static final String[] EMPTY_STRING_ARRAY = new String[0];
+
private final ArrayList<LogStatement> mLogStatementList;
private final ArrayList<Object[]> mValuesList;
// Assume that mTimeList is sorted in increasing order. Do not insert null values into
// mTimeList.
private final ArrayList<Long> mTimeList;
- // Word that this LogUnit generates. Should be null if the LogUnit does not generate a genuine
- // word (i.e. separators alone do not count as a word). Should never be empty.
- private String mWord;
+ // Words that this LogUnit generates. Should be null if the data in the LogUnit does not
+ // generate a genuine word (i.e. separators alone do not count as a word). Should never be
+ // empty. Note that if the user types spaces explicitly, then normally mWords should contain
+ // only a single word; it will only contain space-separate multiple words if the user does not
+ // enter a space, and the system enters one automatically.
+ private String mWords;
+ private String[] mWordArray = EMPTY_STRING_ARRAY;
private boolean mMayContainDigit;
private boolean mIsPartOfMegaword;
private boolean mContainsCorrection;
- // mCorrectionType indicates whether the word was corrected at all, and if so, whether it was
- // to a different word or just a "typo" correction. It is considered a "typo" if the final
- // word was listed in the suggestions available the first time the word was gestured or
- // tapped.
+ // mCorrectionType indicates whether the word was corrected at all, and if so, the nature of the
+ // correction.
private int mCorrectionType;
+ // LogUnits start in this state. If a word is entered without being corrected, it will have
+ // this CorrectiontType.
public static final int CORRECTIONTYPE_NO_CORRECTION = 0;
+ // The LogUnit was corrected manually by the user in an unspecified way.
public static final int CORRECTIONTYPE_CORRECTION = 1;
+ // The LogUnit was corrected manually by the user to a word not in the list of suggestions of
+ // the first word typed here. (Note: this is a heuristic value, it may be incorrect, for
+ // example, if the user repositions the cursor).
public static final int CORRECTIONTYPE_DIFFERENT_WORD = 2;
+ // The LogUnit was corrected manually by the user to a word that was in the list of suggestions
+ // of the first word typed here. (Again, a heuristic). It is probably a typo correction.
public static final int CORRECTIONTYPE_TYPO = 3;
+ // TODO: Rather than just tracking the current state, keep a historical record of the LogUnit's
+ // state and statistics. This should include how many times it has been corrected, whether
+ // other LogUnit edits were done between edits to this LogUnit, etc. Also track when a LogUnit
+ // previously contained a word, but was corrected to empty (because it was deleted, and there is
+ // no known replacement).
private SuggestedWords mSuggestedWords;
@@ -117,9 +136,11 @@ public class LogUnit {
* @param researchLog where to publish the contents of this {@code LogUnit}
* @param canIncludePrivateData whether the private data in this {@code LogUnit} should be
* included
+ *
+ * @throws IOException if publication to the log file is not possible
*/
public synchronized void publishTo(final ResearchLog researchLog,
- final boolean canIncludePrivateData) {
+ final boolean canIncludePrivateData) throws IOException {
// Write out any logStatement that passes the privacy filter.
final int size = mLogStatementList.size();
if (size != 0) {
@@ -166,7 +187,7 @@ public class LogUnit {
final LogStatement logStatement;
if (canIncludePrivateData) {
LOGSTATEMENT_LOG_UNIT_BEGIN_WITH_PRIVATE_DATA.outputToLocked(jsonWriter,
- SystemClock.uptimeMillis(), getWord(), getCorrectionType());
+ SystemClock.uptimeMillis(), getWordsAsString(), getCorrectionType());
} else {
LOGSTATEMENT_LOG_UNIT_BEGIN_WITHOUT_PRIVATE_DATA.outputToLocked(jsonWriter,
SystemClock.uptimeMillis());
@@ -181,22 +202,22 @@ public class LogUnit {
}
/**
- * Mark the current logUnit as containing data to generate {@code word}.
+ * Mark the current logUnit as containing data to generate {@code newWords}.
*
* If {@code setWord()} was previously called for this LogUnit, then the method will try to
* determine what kind of correction it is, and update its internal state of the correctionType
* accordingly.
*
- * @param word The word this LogUnit generates. Caller should not pass null or the empty
+ * @param newWords The words this LogUnit generates. Caller should not pass null or the empty
* string.
*/
- public void setWord(final String word) {
- if (hasWord()) {
+ public void setWords(final String newWords) {
+ if (hasOneOrMoreWords()) {
// The word was already set once, and it is now being changed. See if the new word
// is close to the old word. If so, then the change is probably a typo correction.
// If not, the user may have decided to enter a different word, so flag it.
if (mSuggestedWords != null) {
- if (isInSuggestedWords(word, mSuggestedWords)) {
+ if (isInSuggestedWords(newWords, mSuggestedWords)) {
mCorrectionType = CORRECTIONTYPE_TYPO;
} else {
mCorrectionType = CORRECTIONTYPE_DIFFERENT_WORD;
@@ -206,38 +227,71 @@ public class LogUnit {
// Mark it as a generic correction.
mCorrectionType = CORRECTIONTYPE_CORRECTION;
}
+ } else {
+ mCorrectionType = CORRECTIONTYPE_NO_CORRECTION;
}
- mWord = word;
+ mWords = newWords;
+
+ // Update mWordArray
+ mWordArray = (TextUtils.isEmpty(mWords)) ? EMPTY_STRING_ARRAY
+ : WHITESPACE_PATTERN.split(mWords);
+ if (mWordArray.length > 0 && TextUtils.isEmpty(mWordArray[0])) {
+ // Empty string at beginning of array. Must have been whitespace at the start of the
+ // word. Remove the empty string.
+ mWordArray = Arrays.copyOfRange(mWordArray, 1, mWordArray.length);
+ }
+ }
+
+ public String getWordsAsString() {
+ return mWords;
+ }
+
+ /**
+ * Retuns the words generated by the data in this LogUnit.
+ *
+ * The first word may be an empty string, if the data in the LogUnit started by generating
+ * whitespace.
+ *
+ * @return the array of words. an empty list of there are no words associated with this LogUnit.
+ */
+ public String[] getWordsAsStringArray() {
+ return mWordArray;
}
- public String getWord() {
- return mWord;
+ public boolean hasOneOrMoreWords() {
+ return mWordArray.length >= 1;
}
- public boolean hasWord() {
- return mWord != null && !TextUtils.isEmpty(mWord.trim());
+ public int getNumWords() {
+ return mWordArray.length;
}
+ // TODO: Refactor to eliminate getter/setters
public void setMayContainDigit() {
mMayContainDigit = true;
}
+ // TODO: Refactor to eliminate getter/setters
public boolean mayContainDigit() {
return mMayContainDigit;
}
+ // TODO: Refactor to eliminate getter/setters
public void setContainsCorrection() {
mContainsCorrection = true;
}
+ // TODO: Refactor to eliminate getter/setters
public boolean containsCorrection() {
return mContainsCorrection;
}
+ // TODO: Refactor to eliminate getter/setters
public void setCorrectionType(final int correctionType) {
mCorrectionType = correctionType;
}
+ // TODO: Refactor to eliminate getter/setters
public int getCorrectionType() {
return mCorrectionType;
}
@@ -267,7 +321,7 @@ public class LogUnit {
new ArrayList<Object[]>(laterValues),
new ArrayList<Long>(laterTimes),
true /* isPartOfMegaword */);
- newLogUnit.mWord = null;
+ newLogUnit.mWords = null;
newLogUnit.mMayContainDigit = mMayContainDigit;
newLogUnit.mContainsCorrection = mContainsCorrection;
@@ -287,9 +341,9 @@ public class LogUnit {
mLogStatementList.addAll(logUnit.mLogStatementList);
mValuesList.addAll(logUnit.mValuesList);
mTimeList.addAll(logUnit.mTimeList);
- mWord = null;
- if (logUnit.mWord != null) {
- setWord(logUnit.mWord);
+ mWords = null;
+ if (logUnit.mWords != null) {
+ setWords(logUnit.mWords);
}
mMayContainDigit = mMayContainDigit || logUnit.mMayContainDigit;
mContainsCorrection = mContainsCorrection || logUnit.mContainsCorrection;
diff --git a/java/src/com/android/inputmethod/research/MainLogBuffer.java b/java/src/com/android/inputmethod/research/MainLogBuffer.java
index 3303d2bdb..9aa349906 100644
--- a/java/src/com/android/inputmethod/research/MainLogBuffer.java
+++ b/java/src/com/android/inputmethod/research/MainLogBuffer.java
@@ -23,9 +23,9 @@ import com.android.inputmethod.latin.Dictionary;
import com.android.inputmethod.latin.Suggest;
import com.android.inputmethod.latin.define.ProductionFlag;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
-import java.util.Random;
/**
* MainLogBuffer is a FixedLogBuffer that tracks the state of LogUnits to make privacy guarantees.
@@ -100,10 +100,6 @@ public abstract class MainLogBuffer extends FixedLogBuffer {
return mSuggest.getMainDictionary();
}
- public void resetWordCounter() {
- mNumWordsUntilSafeToSample = mNumWordsBetweenNGrams;
- }
-
public void setIsStopping() {
mIsStopping = true;
}
@@ -131,10 +127,7 @@ public abstract class MainLogBuffer extends FixedLogBuffer {
final int length = logUnits.size();
for (int i = 0; i < length; i++) {
final LogUnit logUnit = logUnits.get(i);
- final String word = logUnit.getWord();
- if (word != null) {
- numWordsInLogUnitList++;
- }
+ numWordsInLogUnitList += logUnit.getNumWords();
}
return numWordsInLogUnitList >= minNGramSize;
}
@@ -158,32 +151,34 @@ public abstract class MainLogBuffer extends FixedLogBuffer {
// the complete buffer contents in detail.
int numWordsInLogUnitList = 0;
final int length = logUnits.size();
- for (int i = 0; i < length; i++) {
- final LogUnit logUnit = logUnits.get(i);
- if (!logUnit.hasWord()) {
+ for (final LogUnit logUnit : logUnits) {
+ if (!logUnit.hasOneOrMoreWords()) {
// Digits outside words are a privacy threat.
if (logUnit.mayContainDigit()) {
return false;
}
} else {
- numWordsInLogUnitList++;
- final String word = logUnit.getWord();
- // Words not in the dictionary are a privacy threat.
- if (ResearchLogger.hasLetters(word) && !(dictionary.isValidWord(word))) {
- if (DEBUG) {
- Log.d(TAG, "NOT SAFE!: hasLetters: " + ResearchLogger.hasLetters(word)
- + ", isValid: " + (dictionary.isValidWord(word)));
+ numWordsInLogUnitList += logUnit.getNumWords();
+ final String[] words = logUnit.getWordsAsStringArray();
+ for (final String word : words) {
+ // Words not in the dictionary are a privacy threat.
+ if (ResearchLogger.hasLetters(word) && !(dictionary.isValidWord(word))) {
+ if (DEBUG) {
+ Log.d(TAG, "\"" + word + "\" NOT SAFE!: hasLetters: "
+ + ResearchLogger.hasLetters(word)
+ + ", isValid: " + (dictionary.isValidWord(word)));
+ }
+ return false;
}
- return false;
}
}
}
- // Finally, only return true if the minNGramSize is met.
- return numWordsInLogUnitList >= minNGramSize;
+ // Finally, only return true if the ngram is the right size.
+ return numWordsInLogUnitList == minNGramSize;
}
- public void shiftAndPublishAll() {
+ public void shiftAndPublishAll() throws IOException {
final LinkedList<LogUnit> logUnits = getLogUnits();
while (!logUnits.isEmpty()) {
publishLogUnitsAtFrontOfBuffer();
@@ -192,23 +187,40 @@ public abstract class MainLogBuffer extends FixedLogBuffer {
@Override
protected final void onBufferFull() {
- publishLogUnitsAtFrontOfBuffer();
+ try {
+ publishLogUnitsAtFrontOfBuffer();
+ } catch (final IOException e) {
+ if (DEBUG) {
+ Log.w(TAG, "IOException when publishing front of LogBuffer", e);
+ }
+ }
}
- protected final void publishLogUnitsAtFrontOfBuffer() {
+ protected final void publishLogUnitsAtFrontOfBuffer() throws IOException {
+ // TODO: Refactor this method to require fewer passes through the LogUnits. Should really
+ // require only one pass.
ArrayList<LogUnit> logUnits = peekAtFirstNWords(N_GRAM_SIZE);
if (isSafeNGram(logUnits, N_GRAM_SIZE)) {
// Good n-gram at the front of the buffer. Publish it, disclosing details.
publish(logUnits, true /* canIncludePrivateData */);
shiftOutWords(N_GRAM_SIZE);
- resetWordCounter();
- } else {
- // No good n-gram at front, and buffer is full. Shift out the first word (or if there
- // is none, the existing logUnits).
- logUnits = peekAtFirstNWords(1);
- publish(logUnits, false /* canIncludePrivateData */);
- shiftOutWords(1);
+ mNumWordsUntilSafeToSample = mNumWordsBetweenNGrams;
+ return;
}
+ // No good n-gram at front, and buffer is full. Shift out up through the first logUnit
+ // with associated words (or if there is none, all the existing logUnits).
+ logUnits.clear();
+ LogUnit logUnit = shiftOut();
+ while (logUnit != null) {
+ logUnits.add(logUnit);
+ final int numWords = logUnit.getNumWords();
+ if (numWords > 0) {
+ mNumWordsUntilSafeToSample = Math.max(0, mNumWordsUntilSafeToSample - numWords);
+ break;
+ }
+ logUnit = shiftOut();
+ }
+ publish(logUnits, false /* canIncludePrivateData */);
}
/**
@@ -219,18 +231,19 @@ public abstract class MainLogBuffer extends FixedLogBuffer {
* @param logUnits The list of logUnits to be published.
* @param canIncludePrivateData Whether the private data in the logUnits can be included in
* publication.
+ *
+ * @throws IOException if publication to the log file is not possible
*/
protected abstract void publish(final ArrayList<LogUnit> logUnits,
- final boolean canIncludePrivateData);
+ final boolean canIncludePrivateData) throws IOException;
@Override
- protected void shiftOutWords(final int numWords) {
- final int oldNumActualWords = getNumActualWords();
- super.shiftOutWords(numWords);
- final int numWordsShifted = oldNumActualWords - getNumActualWords();
- mNumWordsUntilSafeToSample -= numWordsShifted;
+ protected int shiftOutWords(final int numWords) {
+ final int numWordsShiftedOut = super.shiftOutWords(numWords);
+ mNumWordsUntilSafeToSample = Math.max(0, mNumWordsUntilSafeToSample - numWordsShiftedOut);
if (DEBUG) {
Log.d(TAG, "wordsUntilSafeToSample now at " + mNumWordsUntilSafeToSample);
}
+ return numWordsShiftedOut;
}
}
diff --git a/java/src/com/android/inputmethod/research/ResearchLog.java b/java/src/com/android/inputmethod/research/ResearchLog.java
index 35a491f2c..3e82139a6 100644
--- a/java/src/com/android/inputmethod/research/ResearchLog.java
+++ b/java/src/com/android/inputmethod/research/ResearchLog.java
@@ -25,6 +25,7 @@ import com.android.inputmethod.latin.define.ProductionFlag;
import java.io.BufferedWriter;
import java.io.File;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
@@ -61,7 +62,11 @@ public class ResearchLog {
/* package */ final File mFile;
private final Context mContext;
- private JsonWriter mJsonWriter = NULL_JSON_WRITER;
+ // Earlier implementations used a dummy JsonWriter that just swallowed what it was given, but
+ // this was tricky to do well, because JsonWriter throws an exception if it is passed more than
+ // one top-level object.
+ private JsonWriter mJsonWriter = null;
+
// true if at least one byte of data has been written out to the log file. This must be
// remembered because JsonWriter requires that calls matching calls to beginObject and
// endObject, as well as beginArray and endArray, and the file is opened lazily, only when
@@ -69,26 +74,6 @@ public class ResearchLog {
// could be caught, but this might suppress other errors.
private boolean mHasWrittenData = false;
- private static final JsonWriter NULL_JSON_WRITER = new JsonWriter(
- new OutputStreamWriter(new NullOutputStream()));
- private static class NullOutputStream extends OutputStream {
- /** {@inheritDoc} */
- @Override
- public void write(byte[] buffer, int offset, int count) {
- // nop
- }
-
- /** {@inheritDoc} */
- @Override
- public void write(byte[] buffer) {
- // nop
- }
-
- @Override
- public void write(int oneByte) {
- }
- }
-
public ResearchLog(final File outputFile, final Context context) {
mExecutor = Executors.newSingleThreadScheduledExecutor();
mFile = outputFile;
@@ -108,16 +93,21 @@ public class ResearchLog {
@Override
public Object call() throws Exception {
try {
- if (mHasWrittenData) {
- mJsonWriter.endArray();
- mHasWrittenData = false;
+ if (mJsonWriter == null) return null;
+ // TODO: This is necessary to avoid an exception. Better would be to not even
+ // open the JsonWriter if the file is not even opened unless there is valid data
+ // to write.
+ if (!mHasWrittenData) {
+ mJsonWriter.beginArray();
}
+ mJsonWriter.endArray();
+ mHasWrittenData = false;
mJsonWriter.flush();
mJsonWriter.close();
if (DEBUG) {
- Log.d(TAG, "wrote log to " + mFile);
+ Log.d(TAG, "closed " + mFile);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
Log.d(TAG, "error when closing ResearchLog:", e);
} finally {
// Marking the file as read-only signals that this log file is ready to be
@@ -158,7 +148,14 @@ public class ResearchLog {
@Override
public Object call() throws Exception {
try {
+ if (mJsonWriter == null) return null;
if (mHasWrittenData) {
+ // TODO: This is necessary to avoid an exception. Better would be to not
+ // even open the JsonWriter if the file is not even opened unless there is
+ // valid data to write.
+ if (!mHasWrittenData) {
+ mJsonWriter.beginArray();
+ }
mJsonWriter.endArray();
mJsonWriter.close();
mHasWrittenData = false;
@@ -207,7 +204,7 @@ public class ResearchLog {
private final Callable<Object> mFlushCallable = new Callable<Object>() {
@Override
public Object call() throws Exception {
- mJsonWriter.flush();
+ if (mJsonWriter != null) mJsonWriter.flush();
return null;
}
};
@@ -253,30 +250,29 @@ public class ResearchLog {
/**
* Return a JsonWriter for this ResearchLog. It is initialized the first time this method is
* called. The cached value is returned in future calls.
+ *
+ * @throws IOException if opening the JsonWriter is not possible
*/
- public JsonWriter getInitializedJsonWriterLocked() {
- if (mJsonWriter != NULL_JSON_WRITER || mFile == null) return mJsonWriter;
+ public JsonWriter getInitializedJsonWriterLocked() throws IOException {
+ if (mJsonWriter != null) return mJsonWriter;
+ if (mFile == null) throw new FileNotFoundException();
try {
final JsonWriter jsonWriter = createJsonWriter(mContext, mFile);
- if (jsonWriter != null) {
- jsonWriter.beginArray();
- mJsonWriter = jsonWriter;
- mHasWrittenData = true;
- }
+ if (jsonWriter == null) throw new IOException("Could not create JsonWriter");
+
+ jsonWriter.beginArray();
+ mJsonWriter = jsonWriter;
+ mHasWrittenData = true;
+ return mJsonWriter;
} catch (final IOException e) {
- Log.w(TAG, "Error in JsonWriter; disabling logging", e);
- try {
- mJsonWriter.close();
- } catch (final IllegalStateException e1) {
- // Assume that this is just the json not being terminated properly.
- // Ignore
- } catch (final IOException e1) {
- Log.w(TAG, "Error in closing JsonWriter; disabling logging", e1);
- } finally {
- mJsonWriter = NULL_JSON_WRITER;
+ if (DEBUG) {
+ Log.w(TAG, "Exception when creating JsonWriter", e);
+ Log.w(TAG, "Closing JsonWriter");
}
+ if (mJsonWriter != null) mJsonWriter.close();
+ mJsonWriter = null;
+ throw e;
}
- return mJsonWriter;
}
/**
diff --git a/java/src/com/android/inputmethod/research/ResearchLogDirectory.java b/java/src/com/android/inputmethod/research/ResearchLogDirectory.java
index 291dea5d0..d156068d6 100644
--- a/java/src/com/android/inputmethod/research/ResearchLogDirectory.java
+++ b/java/src/com/android/inputmethod/research/ResearchLogDirectory.java
@@ -97,15 +97,17 @@ public class ResearchLogDirectory {
}
}
- public File getLogFilePath(final long time) {
- return new File(mFilesDir, getUniqueFilename(LOG_FILENAME_PREFIX, time));
+ public File getLogFilePath(final long time, final long nanoTime) {
+ return new File(mFilesDir, getUniqueFilename(LOG_FILENAME_PREFIX, time, nanoTime));
}
- public File getUserRecordingFilePath(final long time) {
- return new File(mFilesDir, getUniqueFilename(USER_RECORDING_FILENAME_PREFIX, time));
+ public File getUserRecordingFilePath(final long time, final long nanoTime) {
+ return new File(mFilesDir, getUniqueFilename(USER_RECORDING_FILENAME_PREFIX, time,
+ nanoTime));
}
- private static String getUniqueFilename(final String prefix, final long time) {
- return prefix + "-" + time + FILENAME_SUFFIX;
+ private static String getUniqueFilename(final String prefix, final long time,
+ final long nanoTime) {
+ return prefix + "-" + time + "-" + nanoTime + FILENAME_SUFFIX;
}
}
diff --git a/java/src/com/android/inputmethod/research/ResearchLogger.java b/java/src/com/android/inputmethod/research/ResearchLogger.java
index 7a23ddb05..8b8ea21e9 100644
--- a/java/src/com/android/inputmethod/research/ResearchLogger.java
+++ b/java/src/com/android/inputmethod/research/ResearchLogger.java
@@ -118,7 +118,6 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
private static final boolean FEEDBACK_DIALOG_SHOULD_PRESERVE_TEXT_FIELD = false;
/* package */ static boolean sIsLogging = false;
private static final int OUTPUT_FORMAT_VERSION = 5;
- private static final String PREF_USABILITY_STUDY_MODE = "usability_study_mode";
// Whether all words should be recorded, leaving unsampled word between bigrams. Useful for
// testing.
/* package for test */ static final boolean IS_LOGGING_EVERYTHING = false
@@ -150,24 +149,18 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
private static final ResearchLogger sInstance = new ResearchLogger();
private static String sAccountType = null;
private static String sAllowedAccountDomain = null;
- /* package */ ResearchLog mMainResearchLog;
+ private ResearchLog mMainResearchLog; // always non-null after init() is called
// mFeedbackLog records all events for the session, private or not (excepting
// passwords). It is written to permanent storage only if the user explicitly commands
// the system to do so.
// LogUnits are queued in the LogBuffers and published to the ResearchLogs when words are
// complete.
- /* package */ MainLogBuffer mMainLogBuffer;
- // TODO: Remove the feedback log. The feedback log continuously captured user data in case the
- // user wanted to submit it. We now use the mUserRecordingLogBuffer to allow the user to
- // explicitly reproduce a problem.
- /* package */ ResearchLog mFeedbackLog;
- /* package */ LogBuffer mFeedbackLogBuffer;
+ /* package for test */ MainLogBuffer mMainLogBuffer; // always non-null after init() is called
/* package */ ResearchLog mUserRecordingLog;
/* package */ LogBuffer mUserRecordingLogBuffer;
private File mUserRecordingFile = null;
private boolean mIsPasswordView = false;
- private boolean mIsLoggingSuspended = false;
private SharedPreferences mPrefs;
// digits entered by the user are replaced with this codepoint.
@@ -202,15 +195,6 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
private long mSavedDownEventTime;
private Bundle mFeedbackDialogBundle = null;
private boolean mInFeedbackDialog = false;
- // The feedback dialog causes stop() to be called for the keyboard connected to the original
- // window. This is because the feedback dialog must present its own EditText box that displays
- // a keyboard. stop() normally causes mFeedbackLogBuffer, which contains the user's data, to be
- // cleared, and causes mFeedbackLog, which is ready to collect information in case the user
- // wants to upload, to be closed. This is good because we don't need to log information about
- // what the user is typing in the feedback dialog, but bad because this data must be uploaded.
- // Here we save the LogBuffer and Log so the feedback dialog can later access their data.
- private LogBuffer mSavedFeedbackLogBuffer;
- private ResearchLog mSavedFeedbackLog;
private Handler mUserRecordingTimeoutHandler;
private static final long USER_RECORDING_TIMEOUT_MS = 30L * DateUtils.SECOND_IN_MILLIS;
@@ -241,6 +225,9 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
mResearchLogDirectory = new ResearchLogDirectory(mLatinIME);
cleanLogDirectoryIfNeeded(mResearchLogDirectory, System.currentTimeMillis());
+ // Initialize log buffers
+ resetLogBuffers();
+
// Initialize external services
mUploadIntent = new Intent(mLatinIME, UploaderService.class);
mUploadNowIntent = new Intent(mLatinIME, UploaderService.class);
@@ -252,6 +239,35 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
mReplayer.setKeyboardSwitcher(keyboardSwitcher);
}
+ private void resetLogBuffers() {
+ mMainResearchLog = new ResearchLog(mResearchLogDirectory.getLogFilePath(
+ System.currentTimeMillis(), System.nanoTime()), mLatinIME);
+ final int numWordsToIgnore = new Random().nextInt(NUMBER_OF_WORDS_BETWEEN_SAMPLES + 1);
+ mMainLogBuffer = new MainLogBuffer(NUMBER_OF_WORDS_BETWEEN_SAMPLES, numWordsToIgnore,
+ mSuggest) {
+ @Override
+ protected void publish(final ArrayList<LogUnit> logUnits,
+ boolean canIncludePrivateData) {
+ canIncludePrivateData |= IS_LOGGING_EVERYTHING;
+ for (final LogUnit logUnit : logUnits) {
+ if (DEBUG) {
+ final String wordsString = logUnit.getWordsAsString();
+ Log.d(TAG, "onPublish: '" + wordsString
+ + "', hc: " + logUnit.containsCorrection()
+ + ", cipd: " + canIncludePrivateData);
+ }
+ for (final String word : logUnit.getWordsAsStringArray()) {
+ final Dictionary dictionary = getDictionary();
+ mStatistics.recordWordEntered(
+ dictionary != null && dictionary.isValidWord(word),
+ logUnit.containsCorrection());
+ }
+ }
+ publishLogUnits(logUnits, mMainResearchLog, canIncludePrivateData);
+ }
+ };
+ }
+
private void cleanLogDirectoryIfNeeded(final ResearchLogDirectory researchLogDirectory,
final long now) {
final long lastCleanupTime = ResearchSettings.readResearchLastDirCleanupTime(mPrefs);
@@ -376,52 +392,9 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
Log.d(TAG, "start called");
}
maybeShowSplashScreen();
- updateSuspendedState();
requestIndicatorRedraw();
mStatistics.reset();
checkForEmptyEditor();
- if (mFeedbackLogBuffer == null) {
- resetFeedbackLogging();
- }
- if (!isAllowedToLog()) {
- // Log.w(TAG, "not in usability mode; not logging");
- return;
- }
- if (mMainLogBuffer == null) {
- mMainResearchLog = new ResearchLog(mResearchLogDirectory.getLogFilePath(
- System.currentTimeMillis()), mLatinIME);
- final int numWordsToIgnore = new Random().nextInt(NUMBER_OF_WORDS_BETWEEN_SAMPLES + 1);
- mMainLogBuffer = new MainLogBuffer(NUMBER_OF_WORDS_BETWEEN_SAMPLES, numWordsToIgnore,
- mSuggest) {
- @Override
- protected void publish(final ArrayList<LogUnit> logUnits,
- boolean canIncludePrivateData) {
- canIncludePrivateData |= IS_LOGGING_EVERYTHING;
- final int length = logUnits.size();
- for (int i = 0; i < length; i++) {
- final LogUnit logUnit = logUnits.get(i);
- final String word = logUnit.getWord();
- if (word != null && word.length() > 0 && hasLetters(word)) {
- Log.d(TAG, "onPublish: " + word + ", hc: "
- + logUnit.containsCorrection());
- final Dictionary dictionary = getDictionary();
- mStatistics.recordWordEntered(
- dictionary != null && dictionary.isValidWord(word),
- logUnit.containsCorrection());
- }
- }
- if (mMainResearchLog != null) {
- publishLogUnits(logUnits, mMainResearchLog, canIncludePrivateData);
- }
- }
- };
- }
- }
-
- private void resetFeedbackLogging() {
- mFeedbackLog = new ResearchLog(mResearchLogDirectory.getLogFilePath(
- System.currentTimeMillis()), mLatinIME);
- mFeedbackLogBuffer = new FixedLogBuffer(FEEDBACK_WORD_BUFFER_SIZE);
}
/* package */ void stop() {
@@ -431,35 +404,32 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
// Commit mCurrentLogUnit before closing.
commitCurrentLogUnit();
- if (mMainLogBuffer != null) {
- mMainLogBuffer.shiftAndPublishAll();
- logStatistics();
- commitCurrentLogUnit();
- mMainLogBuffer.setIsStopping();
+ try {
mMainLogBuffer.shiftAndPublishAll();
- mMainResearchLog.blockingClose(RESEARCHLOG_CLOSE_TIMEOUT_IN_MS);
- mMainLogBuffer = null;
+ } catch (final IOException e) {
+ Log.w(TAG, "IOException when publishing LogBuffer", e);
}
- if (mFeedbackLogBuffer != null) {
- mFeedbackLog.blockingClose(RESEARCHLOG_CLOSE_TIMEOUT_IN_MS);
- mFeedbackLogBuffer = null;
+ logStatistics();
+ commitCurrentLogUnit();
+ mMainLogBuffer.setIsStopping();
+ try {
+ mMainLogBuffer.shiftAndPublishAll();
+ } catch (final IOException e) {
+ Log.w(TAG, "IOException when publishing LogBuffer", e);
}
+ mMainResearchLog.blockingClose(RESEARCHLOG_CLOSE_TIMEOUT_IN_MS);
+
+ resetLogBuffers();
}
public void abort() {
if (DEBUG) {
Log.d(TAG, "abort called");
}
- if (mMainLogBuffer != null) {
- mMainLogBuffer.clear();
- mMainResearchLog.blockingAbort(RESEARCHLOG_ABORT_TIMEOUT_IN_MS);
- mMainLogBuffer = null;
- }
- if (mFeedbackLogBuffer != null) {
- mFeedbackLogBuffer.clear();
- mFeedbackLog.blockingAbort(RESEARCHLOG_ABORT_TIMEOUT_IN_MS);
- mFeedbackLogBuffer = null;
- }
+ mMainLogBuffer.clear();
+ mMainResearchLog.blockingAbort(RESEARCHLOG_ABORT_TIMEOUT_IN_MS);
+
+ resetLogBuffers();
}
private void restart() {
@@ -467,23 +437,11 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
start();
}
- private long mResumeTime = 0L;
- private void updateSuspendedState() {
- final long time = System.currentTimeMillis();
- if (time > mResumeTime) {
- mIsLoggingSuspended = false;
- }
- }
-
@Override
public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {
if (key == null || prefs == null) {
return;
}
- sIsLogging = prefs.getBoolean(PREF_USABILITY_STUDY_MODE, false);
- if (sIsLogging == false) {
- abort();
- }
requestIndicatorRedraw();
mPrefs = prefs;
prefsChanged(prefs);
@@ -503,12 +461,6 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
saveRecording();
}
mInFeedbackDialog = true;
- mSavedFeedbackLogBuffer = mFeedbackLogBuffer;
- mSavedFeedbackLog = mFeedbackLog;
- // Set the non-saved versions to null so that the stop() caused by switching to the
- // Feedback dialog will not close them.
- mFeedbackLogBuffer = null;
- mFeedbackLog = null;
final Intent intent = new Intent();
intent.setClass(mLatinIME, FeedbackActivity.class);
@@ -545,7 +497,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
mUserRecordingLog.blockingAbort(RESEARCHLOG_ABORT_TIMEOUT_IN_MS);
}
mUserRecordingFile = mResearchLogDirectory.getUserRecordingFilePath(
- System.currentTimeMillis());
+ System.currentTimeMillis(), System.nanoTime());
mUserRecordingLog = new ResearchLog(mUserRecordingFile, mLatinIME);
mUserRecordingLogBuffer = new LogBuffer();
resetRecordingTimer();
@@ -666,12 +618,6 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
new LogStatement("UserFeedback", false, false, "contents", "accountName", "recording");
public void sendFeedback(final String feedbackContents, final boolean includeHistory,
final boolean isIncludingAccountName, final boolean isIncludingRecording) {
- if (mSavedFeedbackLogBuffer == null) {
- return;
- }
- if (!includeHistory) {
- mSavedFeedbackLogBuffer.clear();
- }
String recording = "";
if (isIncludingRecording) {
// Try to read recording from recently written json file
@@ -703,9 +649,13 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
final String accountName = isIncludingAccountName ? getAccountName() : "";
feedbackLogUnit.addLogStatement(LOGSTATEMENT_FEEDBACK, SystemClock.uptimeMillis(),
feedbackContents, accountName, recording);
- mFeedbackLogBuffer.shiftIn(feedbackLogUnit);
- publishLogBuffer(mFeedbackLogBuffer, mSavedFeedbackLog, true /* isIncludingPrivateData */);
- mSavedFeedbackLog.blockingClose(RESEARCHLOG_CLOSE_TIMEOUT_IN_MS);
+
+ final ResearchLog feedbackLog = new ResearchLog(mResearchLogDirectory.getLogFilePath(
+ System.currentTimeMillis(), System.nanoTime()), mLatinIME);
+ final LogBuffer feedbackLogBuffer = new LogBuffer();
+ feedbackLogBuffer.shiftIn(feedbackLogUnit);
+ publishLogBuffer(feedbackLogBuffer, feedbackLog, true /* isIncludingPrivateData */);
+ feedbackLog.blockingClose(RESEARCHLOG_CLOSE_TIMEOUT_IN_MS);
uploadNow();
if (isIncludingRecording && DEBUG_REPLAY_AFTER_FEEDBACK) {
@@ -744,8 +694,8 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
public void initSuggest(final Suggest suggest) {
mSuggest = suggest;
- // MainLogBuffer has out-of-date Suggest object. Need to close it down and create a new
- // one.
+ // MainLogBuffer now has an out-of-date Suggest object. Close down MainLogBuffer and create
+ // a new one.
if (mMainLogBuffer != null) {
stop();
start();
@@ -764,7 +714,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
private boolean isAllowedToLog() {
- return !mIsPasswordView && !mIsLoggingSuspended && sIsLogging && !mInFeedbackDialog;
+ return !mIsPasswordView && sIsLogging && !mInFeedbackDialog;
}
public void requestIndicatorRedraw() {
@@ -813,7 +763,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
// enabled. The dot is actually a zero-width, zero-height rectangle, placed at the
// lower-right corner of the canvas, painted with a non-zero border width.
paint.setStrokeWidth(3);
- canvas.drawRect(width, height, width, height, paint);
+ canvas.drawRect(width - 1, height - 1, width, height, paint);
}
paint.setColor(savedColor);
paint.setStyle(savedStyle);
@@ -852,16 +802,11 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
/* package for test */ void commitCurrentLogUnit() {
if (DEBUG) {
- Log.d(TAG, "commitCurrentLogUnit" + (mCurrentLogUnit.hasWord() ?
- ": " + mCurrentLogUnit.getWord() : ""));
+ Log.d(TAG, "commitCurrentLogUnit" + (mCurrentLogUnit.hasOneOrMoreWords() ?
+ ": " + mCurrentLogUnit.getWordsAsString() : ""));
}
if (!mCurrentLogUnit.isEmpty()) {
- if (mMainLogBuffer != null) {
- mMainLogBuffer.shiftIn(mCurrentLogUnit);
- }
- if (mFeedbackLogBuffer != null) {
- mFeedbackLogBuffer.shiftIn(mCurrentLogUnit);
- }
+ mMainLogBuffer.shiftIn(mCurrentLogUnit);
if (mUserRecordingLogBuffer != null) {
mUserRecordingLogBuffer.shiftIn(mCurrentLogUnit);
}
@@ -886,15 +831,12 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
//
// Note that we don't use mLastLogUnit here, because it only goes one word back and is only
// needed for reverts, which only happen one back.
- if (mMainLogBuffer == null) {
- return;
- }
final LogUnit oldLogUnit = mMainLogBuffer.peekLastLogUnit();
// Check that expected word matches.
if (oldLogUnit != null) {
- final String oldLogUnitWord = oldLogUnit.getWord();
- if (!oldLogUnitWord.equals(expectedWord)) {
+ final String oldLogUnitWords = oldLogUnit.getWordsAsString();
+ if (oldLogUnitWords != null && !oldLogUnitWords.equals(expectedWord)) {
return;
}
}
@@ -910,13 +852,11 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
} else {
mCurrentLogUnit = oldLogUnit;
}
- if (mFeedbackLogBuffer != null) {
- mFeedbackLogBuffer.unshiftIn();
- }
enqueueEvent(LOGSTATEMENT_UNCOMMIT_CURRENT_LOGUNIT);
if (DEBUG) {
Log.d(TAG, "uncommitCurrentLogUnit (dump=" + dumpCurrentLogUnit + ") back to "
- + (mCurrentLogUnit.hasWord() ? ": '" + mCurrentLogUnit.getWord() + "'" : ""));
+ + (mCurrentLogUnit.hasOneOrMoreWords() ? ": '"
+ + mCurrentLogUnit.getWordsAsString() + "'" : ""));
}
}
@@ -941,6 +881,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
final ResearchLog researchLog, final boolean canIncludePrivateData) {
final LogUnit openingLogUnit = new LogUnit();
if (logUnits.isEmpty()) return;
+ if (!isAllowedToLog()) return;
// LogUnits not containing private data, such as contextual data for the log, do not require
// logSegment boundary statements.
if (canIncludePrivateData) {
@@ -950,8 +891,9 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
}
for (LogUnit logUnit : logUnits) {
if (DEBUG) {
- Log.d(TAG, "publishLogBuffer: " + (logUnit.hasWord() ? logUnit.getWord()
- : "<wordless>") + ", correction?: " + logUnit.containsCorrection());
+ Log.d(TAG, "publishLogBuffer: " + (logUnit.hasOneOrMoreWords()
+ ? logUnit.getWordsAsString() : "<wordless>")
+ + ", correction?: " + logUnit.containsCorrection());
}
researchLog.publish(logUnit, canIncludePrivateData);
}
@@ -986,7 +928,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
return;
}
if (word.length() > 0 && hasLetters(word)) {
- mCurrentLogUnit.setWord(word);
+ mCurrentLogUnit.setWords(word);
}
final LogUnit newLogUnit = mCurrentLogUnit.splitByTime(maxTime);
enqueueCommitText(word, isBatchMode);
@@ -1107,7 +1049,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
packageInfo = mLatinIME.getPackageManager().getPackageInfo(mLatinIME.getPackageName(),
0);
final String versionName = packageInfo.versionName;
- return !(developerBuildRegex.matcher(versionName).find());
+ return developerBuildRegex.matcher(versionName).find();
} catch (final NameNotFoundException e) {
Log.e(TAG, "Could not determine package name", e);
return false;
@@ -1373,11 +1315,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
public static void latinIME_promotePhantomSpace() {
final ResearchLogger researchLogger = getInstance();
final LogUnit logUnit;
- if (researchLogger.mMainLogBuffer == null) {
- logUnit = researchLogger.mCurrentLogUnit;
- } else {
- logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
- }
+ logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
researchLogger.enqueueEvent(logUnit, LOGSTATEMENT_LATINIME_PROMOTEPHANTOMSPACE);
}
@@ -1394,11 +1332,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
final String charactersAfterSwap) {
final ResearchLogger researchLogger = getInstance();
final LogUnit logUnit;
- if (researchLogger.mMainLogBuffer == null) {
- logUnit = null;
- } else {
- logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
- }
+ logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
if (logUnit != null) {
researchLogger.enqueueEvent(logUnit, LOGSTATEMENT_LATINIME_SWAPSWAPPERANDSPACE,
originalCharacters, charactersAfterSwap);
@@ -1471,14 +1405,10 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
final ResearchLogger researchLogger = getInstance();
// TODO: Verify that mCurrentLogUnit has been restored and contains the reverted word.
final LogUnit logUnit;
- if (researchLogger.mMainLogBuffer == null) {
- logUnit = null;
- } else {
- logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
- }
+ logUnit = researchLogger.mMainLogBuffer.peekLastLogUnit();
if (originallyTypedWord.length() > 0 && hasLetters(originallyTypedWord)) {
if (logUnit != null) {
- logUnit.setWord(originallyTypedWord);
+ logUnit.setWords(originallyTypedWord);
}
}
researchLogger.enqueueEvent(logUnit != null ? logUnit : researchLogger.mCurrentLogUnit,
@@ -1616,7 +1546,7 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
* Log a call to LatinIME.commitCurrentAutoCorrection().
*
* SystemResponse: The IME has committed an auto-correction. An auto-correction changes the raw
- * text input to another word that the user more likely desired to type.
+ * text input to another word (or words) that the user more likely desired to type.
*/
private static final LogStatement LOGSTATEMENT_LATINIME_COMMITCURRENTAUTOCORRECTION =
new LogStatement("LatinIMECommitCurrentAutoCorrection", true, true, "typedWord",
@@ -1826,6 +1756,9 @@ public class ResearchLogger implements SharedPreferences.OnSharedPreferenceChang
public static void latinIME_onEndBatchInput(final CharSequence enteredText,
final int enteredWordPos, final SuggestedWords suggestedWords) {
final ResearchLogger researchLogger = getInstance();
+ if (!TextUtils.isEmpty(enteredText) && hasLetters(enteredText.toString())) {
+ researchLogger.mCurrentLogUnit.setWords(enteredText.toString());
+ }
researchLogger.enqueueEvent(LOGSTATEMENT_LATINIME_ONENDBATCHINPUT, enteredText,
enteredWordPos);
researchLogger.mCurrentLogUnit.initializeSuggestions(suggestedWords);
diff --git a/java/src/com/android/inputmethod/research/UploaderService.java b/java/src/com/android/inputmethod/research/UploaderService.java
index 6a9717b7c..d2db34927 100644
--- a/java/src/com/android/inputmethod/research/UploaderService.java
+++ b/java/src/com/android/inputmethod/research/UploaderService.java
@@ -22,6 +22,7 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
+import android.os.SystemClock;
import com.android.inputmethod.latin.define.ProductionFlag;
@@ -79,28 +80,14 @@ public final class UploaderService extends IntentService {
*/
public static void cancelAndRescheduleUploadingService(final Context context,
final boolean needsRescheduling) {
- final PendingIntent pendingIntent = getPendingIntentForService(context);
+ final Intent intent = new Intent(context, UploaderService.class);
+ final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
- cancelAnyScheduledServiceAlarm(alarmManager, pendingIntent);
+ alarmManager.cancel(pendingIntent);
if (needsRescheduling) {
- scheduleServiceAlarm(alarmManager, pendingIntent);
+ alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()
+ + UploaderService.RUN_INTERVAL, pendingIntent);
}
}
-
- private static PendingIntent getPendingIntentForService(final Context context) {
- final Intent intent = new Intent(context, UploaderService.class);
- return PendingIntent.getService(context, 0, intent, 0);
- }
-
- private static void cancelAnyScheduledServiceAlarm(final AlarmManager alarmManager,
- final PendingIntent pendingIntent) {
- alarmManager.cancel(pendingIntent);
- }
-
- private static void scheduleServiceAlarm(final AlarmManager alarmManager,
- final PendingIntent pendingIntent) {
- alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, UploaderService.RUN_INTERVAL,
- pendingIntent);
- }
}