LatinIME.java revision 85e397cd1060f3878d9a55373b7409641175179a
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17package com.android.inputmethod.latin; 18 19import static com.android.inputmethod.latin.Constants.ImeOption.FORCE_ASCII; 20import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE; 21import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE_COMPAT; 22 23import android.app.Activity; 24import android.app.AlertDialog; 25import android.content.BroadcastReceiver; 26import android.content.Context; 27import android.content.DialogInterface; 28import android.content.Intent; 29import android.content.IntentFilter; 30import android.content.SharedPreferences; 31import android.content.pm.ApplicationInfo; 32import android.content.res.Configuration; 33import android.content.res.Resources; 34import android.graphics.Rect; 35import android.inputmethodservice.InputMethodService; 36import android.media.AudioManager; 37import android.net.ConnectivityManager; 38import android.os.Debug; 39import android.os.Handler; 40import android.os.HandlerThread; 41import android.os.IBinder; 42import android.os.Message; 43import android.os.SystemClock; 44import android.preference.PreferenceManager; 45import android.text.InputType; 46import android.text.TextUtils; 47import android.util.Log; 48import android.util.PrintWriterPrinter; 49import android.util.Printer; 50import android.view.KeyCharacterMap; 51import android.view.KeyEvent; 52import android.view.View; 53import android.view.ViewGroup.LayoutParams; 54import android.view.Window; 55import android.view.WindowManager; 56import android.view.inputmethod.CompletionInfo; 57import android.view.inputmethod.CorrectionInfo; 58import android.view.inputmethod.EditorInfo; 59import android.view.inputmethod.InputMethodSubtype; 60 61import com.android.inputmethod.accessibility.AccessibilityUtils; 62import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy; 63import com.android.inputmethod.annotations.UsedForTesting; 64import com.android.inputmethod.compat.CompatUtils; 65import com.android.inputmethod.compat.InputMethodServiceCompatUtils; 66import com.android.inputmethod.compat.SuggestionSpanUtils; 67import com.android.inputmethod.keyboard.KeyDetector; 68import com.android.inputmethod.keyboard.Keyboard; 69import com.android.inputmethod.keyboard.KeyboardActionListener; 70import com.android.inputmethod.keyboard.KeyboardId; 71import com.android.inputmethod.keyboard.KeyboardSwitcher; 72import com.android.inputmethod.keyboard.KeyboardView; 73import com.android.inputmethod.keyboard.MainKeyboardView; 74import com.android.inputmethod.latin.LocaleUtils.RunInLocale; 75import com.android.inputmethod.latin.Utils.Stats; 76import com.android.inputmethod.latin.define.ProductionFlag; 77import com.android.inputmethod.latin.suggestions.SuggestionStripView; 78import com.android.inputmethod.research.ResearchLogger; 79 80import java.io.FileDescriptor; 81import java.io.PrintWriter; 82import java.util.ArrayList; 83import java.util.Locale; 84 85/** 86 * Input method implementation for Qwerty'ish keyboard. 87 */ 88public final class LatinIME extends InputMethodService implements KeyboardActionListener, 89 SuggestionStripView.Listener, TargetApplicationGetter.OnTargetApplicationKnownListener, 90 Suggest.SuggestInitializationListener { 91 private static final String TAG = LatinIME.class.getSimpleName(); 92 private static final boolean TRACE = false; 93 private static boolean DEBUG; 94 95 private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; 96 97 // How many continuous deletes at which to start deleting at a higher speed. 98 private static final int DELETE_ACCELERATE_AT = 20; 99 // Key events coming any faster than this are long-presses. 100 private static final int QUICK_PRESS = 200; 101 102 private static final int PENDING_IMS_CALLBACK_DURATION = 800; 103 104 /** 105 * The name of the scheme used by the Package Manager to warn of a new package installation, 106 * replacement or removal. 107 */ 108 private static final String SCHEME_PACKAGE = "package"; 109 110 private static final int SPACE_STATE_NONE = 0; 111 // Double space: the state where the user pressed space twice quickly, which LatinIME 112 // resolved as period-space. Undoing this converts the period to a space. 113 private static final int SPACE_STATE_DOUBLE = 1; 114 // Swap punctuation: the state where a weak space and a punctuation from the suggestion strip 115 // have just been swapped. Undoing this swaps them back; the space is still considered weak. 116 private static final int SPACE_STATE_SWAP_PUNCTUATION = 2; 117 // Weak space: a space that should be swapped only by suggestion strip punctuation. Weak 118 // spaces happen when the user presses space, accepting the current suggestion (whether 119 // it's an auto-correction or not). 120 private static final int SPACE_STATE_WEAK = 3; 121 // Phantom space: a not-yet-inserted space that should get inserted on the next input, 122 // character provided it's not a separator. If it's a separator, the phantom space is dropped. 123 // Phantom spaces happen when a user chooses a word from the suggestion strip. 124 private static final int SPACE_STATE_PHANTOM = 4; 125 126 // Current space state of the input method. This can be any of the above constants. 127 private int mSpaceState; 128 129 private SettingsValues mCurrentSettings; 130 131 private View mExtractArea; 132 private View mKeyPreviewBackingView; 133 private View mSuggestionsContainer; 134 private SuggestionStripView mSuggestionStripView; 135 @UsedForTesting Suggest mSuggest; 136 private CompletionInfo[] mApplicationSpecifiedCompletions; 137 private ApplicationInfo mTargetApplicationInfo; 138 139 private RichInputMethodManager mRichImm; 140 private Resources mResources; 141 private SharedPreferences mPrefs; 142 @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher; 143 private final SubtypeSwitcher mSubtypeSwitcher; 144 private final SubtypeState mSubtypeState = new SubtypeState(); 145 146 private boolean mIsMainDictionaryAvailable; 147 private UserBinaryDictionary mUserDictionary; 148 private UserHistoryDictionary mUserHistoryDictionary; 149 private boolean mIsUserDictionaryAvailable; 150 151 private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 152 private final WordComposer mWordComposer = new WordComposer(); 153 private RichInputConnection mConnection = new RichInputConnection(this); 154 155 // Keep track of the last selection range to decide if we need to show word alternatives 156 private static final int NOT_A_CURSOR_POSITION = -1; 157 private int mLastSelectionStart = NOT_A_CURSOR_POSITION; 158 private int mLastSelectionEnd = NOT_A_CURSOR_POSITION; 159 160 // Whether we are expecting an onUpdateSelection event to fire. If it does when we don't 161 // "expect" it, it means the user actually moved the cursor. 162 private boolean mExpectingUpdateSelection; 163 private int mDeleteCount; 164 private long mLastKeyTime; 165 166 // Member variables for remembering the current device orientation. 167 private int mDisplayOrientation; 168 169 // Object for reacting to adding/removing a dictionary pack. 170 // TODO: The experimental version is not supported by the Dictionary Pack Service yet. 171 private BroadcastReceiver mDictionaryPackInstallReceiver = 172 ProductionFlag.IS_EXPERIMENTAL 173 ? null : new DictionaryPackInstallBroadcastReceiver(this); 174 175 // Keeps track of most recently inserted text (multi-character key) for reverting 176 private String mEnteredText; 177 178 private boolean mIsAutoCorrectionIndicatorOn; 179 180 private AlertDialog mOptionsDialog; 181 182 private final boolean mIsHardwareAcceleratedDrawingEnabled; 183 184 public final UIHandler mHandler = new UIHandler(this); 185 186 public static final class UIHandler extends StaticInnerHandlerWrapper<LatinIME> { 187 private static final int MSG_UPDATE_SHIFT_STATE = 0; 188 private static final int MSG_PENDING_IMS_CALLBACK = 1; 189 private static final int MSG_UPDATE_SUGGESTION_STRIP = 2; 190 private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3; 191 192 private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1; 193 194 private int mDelayUpdateSuggestions; 195 private int mDelayUpdateShiftState; 196 private long mDoubleSpacesTurnIntoPeriodTimeout; 197 private long mDoubleSpaceTimerStart; 198 199 public UIHandler(final LatinIME outerInstance) { 200 super(outerInstance); 201 } 202 203 public void onCreate() { 204 final Resources res = getOuterInstance().getResources(); 205 mDelayUpdateSuggestions = 206 res.getInteger(R.integer.config_delay_update_suggestions); 207 mDelayUpdateShiftState = 208 res.getInteger(R.integer.config_delay_update_shift_state); 209 mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger( 210 R.integer.config_double_spaces_turn_into_period_timeout); 211 } 212 213 @Override 214 public void handleMessage(final Message msg) { 215 final LatinIME latinIme = getOuterInstance(); 216 final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher; 217 switch (msg.what) { 218 case MSG_UPDATE_SUGGESTION_STRIP: 219 latinIme.updateSuggestionStrip(); 220 break; 221 case MSG_UPDATE_SHIFT_STATE: 222 switcher.updateShiftState(); 223 break; 224 case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP: 225 latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords)msg.obj, 226 msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT); 227 break; 228 } 229 } 230 231 public void postUpdateSuggestionStrip() { 232 sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions); 233 } 234 235 public void cancelUpdateSuggestionStrip() { 236 removeMessages(MSG_UPDATE_SUGGESTION_STRIP); 237 } 238 239 public boolean hasPendingUpdateSuggestions() { 240 return hasMessages(MSG_UPDATE_SUGGESTION_STRIP); 241 } 242 243 public void postUpdateShiftState() { 244 removeMessages(MSG_UPDATE_SHIFT_STATE); 245 sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState); 246 } 247 248 public void cancelUpdateShiftState() { 249 removeMessages(MSG_UPDATE_SHIFT_STATE); 250 } 251 252 public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, 253 final boolean dismissGestureFloatingPreviewText) { 254 removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); 255 final int arg1 = dismissGestureFloatingPreviewText 256 ? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT : 0; 257 obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, 0, suggestedWords) 258 .sendToTarget(); 259 } 260 261 public void startDoubleSpacesTimer() { 262 mDoubleSpaceTimerStart = SystemClock.uptimeMillis(); 263 } 264 265 public void cancelDoubleSpacesTimer() { 266 mDoubleSpaceTimerStart = 0; 267 } 268 269 public boolean isAcceptingDoubleSpaces() { 270 return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart 271 < mDoubleSpacesTurnIntoPeriodTimeout; 272 } 273 274 // Working variables for the following methods. 275 private boolean mIsOrientationChanging; 276 private boolean mPendingSuccessiveImsCallback; 277 private boolean mHasPendingStartInput; 278 private boolean mHasPendingFinishInputView; 279 private boolean mHasPendingFinishInput; 280 private EditorInfo mAppliedEditorInfo; 281 282 public void startOrientationChanging() { 283 removeMessages(MSG_PENDING_IMS_CALLBACK); 284 resetPendingImsCallback(); 285 mIsOrientationChanging = true; 286 final LatinIME latinIme = getOuterInstance(); 287 if (latinIme.isInputViewShown()) { 288 latinIme.mKeyboardSwitcher.saveKeyboardState(); 289 } 290 } 291 292 private void resetPendingImsCallback() { 293 mHasPendingFinishInputView = false; 294 mHasPendingFinishInput = false; 295 mHasPendingStartInput = false; 296 } 297 298 private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo, 299 boolean restarting) { 300 if (mHasPendingFinishInputView) 301 latinIme.onFinishInputViewInternal(mHasPendingFinishInput); 302 if (mHasPendingFinishInput) 303 latinIme.onFinishInputInternal(); 304 if (mHasPendingStartInput) 305 latinIme.onStartInputInternal(editorInfo, restarting); 306 resetPendingImsCallback(); 307 } 308 309 public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { 310 if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { 311 // Typically this is the second onStartInput after orientation changed. 312 mHasPendingStartInput = true; 313 } else { 314 if (mIsOrientationChanging && restarting) { 315 // This is the first onStartInput after orientation changed. 316 mIsOrientationChanging = false; 317 mPendingSuccessiveImsCallback = true; 318 } 319 final LatinIME latinIme = getOuterInstance(); 320 executePendingImsCallback(latinIme, editorInfo, restarting); 321 latinIme.onStartInputInternal(editorInfo, restarting); 322 } 323 } 324 325 public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { 326 if (hasMessages(MSG_PENDING_IMS_CALLBACK) 327 && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) { 328 // Typically this is the second onStartInputView after orientation changed. 329 resetPendingImsCallback(); 330 } else { 331 if (mPendingSuccessiveImsCallback) { 332 // This is the first onStartInputView after orientation changed. 333 mPendingSuccessiveImsCallback = false; 334 resetPendingImsCallback(); 335 sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK), 336 PENDING_IMS_CALLBACK_DURATION); 337 } 338 final LatinIME latinIme = getOuterInstance(); 339 executePendingImsCallback(latinIme, editorInfo, restarting); 340 latinIme.onStartInputViewInternal(editorInfo, restarting); 341 mAppliedEditorInfo = editorInfo; 342 } 343 } 344 345 public void onFinishInputView(final boolean finishingInput) { 346 if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { 347 // Typically this is the first onFinishInputView after orientation changed. 348 mHasPendingFinishInputView = true; 349 } else { 350 final LatinIME latinIme = getOuterInstance(); 351 latinIme.onFinishInputViewInternal(finishingInput); 352 mAppliedEditorInfo = null; 353 } 354 } 355 356 public void onFinishInput() { 357 if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { 358 // Typically this is the first onFinishInput after orientation changed. 359 mHasPendingFinishInput = true; 360 } else { 361 final LatinIME latinIme = getOuterInstance(); 362 executePendingImsCallback(latinIme, null, false); 363 latinIme.onFinishInputInternal(); 364 } 365 } 366 } 367 368 static final class SubtypeState { 369 private InputMethodSubtype mLastActiveSubtype; 370 private boolean mCurrentSubtypeUsed; 371 372 public void currentSubtypeUsed() { 373 mCurrentSubtypeUsed = true; 374 } 375 376 public void switchSubtype(final IBinder token, final RichInputMethodManager richImm) { 377 final InputMethodSubtype currentSubtype = richImm.getInputMethodManager() 378 .getCurrentInputMethodSubtype(); 379 final InputMethodSubtype lastActiveSubtype = mLastActiveSubtype; 380 final boolean currentSubtypeUsed = mCurrentSubtypeUsed; 381 if (currentSubtypeUsed) { 382 mLastActiveSubtype = currentSubtype; 383 mCurrentSubtypeUsed = false; 384 } 385 if (currentSubtypeUsed 386 && richImm.checkIfSubtypeBelongsToThisImeAndEnabled(lastActiveSubtype) 387 && !currentSubtype.equals(lastActiveSubtype)) { 388 richImm.setInputMethodAndSubtype(token, lastActiveSubtype); 389 return; 390 } 391 richImm.switchToNextInputMethod(token, true /* onlyCurrentIme */); 392 } 393 } 394 395 public LatinIME() { 396 super(); 397 mSubtypeSwitcher = SubtypeSwitcher.getInstance(); 398 mKeyboardSwitcher = KeyboardSwitcher.getInstance(); 399 mIsHardwareAcceleratedDrawingEnabled = 400 InputMethodServiceCompatUtils.enableHardwareAcceleration(this); 401 Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled); 402 } 403 404 @Override 405 public void onCreate() { 406 mPrefs = PreferenceManager.getDefaultSharedPreferences(this); 407 mResources = getResources(); 408 409 LatinImeLogger.init(this, mPrefs); 410 if (ProductionFlag.IS_EXPERIMENTAL) { 411 ResearchLogger.getInstance().init(this, mPrefs); 412 } 413 RichInputMethodManager.init(this, mPrefs); 414 mRichImm = RichInputMethodManager.getInstance(); 415 SubtypeSwitcher.init(this); 416 KeyboardSwitcher.init(this, mPrefs); 417 AccessibilityUtils.init(this); 418 419 super.onCreate(); 420 421 mHandler.onCreate(); 422 DEBUG = LatinImeLogger.sDBG; 423 424 loadSettings(); 425 initSuggest(); 426 427 mDisplayOrientation = mResources.getConfiguration().orientation; 428 429 // Register to receive ringer mode change and network state change. 430 // Also receive installation and removal of a dictionary pack. 431 final IntentFilter filter = new IntentFilter(); 432 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 433 filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); 434 registerReceiver(mReceiver, filter); 435 436 // TODO: The experimental version is not supported by the Dictionary Pack Service yet. 437 if (!ProductionFlag.IS_EXPERIMENTAL) { 438 final IntentFilter packageFilter = new IntentFilter(); 439 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 440 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 441 packageFilter.addDataScheme(SCHEME_PACKAGE); 442 registerReceiver(mDictionaryPackInstallReceiver, packageFilter); 443 444 final IntentFilter newDictFilter = new IntentFilter(); 445 newDictFilter.addAction( 446 DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION); 447 registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); 448 } 449 } 450 451 // Has to be package-visible for unit tests 452 @UsedForTesting 453 void loadSettings() { 454 // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() 455 // is not guaranteed. It may even be called at the same time on a different thread. 456 if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); 457 final InputAttributes inputAttributes = 458 new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode()); 459 final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { 460 @Override 461 protected SettingsValues job(Resources res) { 462 return new SettingsValues(mPrefs, inputAttributes, LatinIME.this); 463 } 464 }; 465 mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale()); 466 resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary()); 467 } 468 469 // Note that this method is called from a non-UI thread. 470 @Override 471 public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) { 472 mIsMainDictionaryAvailable = isMainDictionaryAvailable; 473 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 474 if (mainKeyboardView != null) { 475 mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable); 476 } 477 } 478 479 private void initSuggest() { 480 final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 481 final String localeStr = subtypeLocale.toString(); 482 483 final ContactsBinaryDictionary oldContactsDictionary; 484 if (mSuggest != null) { 485 oldContactsDictionary = mSuggest.getContactsDictionary(); 486 mSuggest.close(); 487 } else { 488 oldContactsDictionary = null; 489 } 490 mSuggest = new Suggest(this /* Context */, subtypeLocale, 491 this /* SuggestInitializationListener */); 492 if (mCurrentSettings.mCorrectionEnabled) { 493 mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold); 494 } 495 496 mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale); 497 if (ProductionFlag.IS_EXPERIMENTAL) { 498 ResearchLogger.getInstance().initSuggest(mSuggest); 499 } 500 501 mUserDictionary = new UserBinaryDictionary(this, localeStr); 502 mIsUserDictionaryAvailable = mUserDictionary.isEnabled(); 503 mSuggest.setUserDictionary(mUserDictionary); 504 505 resetContactsDictionary(oldContactsDictionary); 506 507 // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() 508 // is not guaranteed. It may even be called at the same time on a different thread. 509 if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); 510 mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs); 511 mSuggest.setUserHistoryDictionary(mUserHistoryDictionary); 512 } 513 514 /** 515 * Resets the contacts dictionary in mSuggest according to the user settings. 516 * 517 * This method takes an optional contacts dictionary to use when the locale hasn't changed 518 * since the contacts dictionary can be opened or closed as necessary depending on the settings. 519 * 520 * @param oldContactsDictionary an optional dictionary to use, or null 521 */ 522 private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) { 523 final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict); 524 525 final ContactsBinaryDictionary dictionaryToUse; 526 if (!shouldSetDictionary) { 527 // Make sure the dictionary is closed. If it is already closed, this is a no-op, 528 // so it's safe to call it anyways. 529 if (null != oldContactsDictionary) oldContactsDictionary.close(); 530 dictionaryToUse = null; 531 } else { 532 final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 533 if (null != oldContactsDictionary) { 534 if (!oldContactsDictionary.mLocale.equals(locale)) { 535 // If the locale has changed then recreate the contacts dictionary. This 536 // allows locale dependent rules for handling bigram name predictions. 537 oldContactsDictionary.close(); 538 dictionaryToUse = new ContactsBinaryDictionary(this, locale); 539 } else { 540 // Make sure the old contacts dictionary is opened. If it is already open, 541 // this is a no-op, so it's safe to call it anyways. 542 oldContactsDictionary.reopen(this); 543 dictionaryToUse = oldContactsDictionary; 544 } 545 } else { 546 dictionaryToUse = new ContactsBinaryDictionary(this, locale); 547 } 548 } 549 550 if (null != mSuggest) { 551 mSuggest.setContactsDictionary(dictionaryToUse); 552 } 553 } 554 555 /* package private */ void resetSuggestMainDict() { 556 final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 557 mSuggest.resetMainDict(this, subtypeLocale, this /* SuggestInitializationListener */); 558 mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale); 559 } 560 561 @Override 562 public void onDestroy() { 563 if (mSuggest != null) { 564 mSuggest.close(); 565 mSuggest = null; 566 } 567 unregisterReceiver(mReceiver); 568 // TODO: The experimental version is not supported by the Dictionary Pack Service yet. 569 if (!ProductionFlag.IS_EXPERIMENTAL) { 570 unregisterReceiver(mDictionaryPackInstallReceiver); 571 } 572 LatinImeLogger.commit(); 573 LatinImeLogger.onDestroy(); 574 super.onDestroy(); 575 } 576 577 @Override 578 public void onConfigurationChanged(final Configuration conf) { 579 // System locale has been changed. Needs to reload keyboard. 580 if (mSubtypeSwitcher.onConfigurationChanged(conf)) { 581 loadKeyboard(); 582 } 583 // If orientation changed while predicting, commit the change 584 if (mDisplayOrientation != conf.orientation) { 585 mDisplayOrientation = conf.orientation; 586 mHandler.startOrientationChanging(); 587 mConnection.beginBatchEdit(); 588 commitTyped(LastComposedWord.NOT_A_SEPARATOR); 589 mConnection.finishComposingText(); 590 mConnection.endBatchEdit(); 591 if (isShowingOptionDialog()) { 592 mOptionsDialog.dismiss(); 593 } 594 } 595 super.onConfigurationChanged(conf); 596 } 597 598 @Override 599 public View onCreateInputView() { 600 return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled); 601 } 602 603 @Override 604 public void setInputView(final View view) { 605 super.setInputView(view); 606 mExtractArea = getWindow().getWindow().getDecorView() 607 .findViewById(android.R.id.extractArea); 608 mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing); 609 mSuggestionsContainer = view.findViewById(R.id.suggestions_container); 610 mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view); 611 if (mSuggestionStripView != null) 612 mSuggestionStripView.setListener(this, view); 613 if (LatinImeLogger.sVISUALDEBUG) { 614 mKeyPreviewBackingView.setBackgroundColor(0x10FF0000); 615 } 616 } 617 618 @Override 619 public void setCandidatesView(final View view) { 620 // To ensure that CandidatesView will never be set. 621 return; 622 } 623 624 @Override 625 public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { 626 mHandler.onStartInput(editorInfo, restarting); 627 } 628 629 @Override 630 public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { 631 mHandler.onStartInputView(editorInfo, restarting); 632 } 633 634 @Override 635 public void onFinishInputView(final boolean finishingInput) { 636 mHandler.onFinishInputView(finishingInput); 637 } 638 639 @Override 640 public void onFinishInput() { 641 mHandler.onFinishInput(); 642 } 643 644 @Override 645 public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) { 646 // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() 647 // is not guaranteed. It may even be called at the same time on a different thread. 648 mSubtypeSwitcher.updateSubtype(subtype); 649 loadKeyboard(); 650 } 651 652 private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { 653 super.onStartInput(editorInfo, restarting); 654 } 655 656 @SuppressWarnings("deprecation") 657 private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { 658 super.onStartInputView(editorInfo, restarting); 659 final KeyboardSwitcher switcher = mKeyboardSwitcher; 660 final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); 661 662 if (editorInfo == null) { 663 Log.e(TAG, "Null EditorInfo in onStartInputView()"); 664 if (LatinImeLogger.sDBG) { 665 throw new NullPointerException("Null EditorInfo in onStartInputView()"); 666 } 667 return; 668 } 669 if (DEBUG) { 670 Log.d(TAG, "onStartInputView: editorInfo:" 671 + String.format("inputType=0x%08x imeOptions=0x%08x", 672 editorInfo.inputType, editorInfo.imeOptions)); 673 Log.d(TAG, "All caps = " 674 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) 675 + ", sentence caps = " 676 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) 677 + ", word caps = " 678 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); 679 } 680 if (ProductionFlag.IS_EXPERIMENTAL) { 681 ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs); 682 } 683 if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { 684 Log.w(TAG, "Deprecated private IME option specified: " 685 + editorInfo.privateImeOptions); 686 Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); 687 } 688 if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { 689 Log.w(TAG, "Deprecated private IME option specified: " 690 + editorInfo.privateImeOptions); 691 Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); 692 } 693 694 mTargetApplicationInfo = 695 TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName); 696 if (null == mTargetApplicationInfo) { 697 new TargetApplicationGetter(this /* context */, this /* listener */) 698 .execute(editorInfo.packageName); 699 } 700 701 LatinImeLogger.onStartInputView(editorInfo); 702 // In landscape mode, this method gets called without the input view being created. 703 if (mainKeyboardView == null) { 704 return; 705 } 706 707 // Forward this event to the accessibility utilities, if enabled. 708 final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); 709 if (accessUtils.isTouchExplorationEnabled()) { 710 accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); 711 } 712 713 final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo); 714 final boolean isDifferentTextField = !restarting || inputTypeChanged; 715 if (isDifferentTextField) { 716 final boolean currentSubtypeEnabled = mSubtypeSwitcher 717 .updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled(); 718 if (!currentSubtypeEnabled) { 719 // Current subtype is disabled. Needs to update subtype and keyboard. 720 final InputMethodSubtype newSubtype = mRichImm.getCurrentInputMethodSubtype( 721 mSubtypeSwitcher.getNoLanguageSubtype()); 722 mSubtypeSwitcher.updateSubtype(newSubtype); 723 loadKeyboard(); 724 } 725 } 726 727 // The EditorInfo might have a flag that affects fullscreen mode. 728 // Note: This call should be done by InputMethodService? 729 updateFullscreenMode(); 730 mApplicationSpecifiedCompletions = null; 731 732 // The app calling setText() has the effect of clearing the composing 733 // span, so we should reset our state unconditionally, even if restarting is true. 734 mEnteredText = null; 735 resetComposingState(true /* alsoResetLastComposedWord */); 736 mDeleteCount = 0; 737 mSpaceState = SPACE_STATE_NONE; 738 739 if (mSuggestionStripView != null) { 740 // This will set the punctuation suggestions if next word suggestion is off; 741 // otherwise it will clear the suggestion strip. 742 setPunctuationSuggestions(); 743 } 744 745 mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart); 746 747 if (isDifferentTextField) { 748 mainKeyboardView.closing(); 749 loadSettings(); 750 751 if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) { 752 mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold); 753 } 754 755 switcher.loadKeyboard(editorInfo, mCurrentSettings); 756 } else if (restarting) { 757 // TODO: Come up with a more comprehensive way to reset the keyboard layout when 758 // a keyboard layout set doesn't get reloaded in this method. 759 switcher.resetKeyboardStateToAlphabet(); 760 // In apps like Talk, we come here when the text is sent and the field gets emptied and 761 // we need to re-evaluate the shift state, but not the whole layout which would be 762 // disruptive. 763 // Space state must be updated before calling updateShiftState 764 switcher.updateShiftState(); 765 } 766 setSuggestionStripShownInternal( 767 isSuggestionsStripVisible(), /* needsInputViewShown */ false); 768 769 mLastSelectionStart = editorInfo.initialSelStart; 770 mLastSelectionEnd = editorInfo.initialSelEnd; 771 772 mHandler.cancelUpdateSuggestionStrip(); 773 mHandler.cancelDoubleSpacesTimer(); 774 775 mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable); 776 mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn, 777 mCurrentSettings.mKeyPreviewPopupDismissDelay); 778 mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled); 779 mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled, 780 mCurrentSettings.mGestureFloatingPreviewTextEnabled); 781 782 if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); 783 } 784 785 // Callback for the TargetApplicationGetter 786 @Override 787 public void onTargetApplicationKnown(final ApplicationInfo info) { 788 mTargetApplicationInfo = info; 789 } 790 791 @Override 792 public void onWindowHidden() { 793 if (ProductionFlag.IS_EXPERIMENTAL) { 794 ResearchLogger.latinIME_onWindowHidden(mLastSelectionStart, mLastSelectionEnd, 795 getCurrentInputConnection()); 796 } 797 super.onWindowHidden(); 798 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 799 if (mainKeyboardView != null) { 800 mainKeyboardView.closing(); 801 } 802 } 803 804 private void onFinishInputInternal() { 805 super.onFinishInput(); 806 807 LatinImeLogger.commit(); 808 if (ProductionFlag.IS_EXPERIMENTAL) { 809 ResearchLogger.getInstance().latinIME_onFinishInputInternal(); 810 } 811 812 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 813 if (mainKeyboardView != null) { 814 mainKeyboardView.closing(); 815 } 816 } 817 818 private void onFinishInputViewInternal(final boolean finishingInput) { 819 super.onFinishInputView(finishingInput); 820 mKeyboardSwitcher.onFinishInputView(); 821 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 822 if (mainKeyboardView != null) { 823 mainKeyboardView.cancelAllMessages(); 824 } 825 // Remove pending messages related to update suggestions 826 mHandler.cancelUpdateSuggestionStrip(); 827 } 828 829 @Override 830 public void onUpdateSelection(final int oldSelStart, final int oldSelEnd, 831 final int newSelStart, final int newSelEnd, 832 final int composingSpanStart, final int composingSpanEnd) { 833 super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, 834 composingSpanStart, composingSpanEnd); 835 if (DEBUG) { 836 Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart 837 + ", ose=" + oldSelEnd 838 + ", lss=" + mLastSelectionStart 839 + ", lse=" + mLastSelectionEnd 840 + ", nss=" + newSelStart 841 + ", nse=" + newSelEnd 842 + ", cs=" + composingSpanStart 843 + ", ce=" + composingSpanEnd); 844 } 845 if (ProductionFlag.IS_EXPERIMENTAL) { 846 final boolean expectingUpdateSelectionFromLogger = 847 ResearchLogger.getAndClearLatinIMEExpectingUpdateSelection(); 848 ResearchLogger.latinIME_onUpdateSelection(mLastSelectionStart, mLastSelectionEnd, 849 oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart, 850 composingSpanEnd, mExpectingUpdateSelection, 851 expectingUpdateSelectionFromLogger, mConnection); 852 if (expectingUpdateSelectionFromLogger) { 853 // TODO: Investigate. Quitting now sounds wrong - we won't do the resetting work 854 return; 855 } 856 } 857 858 // TODO: refactor the following code to be less contrived. 859 // "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means 860 // that the cursor is not at the end of the composing span, or there is a selection. 861 // "mLastSelectionStart != newSelStart" means that the cursor is not in the same place 862 // as last time we were called (if there is a selection, it means the start hasn't 863 // changed, so it's the end that did). 864 final boolean selectionChanged = (newSelStart != composingSpanEnd 865 || newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart; 866 // if composingSpanStart and composingSpanEnd are -1, it means there is no composing 867 // span in the view - we can use that to narrow down whether the cursor was moved 868 // by us or not. If we are composing a word but there is no composing span, then 869 // we know for sure the cursor moved while we were composing and we should reset 870 // the state. 871 final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1; 872 if (!mExpectingUpdateSelection 873 && !mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart)) { 874 // TAKE CARE: there is a race condition when we enter this test even when the user 875 // did not explicitly move the cursor. This happens when typing fast, where two keys 876 // turn this flag on in succession and both onUpdateSelection() calls arrive after 877 // the second one - the first call successfully avoids this test, but the second one 878 // enters. For the moment we rely on noComposingSpan to further reduce the impact. 879 880 // TODO: the following is probably better done in resetEntireInputState(). 881 // it should only happen when the cursor moved, and the very purpose of the 882 // test below is to narrow down whether this happened or not. Likewise with 883 // the call to updateShiftState. 884 // We set this to NONE because after a cursor move, we don't want the space 885 // state-related special processing to kick in. 886 mSpaceState = SPACE_STATE_NONE; 887 888 if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) { 889 // If we are composing a word and moving the cursor, we would want to set a 890 // suggestion span for recorrection to work correctly. Unfortunately, that 891 // would involve the keyboard committing some new text, which would move the 892 // cursor back to where it was. Latin IME could then fix the position of the cursor 893 // again, but the asynchronous nature of the calls results in this wreaking havoc 894 // with selection on double tap and the like. 895 // Another option would be to send suggestions each time we set the composing 896 // text, but that is probably too expensive to do, so we decided to leave things 897 // as is. 898 resetEntireInputState(newSelStart); 899 } 900 901 mKeyboardSwitcher.updateShiftState(); 902 } 903 mExpectingUpdateSelection = false; 904 // TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not 905 // here. It would probably be too expensive to call directly here but we may want to post a 906 // message to delay it. The point would be to unify behavior between backspace to the 907 // end of a word and manually put the pointer at the end of the word. 908 909 // Make a note of the cursor position 910 mLastSelectionStart = newSelStart; 911 mLastSelectionEnd = newSelEnd; 912 mSubtypeState.currentSubtypeUsed(); 913 } 914 915 /** 916 * This is called when the user has clicked on the extracted text view, 917 * when running in fullscreen mode. The default implementation hides 918 * the suggestions view when this happens, but only if the extracted text 919 * editor has a vertical scroll bar because its text doesn't fit. 920 * Here we override the behavior due to the possibility that a re-correction could 921 * cause the suggestions strip to disappear and re-appear. 922 */ 923 @Override 924 public void onExtractedTextClicked() { 925 if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return; 926 927 super.onExtractedTextClicked(); 928 } 929 930 /** 931 * This is called when the user has performed a cursor movement in the 932 * extracted text view, when it is running in fullscreen mode. The default 933 * implementation hides the suggestions view when a vertical movement 934 * happens, but only if the extracted text editor has a vertical scroll bar 935 * because its text doesn't fit. 936 * Here we override the behavior due to the possibility that a re-correction could 937 * cause the suggestions strip to disappear and re-appear. 938 */ 939 @Override 940 public void onExtractedCursorMovement(final int dx, final int dy) { 941 if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return; 942 943 super.onExtractedCursorMovement(dx, dy); 944 } 945 946 @Override 947 public void hideWindow() { 948 LatinImeLogger.commit(); 949 mKeyboardSwitcher.onHideWindow(); 950 951 if (TRACE) Debug.stopMethodTracing(); 952 if (mOptionsDialog != null && mOptionsDialog.isShowing()) { 953 mOptionsDialog.dismiss(); 954 mOptionsDialog = null; 955 } 956 super.hideWindow(); 957 } 958 959 @Override 960 public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) { 961 if (DEBUG) { 962 Log.i(TAG, "Received completions:"); 963 if (applicationSpecifiedCompletions != null) { 964 for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { 965 Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); 966 } 967 } 968 } 969 if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return; 970 mApplicationSpecifiedCompletions = applicationSpecifiedCompletions; 971 if (applicationSpecifiedCompletions == null) { 972 clearSuggestionStrip(); 973 if (ProductionFlag.IS_EXPERIMENTAL) { 974 ResearchLogger.latinIME_onDisplayCompletions(null); 975 } 976 return; 977 } 978 979 final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords = 980 SuggestedWords.getFromApplicationSpecifiedCompletions( 981 applicationSpecifiedCompletions); 982 final SuggestedWords suggestedWords = new SuggestedWords( 983 applicationSuggestedWords, 984 false /* typedWordValid */, 985 false /* hasAutoCorrectionCandidate */, 986 false /* isPunctuationSuggestions */, 987 false /* isObsoleteSuggestions */, 988 false /* isPrediction */); 989 // When in fullscreen mode, show completions generated by the application 990 final boolean isAutoCorrection = false; 991 setSuggestionStrip(suggestedWords, isAutoCorrection); 992 setAutoCorrectionIndicator(isAutoCorrection); 993 // TODO: is this the right thing to do? What should we auto-correct to in 994 // this case? This says to keep whatever the user typed. 995 mWordComposer.setAutoCorrection(mWordComposer.getTypedWord()); 996 setSuggestionStripShown(true); 997 if (ProductionFlag.IS_EXPERIMENTAL) { 998 ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions); 999 } 1000 } 1001 1002 private void setSuggestionStripShownInternal(final boolean shown, 1003 final boolean needsInputViewShown) { 1004 // TODO: Modify this if we support suggestions with hard keyboard 1005 if (onEvaluateInputViewShown() && mSuggestionsContainer != null) { 1006 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1007 final boolean inputViewShown = (mainKeyboardView != null) 1008 ? mainKeyboardView.isShown() : false; 1009 final boolean shouldShowSuggestions = shown 1010 && (needsInputViewShown ? inputViewShown : true); 1011 if (isFullscreenMode()) { 1012 mSuggestionsContainer.setVisibility( 1013 shouldShowSuggestions ? View.VISIBLE : View.GONE); 1014 } else { 1015 mSuggestionsContainer.setVisibility( 1016 shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE); 1017 } 1018 } 1019 } 1020 1021 private void setSuggestionStripShown(final boolean shown) { 1022 setSuggestionStripShownInternal(shown, /* needsInputViewShown */true); 1023 } 1024 1025 private int getAdjustedBackingViewHeight() { 1026 final int currentHeight = mKeyPreviewBackingView.getHeight(); 1027 if (currentHeight > 0) { 1028 return currentHeight; 1029 } 1030 1031 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1032 if (mainKeyboardView == null) { 1033 return 0; 1034 } 1035 final int keyboardHeight = mainKeyboardView.getHeight(); 1036 final int suggestionsHeight = mSuggestionsContainer.getHeight(); 1037 final int displayHeight = mResources.getDisplayMetrics().heightPixels; 1038 final Rect rect = new Rect(); 1039 mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect); 1040 final int notificationBarHeight = rect.top; 1041 final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight 1042 - keyboardHeight; 1043 1044 final LayoutParams params = mKeyPreviewBackingView.getLayoutParams(); 1045 params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight); 1046 mKeyPreviewBackingView.setLayoutParams(params); 1047 return params.height; 1048 } 1049 1050 @Override 1051 public void onComputeInsets(final InputMethodService.Insets outInsets) { 1052 super.onComputeInsets(outInsets); 1053 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1054 if (mainKeyboardView == null || mSuggestionsContainer == null) { 1055 return; 1056 } 1057 final int adjustedBackingHeight = getAdjustedBackingViewHeight(); 1058 final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE); 1059 final int backingHeight = backingGone ? 0 : adjustedBackingHeight; 1060 // In fullscreen mode, the height of the extract area managed by InputMethodService should 1061 // be considered. 1062 // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}. 1063 final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0; 1064 final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0 1065 : mSuggestionsContainer.getHeight(); 1066 final int extraHeight = extractHeight + backingHeight + suggestionsHeight; 1067 int touchY = extraHeight; 1068 // Need to set touchable region only if input view is being shown 1069 if (mainKeyboardView.isShown()) { 1070 if (mSuggestionsContainer.getVisibility() == View.VISIBLE) { 1071 touchY -= suggestionsHeight; 1072 } 1073 final int touchWidth = mainKeyboardView.getWidth(); 1074 final int touchHeight = mainKeyboardView.getHeight() + extraHeight 1075 // Extend touchable region below the keyboard. 1076 + EXTENDED_TOUCHABLE_REGION_HEIGHT; 1077 outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; 1078 outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight); 1079 } 1080 outInsets.contentTopInsets = touchY; 1081 outInsets.visibleTopInsets = touchY; 1082 } 1083 1084 @Override 1085 public boolean onEvaluateFullscreenMode() { 1086 // Reread resource value here, because this method is called by framework anytime as needed. 1087 final boolean isFullscreenModeAllowed = 1088 mCurrentSettings.isFullscreenModeAllowed(getResources()); 1089 if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) { 1090 // TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI 1091 // implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI 1092 // without NO_FULLSCREEN doesn't work as expected. Because of this we need this 1093 // hack for now. Let's get rid of this once the framework gets fixed. 1094 final EditorInfo ei = getCurrentInputEditorInfo(); 1095 return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0)); 1096 } else { 1097 return false; 1098 } 1099 } 1100 1101 @Override 1102 public void updateFullscreenMode() { 1103 super.updateFullscreenMode(); 1104 1105 if (mKeyPreviewBackingView == null) return; 1106 // In fullscreen mode, no need to have extra space to show the key preview. 1107 // If not, we should have extra space above the keyboard to show the key preview. 1108 mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE); 1109 } 1110 1111 // This will reset the whole input state to the starting state. It will clear 1112 // the composing word, reset the last composed word, tell the inputconnection about it. 1113 private void resetEntireInputState(final int newCursorPosition) { 1114 resetComposingState(true /* alsoResetLastComposedWord */); 1115 if (mCurrentSettings.mBigramPredictionEnabled) { 1116 clearSuggestionStrip(); 1117 } else { 1118 setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false); 1119 } 1120 mConnection.resetCachesUponCursorMove(newCursorPosition); 1121 } 1122 1123 private void resetComposingState(final boolean alsoResetLastComposedWord) { 1124 mWordComposer.reset(); 1125 if (alsoResetLastComposedWord) 1126 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 1127 } 1128 1129 private void commitTyped(final String separatorString) { 1130 if (!mWordComposer.isComposingWord()) return; 1131 final String typedWord = mWordComposer.getTypedWord(); 1132 if (typedWord.length() > 0) { 1133 commitChosenWord(typedWord, LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, 1134 separatorString); 1135 } 1136 } 1137 1138 // Called from the KeyboardSwitcher which needs to know auto caps state to display 1139 // the right layout. 1140 public int getCurrentAutoCapsState() { 1141 if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF; 1142 1143 final EditorInfo ei = getCurrentInputEditorInfo(); 1144 if (ei == null) return Constants.TextUtils.CAP_MODE_OFF; 1145 final int inputType = ei.inputType; 1146 // Warning: this depends on mSpaceState, which may not be the most current value. If 1147 // mSpaceState gets updated later, whoever called this may need to be told about it. 1148 return mConnection.getCursorCapsMode(inputType, mSubtypeSwitcher.getCurrentSubtypeLocale(), 1149 SPACE_STATE_PHANTOM == mSpaceState); 1150 } 1151 1152 // Factor in auto-caps and manual caps and compute the current caps mode. 1153 private int getActualCapsMode() { 1154 final int keyboardShiftMode = mKeyboardSwitcher.getKeyboardShiftMode(); 1155 if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) return keyboardShiftMode; 1156 final int auto = getCurrentAutoCapsState(); 1157 if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) { 1158 return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED; 1159 } 1160 if (0 != auto) return WordComposer.CAPS_MODE_AUTO_SHIFTED; 1161 return WordComposer.CAPS_MODE_OFF; 1162 } 1163 1164 private void swapSwapperAndSpace() { 1165 CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0); 1166 // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called. 1167 if (lastTwo != null && lastTwo.length() == 2 1168 && lastTwo.charAt(0) == Constants.CODE_SPACE) { 1169 mConnection.deleteSurroundingText(2, 0); 1170 mConnection.commitText(lastTwo.charAt(1) + " ", 1); 1171 if (ProductionFlag.IS_EXPERIMENTAL) { 1172 ResearchLogger.latinIME_swapSwapperAndSpace(); 1173 } 1174 mKeyboardSwitcher.updateShiftState(); 1175 } 1176 } 1177 1178 private boolean maybeDoubleSpace() { 1179 if (!mCurrentSettings.mCorrectionEnabled) return false; 1180 if (!mHandler.isAcceptingDoubleSpaces()) return false; 1181 final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0); 1182 if (lastThree != null && lastThree.length() == 3 1183 && canBeFollowedByPeriod(lastThree.charAt(0)) 1184 && lastThree.charAt(1) == Constants.CODE_SPACE 1185 && lastThree.charAt(2) == Constants.CODE_SPACE) { 1186 mHandler.cancelDoubleSpacesTimer(); 1187 mConnection.deleteSurroundingText(2, 0); 1188 mConnection.commitText(". ", 1); 1189 mKeyboardSwitcher.updateShiftState(); 1190 return true; 1191 } 1192 return false; 1193 } 1194 1195 private static boolean canBeFollowedByPeriod(final int codePoint) { 1196 // TODO: Check again whether there really ain't a better way to check this. 1197 // TODO: This should probably be language-dependant... 1198 return Character.isLetterOrDigit(codePoint) 1199 || codePoint == Constants.CODE_SINGLE_QUOTE 1200 || codePoint == Constants.CODE_DOUBLE_QUOTE 1201 || codePoint == Constants.CODE_CLOSING_PARENTHESIS 1202 || codePoint == Constants.CODE_CLOSING_SQUARE_BRACKET 1203 || codePoint == Constants.CODE_CLOSING_CURLY_BRACKET 1204 || codePoint == Constants.CODE_CLOSING_ANGLE_BRACKET; 1205 } 1206 1207 // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is 1208 // pressed. 1209 @Override 1210 public boolean addWordToUserDictionary(final String word) { 1211 mUserDictionary.addWordToUserDictionary(word, 128); 1212 return true; 1213 } 1214 1215 private static boolean isAlphabet(final int code) { 1216 return Character.isLetter(code); 1217 } 1218 1219 private void onSettingsKeyPressed() { 1220 if (isShowingOptionDialog()) return; 1221 showSubtypeSelectorAndSettings(); 1222 } 1223 1224 // Virtual codes representing custom requests. These are used in onCustomRequest() below. 1225 public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1; 1226 1227 @Override 1228 public boolean onCustomRequest(final int requestCode) { 1229 if (isShowingOptionDialog()) return false; 1230 switch (requestCode) { 1231 case CODE_SHOW_INPUT_METHOD_PICKER: 1232 if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { 1233 mRichImm.getInputMethodManager().showInputMethodPicker(); 1234 return true; 1235 } 1236 return false; 1237 } 1238 return false; 1239 } 1240 1241 private boolean isShowingOptionDialog() { 1242 return mOptionsDialog != null && mOptionsDialog.isShowing(); 1243 } 1244 1245 private static int getActionId(final Keyboard keyboard) { 1246 return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE; 1247 } 1248 1249 private void performEditorAction(final int actionId) { 1250 mConnection.performEditorAction(actionId); 1251 } 1252 1253 // TODO: Revise the language switch key behavior to make it much smarter and more reasonable. 1254 private void handleLanguageSwitchKey() { 1255 final IBinder token = getWindow().getWindow().getAttributes().token; 1256 if (mCurrentSettings.mIncludesOtherImesInLanguageSwitchList) { 1257 mRichImm.switchToNextInputMethod(token, false /* onlyCurrentIme */); 1258 return; 1259 } 1260 mSubtypeState.switchSubtype(token, mRichImm); 1261 } 1262 1263 private void sendDownUpKeyEventForBackwardCompatibility(final int code) { 1264 final long eventTime = SystemClock.uptimeMillis(); 1265 mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime, 1266 KeyEvent.ACTION_DOWN, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1267 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1268 mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, 1269 KeyEvent.ACTION_UP, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 1270 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); 1271 } 1272 1273 private void sendKeyCodePoint(final int code) { 1274 // TODO: Remove this special handling of digit letters. 1275 // For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}. 1276 if (code >= '0' && code <= '9') { 1277 sendDownUpKeyEventForBackwardCompatibility(code - '0' + KeyEvent.KEYCODE_0); 1278 if (ProductionFlag.IS_EXPERIMENTAL) { 1279 ResearchLogger.latinIME_sendKeyCodePoint(code); 1280 } 1281 return; 1282 } 1283 1284 // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because 1285 // we want to be able to compile against the Ice Cream Sandwich SDK. 1286 if (Constants.CODE_ENTER == code && mTargetApplicationInfo != null 1287 && mTargetApplicationInfo.targetSdkVersion < 16) { 1288 // Backward compatibility mode. Before Jelly bean, the keyboard would simulate 1289 // a hardware keyboard event on pressing enter or delete. This is bad for many 1290 // reasons (there are race conditions with commits) but some applications are 1291 // relying on this behavior so we continue to support it for older apps. 1292 sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_ENTER); 1293 } else { 1294 final String text = new String(new int[] { code }, 0, 1); 1295 mConnection.commitText(text, text.length()); 1296 } 1297 } 1298 1299 // Implementation of {@link KeyboardActionListener}. 1300 @Override 1301 public void onCodeInput(final int primaryCode, final int x, final int y) { 1302 final long when = SystemClock.uptimeMillis(); 1303 if (primaryCode != Constants.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { 1304 mDeleteCount = 0; 1305 } 1306 mLastKeyTime = when; 1307 mConnection.beginBatchEdit(); 1308 final KeyboardSwitcher switcher = mKeyboardSwitcher; 1309 // The space state depends only on the last character pressed and its own previous 1310 // state. Here, we revert the space state to neutral if the key is actually modifying 1311 // the input contents (any non-shift key), which is what we should do for 1312 // all inputs that do not result in a special state. Each character handling is then 1313 // free to override the state as they see fit. 1314 final int spaceState = mSpaceState; 1315 if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false; 1316 1317 // TODO: Consolidate the double space timer, mLastKeyTime, and the space state. 1318 if (primaryCode != Constants.CODE_SPACE) { 1319 mHandler.cancelDoubleSpacesTimer(); 1320 } 1321 1322 boolean didAutoCorrect = false; 1323 switch (primaryCode) { 1324 case Constants.CODE_DELETE: 1325 mSpaceState = SPACE_STATE_NONE; 1326 handleBackspace(spaceState); 1327 mDeleteCount++; 1328 mExpectingUpdateSelection = true; 1329 LatinImeLogger.logOnDelete(x, y); 1330 break; 1331 case Constants.CODE_SHIFT: 1332 case Constants.CODE_SWITCH_ALPHA_SYMBOL: 1333 // Shift and symbol key is handled in onPressKey() and onReleaseKey(). 1334 break; 1335 case Constants.CODE_SETTINGS: 1336 onSettingsKeyPressed(); 1337 break; 1338 case Constants.CODE_SHORTCUT: 1339 mSubtypeSwitcher.switchToShortcutIME(this); 1340 break; 1341 case Constants.CODE_ACTION_ENTER: 1342 performEditorAction(getActionId(switcher.getKeyboard())); 1343 break; 1344 case Constants.CODE_ACTION_NEXT: 1345 performEditorAction(EditorInfo.IME_ACTION_NEXT); 1346 break; 1347 case Constants.CODE_ACTION_PREVIOUS: 1348 performEditorAction(EditorInfo.IME_ACTION_PREVIOUS); 1349 break; 1350 case Constants.CODE_LANGUAGE_SWITCH: 1351 handleLanguageSwitchKey(); 1352 break; 1353 case Constants.CODE_RESEARCH: 1354 if (ProductionFlag.IS_EXPERIMENTAL) { 1355 ResearchLogger.getInstance().onResearchKeySelected(this); 1356 } 1357 break; 1358 default: 1359 mSpaceState = SPACE_STATE_NONE; 1360 if (mCurrentSettings.isWordSeparator(primaryCode)) { 1361 didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState); 1362 } else { 1363 if (SPACE_STATE_PHANTOM == spaceState) { 1364 if (ProductionFlag.IS_INTERNAL) { 1365 if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) { 1366 Stats.onAutoCorrection( 1367 "", mWordComposer.getTypedWord(), " ", mWordComposer); 1368 } 1369 } 1370 commitTyped(LastComposedWord.NOT_A_SEPARATOR); 1371 } 1372 final int keyX, keyY; 1373 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1374 if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) { 1375 keyX = x; 1376 keyY = y; 1377 } else { 1378 keyX = Constants.NOT_A_COORDINATE; 1379 keyY = Constants.NOT_A_COORDINATE; 1380 } 1381 handleCharacter(primaryCode, keyX, keyY, spaceState); 1382 } 1383 mExpectingUpdateSelection = true; 1384 break; 1385 } 1386 switcher.onCodeInput(primaryCode); 1387 // Reset after any single keystroke, except shift and symbol-shift 1388 if (!didAutoCorrect && primaryCode != Constants.CODE_SHIFT 1389 && primaryCode != Constants.CODE_SWITCH_ALPHA_SYMBOL) 1390 mLastComposedWord.deactivate(); 1391 if (Constants.CODE_DELETE != primaryCode) { 1392 mEnteredText = null; 1393 } 1394 mConnection.endBatchEdit(); 1395 if (ProductionFlag.IS_EXPERIMENTAL) { 1396 ResearchLogger.latinIME_onCodeInput(primaryCode, x, y); 1397 } 1398 } 1399 1400 // Called from PointerTracker through the KeyboardActionListener interface 1401 @Override 1402 public void onTextInput(final String rawText) { 1403 mConnection.beginBatchEdit(); 1404 if (mWordComposer.isComposingWord()) { 1405 commitCurrentAutoCorrection(rawText.toString()); 1406 } else { 1407 resetComposingState(true /* alsoResetLastComposedWord */); 1408 } 1409 mHandler.postUpdateSuggestionStrip(); 1410 final String text = specificTldProcessingOnTextInput(rawText); 1411 if (SPACE_STATE_PHANTOM == mSpaceState) { 1412 promotePhantomSpace(); 1413 } 1414 mConnection.commitText(text, 1); 1415 mConnection.endBatchEdit(); 1416 // Space state must be updated before calling updateShiftState 1417 mSpaceState = SPACE_STATE_NONE; 1418 mKeyboardSwitcher.updateShiftState(); 1419 mKeyboardSwitcher.onCodeInput(Constants.CODE_OUTPUT_TEXT); 1420 mEnteredText = text; 1421 } 1422 1423 @Override 1424 public void onStartBatchInput() { 1425 BatchInputUpdater.getInstance().onStartBatchInput(); 1426 mConnection.beginBatchEdit(); 1427 if (mWordComposer.isComposingWord()) { 1428 if (ProductionFlag.IS_INTERNAL) { 1429 if (mWordComposer.isBatchMode()) { 1430 Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer); 1431 } 1432 } 1433 if (mWordComposer.size() <= 1) { 1434 // We auto-correct the previous (typed, not gestured) string iff it's one character 1435 // long. The reason for this is, even in the middle of gesture typing, you'll still 1436 // tap one-letter words and you want them auto-corrected (typically, "i" in English 1437 // should become "I"). However for any longer word, we assume that the reason for 1438 // tapping probably is that the word you intend to type is not in the dictionary, 1439 // so we do not attempt to correct, on the assumption that if that was a dictionary 1440 // word, the user would probably have gestured instead. 1441 commitCurrentAutoCorrection(LastComposedWord.NOT_A_SEPARATOR); 1442 } else { 1443 commitTyped(LastComposedWord.NOT_A_SEPARATOR); 1444 } 1445 mExpectingUpdateSelection = true; 1446 // The following is necessary for the case where the user typed something but didn't 1447 // manual pick it and didn't input any separator. 1448 mSpaceState = SPACE_STATE_PHANTOM; 1449 } else { 1450 final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor(); 1451 // TODO: reverse this logic. We should have the means to determine whether a character 1452 // should usually be followed by a space, and it should be more readable. 1453 if (Constants.NOT_A_CODE != codePointBeforeCursor 1454 && !Character.isWhitespace(codePointBeforeCursor) 1455 && !mCurrentSettings.isPhantomSpacePromotingSymbol(codePointBeforeCursor) 1456 && !mCurrentSettings.isWeakSpaceStripper(codePointBeforeCursor)) { 1457 mSpaceState = SPACE_STATE_PHANTOM; 1458 } 1459 } 1460 mConnection.endBatchEdit(); 1461 mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode()); 1462 } 1463 1464 private static final class BatchInputUpdater implements Handler.Callback { 1465 private final Handler mHandler; 1466 private LatinIME mLatinIme; 1467 private boolean mInBatchInput; // synchornized using "this". 1468 1469 private BatchInputUpdater() { 1470 final HandlerThread handlerThread = new HandlerThread( 1471 BatchInputUpdater.class.getSimpleName()); 1472 handlerThread.start(); 1473 mHandler = new Handler(handlerThread.getLooper(), this); 1474 } 1475 1476 // Initialization-on-demand holder 1477 private static final class OnDemandInitializationHolder { 1478 public static final BatchInputUpdater sInstance = new BatchInputUpdater(); 1479 } 1480 1481 public static BatchInputUpdater getInstance() { 1482 return OnDemandInitializationHolder.sInstance; 1483 } 1484 1485 private static final int MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 1; 1486 1487 @Override 1488 public boolean handleMessage(final Message msg) { 1489 switch (msg.what) { 1490 case MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP: 1491 updateBatchInput((InputPointers)msg.obj, mLatinIme); 1492 break; 1493 } 1494 return true; 1495 } 1496 1497 // Run in the UI thread. 1498 public synchronized void onStartBatchInput() { 1499 mInBatchInput = true; 1500 } 1501 1502 // Run in the Handler thread. 1503 private synchronized void updateBatchInput(final InputPointers batchPointers, 1504 final LatinIME latinIme) { 1505 if (!mInBatchInput) { 1506 // Batch input has ended while the message was being delivered. 1507 return; 1508 } 1509 final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked( 1510 batchPointers, latinIme); 1511 latinIme.mHandler.showGesturePreviewAndSuggestionStrip( 1512 suggestedWords, false /* dismissGestureFloatingPreviewText */); 1513 } 1514 1515 // Run in the UI thread. 1516 public void onUpdateBatchInput(final InputPointers batchPointers, final LatinIME latinIme) { 1517 mLatinIme = latinIme; 1518 if (mHandler.hasMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP)) { 1519 return; 1520 } 1521 mHandler.obtainMessage( 1522 MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, batchPointers) 1523 .sendToTarget(); 1524 } 1525 1526 public void onCancelBatchInput(final LatinIME latinIme) { 1527 mInBatchInput = false; 1528 latinIme.mHandler.showGesturePreviewAndSuggestionStrip( 1529 SuggestedWords.EMPTY, true /* dismissGestureFloatingPreviewText */); 1530 } 1531 1532 // Run in the UI thread. 1533 public synchronized SuggestedWords onEndBatchInput(final InputPointers batchPointers, 1534 final LatinIME latinIme) { 1535 mInBatchInput = false; 1536 final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked( 1537 batchPointers, latinIme); 1538 latinIme.mHandler.showGesturePreviewAndSuggestionStrip( 1539 suggestedWords, true /* dismissGestureFloatingPreviewText */); 1540 return suggestedWords; 1541 } 1542 1543 // {@link LatinIME#getSuggestedWords(int)} method calls with same session id have to 1544 // be synchronized. 1545 private static SuggestedWords getSuggestedWordsGestureLocked( 1546 final InputPointers batchPointers, final LatinIME latinIme) { 1547 latinIme.mWordComposer.setBatchInputPointers(batchPointers); 1548 return latinIme.getSuggestedWords(Suggest.SESSION_GESTURE); 1549 } 1550 } 1551 1552 private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, 1553 final boolean dismissGestureFloatingPreviewText) { 1554 final String batchInputText = suggestedWords.isEmpty() 1555 ? null : suggestedWords.getWord(0); 1556 final KeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1557 mainKeyboardView.showGestureFloatingPreviewText(batchInputText); 1558 showSuggestionStrip(suggestedWords, null); 1559 if (dismissGestureFloatingPreviewText) { 1560 mainKeyboardView.dismissGestureFloatingPreviewText(); 1561 } 1562 } 1563 1564 @Override 1565 public void onUpdateBatchInput(final InputPointers batchPointers) { 1566 BatchInputUpdater.getInstance().onUpdateBatchInput(batchPointers, this); 1567 } 1568 1569 @Override 1570 public void onEndBatchInput(final InputPointers batchPointers) { 1571 final SuggestedWords suggestedWords = BatchInputUpdater.getInstance().onEndBatchInput( 1572 batchPointers, this); 1573 final String batchInputText = suggestedWords.isEmpty() 1574 ? null : suggestedWords.getWord(0); 1575 if (TextUtils.isEmpty(batchInputText)) { 1576 return; 1577 } 1578 mWordComposer.setBatchInputWord(batchInputText); 1579 mConnection.beginBatchEdit(); 1580 if (SPACE_STATE_PHANTOM == mSpaceState) { 1581 promotePhantomSpace(); 1582 } 1583 mConnection.setComposingText(batchInputText, 1); 1584 mExpectingUpdateSelection = true; 1585 mConnection.endBatchEdit(); 1586 // Space state must be updated before calling updateShiftState 1587 mSpaceState = SPACE_STATE_PHANTOM; 1588 mKeyboardSwitcher.updateShiftState(); 1589 } 1590 1591 private String specificTldProcessingOnTextInput(final String text) { 1592 if (text.length() <= 1 || text.charAt(0) != Constants.CODE_PERIOD 1593 || !Character.isLetter(text.charAt(1))) { 1594 // Not a tld: do nothing. 1595 return text; 1596 } 1597 // We have a TLD (or something that looks like this): make sure we don't add 1598 // a space even if currently in phantom mode. 1599 mSpaceState = SPACE_STATE_NONE; 1600 // TODO: use getCodePointBeforeCursor instead to improve performance and simplify the code 1601 final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0); 1602 if (lastOne != null && lastOne.length() == 1 1603 && lastOne.charAt(0) == Constants.CODE_PERIOD) { 1604 return text.substring(1); 1605 } else { 1606 return text; 1607 } 1608 } 1609 1610 // Called from PointerTracker through the KeyboardActionListener interface 1611 @Override 1612 public void onCancelInput() { 1613 // User released a finger outside any key 1614 mKeyboardSwitcher.onCancelInput(); 1615 } 1616 1617 @Override 1618 public void onCancelBatchInput() { 1619 BatchInputUpdater.getInstance().onCancelBatchInput(this); 1620 } 1621 1622 private void handleBackspace(final int spaceState) { 1623 // In many cases, we may have to put the keyboard in auto-shift state again. However 1624 // we want to wait a few milliseconds before doing it to avoid the keyboard flashing 1625 // during key repeat. 1626 mHandler.postUpdateShiftState(); 1627 1628 if (mWordComposer.isComposingWord()) { 1629 final int length = mWordComposer.size(); 1630 if (length > 0) { 1631 if (mWordComposer.isBatchMode()) { 1632 mWordComposer.reset(); 1633 } else { 1634 mWordComposer.deleteLast(); 1635 } 1636 mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); 1637 mHandler.postUpdateSuggestionStrip(); 1638 } else { 1639 mConnection.deleteSurroundingText(1, 0); 1640 } 1641 } else { 1642 if (mLastComposedWord.canRevertCommit()) { 1643 if (ProductionFlag.IS_INTERNAL) { 1644 Stats.onAutoCorrectionCancellation(); 1645 } 1646 revertCommit(); 1647 return; 1648 } 1649 if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) { 1650 // Cancel multi-character input: remove the text we just entered. 1651 // This is triggered on backspace after a key that inputs multiple characters, 1652 // like the smiley key or the .com key. 1653 final int length = mEnteredText.length(); 1654 mConnection.deleteSurroundingText(length, 0); 1655 mEnteredText = null; 1656 // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. 1657 // In addition we know that spaceState is false, and that we should not be 1658 // reverting any autocorrect at this point. So we can safely return. 1659 return; 1660 } 1661 if (SPACE_STATE_DOUBLE == spaceState) { 1662 mHandler.cancelDoubleSpacesTimer(); 1663 if (mConnection.revertDoubleSpace()) { 1664 // No need to reset mSpaceState, it has already be done (that's why we 1665 // receive it as a parameter) 1666 return; 1667 } 1668 } else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) { 1669 if (mConnection.revertSwapPunctuation()) { 1670 // Likewise 1671 return; 1672 } 1673 } 1674 1675 // No cancelling of commit/double space/swap: we have a regular backspace. 1676 // We should backspace one char and restart suggestion if at the end of a word. 1677 if (mLastSelectionStart != mLastSelectionEnd) { 1678 // If there is a selection, remove it. 1679 final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart; 1680 mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd); 1681 mConnection.deleteSurroundingText(lengthToDelete, 0); 1682 } else { 1683 // There is no selection, just delete one character. 1684 if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) { 1685 // This should never happen. 1686 Log.e(TAG, "Backspace when we don't know the selection position"); 1687 } 1688 // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because 1689 // we want to be able to compile against the Ice Cream Sandwich SDK. 1690 if (mTargetApplicationInfo != null 1691 && mTargetApplicationInfo.targetSdkVersion < 16) { 1692 // Backward compatibility mode. Before Jelly bean, the keyboard would simulate 1693 // a hardware keyboard event on pressing enter or delete. This is bad for many 1694 // reasons (there are race conditions with commits) but some applications are 1695 // relying on this behavior so we continue to support it for older apps. 1696 sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_DEL); 1697 } else { 1698 mConnection.deleteSurroundingText(1, 0); 1699 } 1700 if (mDeleteCount > DELETE_ACCELERATE_AT) { 1701 mConnection.deleteSurroundingText(1, 0); 1702 } 1703 } 1704 if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) { 1705 restartSuggestionsOnWordBeforeCursorIfAtEndOfWord(); 1706 } 1707 } 1708 } 1709 1710 private boolean maybeStripSpace(final int code, 1711 final int spaceState, final boolean isFromSuggestionStrip) { 1712 if (Constants.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) { 1713 mConnection.removeTrailingSpace(); 1714 return false; 1715 } else if ((SPACE_STATE_WEAK == spaceState 1716 || SPACE_STATE_SWAP_PUNCTUATION == spaceState) 1717 && isFromSuggestionStrip) { 1718 if (mCurrentSettings.isWeakSpaceSwapper(code)) { 1719 return true; 1720 } else { 1721 if (mCurrentSettings.isWeakSpaceStripper(code)) { 1722 mConnection.removeTrailingSpace(); 1723 } 1724 return false; 1725 } 1726 } else { 1727 return false; 1728 } 1729 } 1730 1731 private void handleCharacter(final int primaryCode, final int x, 1732 final int y, final int spaceState) { 1733 boolean isComposingWord = mWordComposer.isComposingWord(); 1734 1735 if (SPACE_STATE_PHANTOM == spaceState && 1736 !mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) { 1737 if (isComposingWord) { 1738 // Sanity check 1739 throw new RuntimeException("Should not be composing here"); 1740 } 1741 promotePhantomSpace(); 1742 } 1743 1744 // NOTE: isCursorTouchingWord() is a blocking IPC call, so it often takes several 1745 // dozen milliseconds. Avoid calling it as much as possible, since we are on the UI 1746 // thread here. 1747 if (!isComposingWord && (isAlphabet(primaryCode) 1748 || mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) 1749 && mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) && 1750 !mConnection.isCursorTouchingWord(mCurrentSettings)) { 1751 // Reset entirely the composing state anyway, then start composing a new word unless 1752 // the character is a single quote. The idea here is, single quote is not a 1753 // separator and it should be treated as a normal character, except in the first 1754 // position where it should not start composing a word. 1755 isComposingWord = (Constants.CODE_SINGLE_QUOTE != primaryCode); 1756 // Here we don't need to reset the last composed word. It will be reset 1757 // when we commit this one, if we ever do; if on the other hand we backspace 1758 // it entirely and resume suggestions on the previous word, we'd like to still 1759 // have touch coordinates for it. 1760 resetComposingState(false /* alsoResetLastComposedWord */); 1761 } 1762 if (isComposingWord) { 1763 final int keyX, keyY; 1764 if (Constants.isValidCoordinate(x) && Constants.isValidCoordinate(y)) { 1765 final KeyDetector keyDetector = 1766 mKeyboardSwitcher.getMainKeyboardView().getKeyDetector(); 1767 keyX = keyDetector.getTouchX(x); 1768 keyY = keyDetector.getTouchY(y); 1769 } else { 1770 keyX = x; 1771 keyY = y; 1772 } 1773 mWordComposer.add(primaryCode, keyX, keyY); 1774 // If it's the first letter, make note of auto-caps state 1775 if (mWordComposer.size() == 1) { 1776 mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode()); 1777 } 1778 mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); 1779 } else { 1780 final boolean swapWeakSpace = maybeStripSpace(primaryCode, 1781 spaceState, Constants.SUGGESTION_STRIP_COORDINATE == x); 1782 1783 sendKeyCodePoint(primaryCode); 1784 1785 if (swapWeakSpace) { 1786 swapSwapperAndSpace(); 1787 mSpaceState = SPACE_STATE_WEAK; 1788 } 1789 // In case the "add to dictionary" hint was still displayed. 1790 if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint(); 1791 } 1792 mHandler.postUpdateSuggestionStrip(); 1793 if (ProductionFlag.IS_INTERNAL) { 1794 Utils.Stats.onNonSeparator((char)primaryCode, x, y); 1795 } 1796 } 1797 1798 // Returns true if we did an autocorrection, false otherwise. 1799 private boolean handleSeparator(final int primaryCode, final int x, final int y, 1800 final int spaceState) { 1801 boolean didAutoCorrect = false; 1802 // Handle separator 1803 if (mWordComposer.isComposingWord()) { 1804 if (mCurrentSettings.mCorrectionEnabled) { 1805 // TODO: maybe cache Strings in an <String> sparse array or something 1806 commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1)); 1807 didAutoCorrect = true; 1808 } else { 1809 commitTyped(new String(new int[]{primaryCode}, 0, 1)); 1810 } 1811 } 1812 1813 final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState, 1814 Constants.SUGGESTION_STRIP_COORDINATE == x); 1815 1816 if (SPACE_STATE_PHANTOM == spaceState && 1817 mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) { 1818 promotePhantomSpace(); 1819 } 1820 sendKeyCodePoint(primaryCode); 1821 1822 if (Constants.CODE_SPACE == primaryCode) { 1823 if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) { 1824 if (maybeDoubleSpace()) { 1825 mSpaceState = SPACE_STATE_DOUBLE; 1826 } else if (!isShowingPunctuationList()) { 1827 mSpaceState = SPACE_STATE_WEAK; 1828 } 1829 } 1830 1831 mHandler.startDoubleSpacesTimer(); 1832 if (!mConnection.isCursorTouchingWord(mCurrentSettings)) { 1833 mHandler.postUpdateSuggestionStrip(); 1834 } 1835 } else { 1836 if (swapWeakSpace) { 1837 swapSwapperAndSpace(); 1838 mSpaceState = SPACE_STATE_SWAP_PUNCTUATION; 1839 } else if (SPACE_STATE_PHANTOM == spaceState 1840 && !mCurrentSettings.isWeakSpaceStripper(primaryCode) 1841 && !mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) { 1842 // If we are in phantom space state, and the user presses a separator, we want to 1843 // stay in phantom space state so that the next keypress has a chance to add the 1844 // space. For example, if I type "Good dat", pick "day" from the suggestion strip 1845 // then insert a comma and go on to typing the next word, I want the space to be 1846 // inserted automatically before the next word, the same way it is when I don't 1847 // input the comma. 1848 // The case is a little different if the separator is a space stripper. Such a 1849 // separator does not normally need a space on the right (that's the difference 1850 // between swappers and strippers), so we should not stay in phantom space state if 1851 // the separator is a stripper. Hence the additional test above. 1852 mSpaceState = SPACE_STATE_PHANTOM; 1853 } 1854 1855 // Set punctuation right away. onUpdateSelection will fire but tests whether it is 1856 // already displayed or not, so it's okay. 1857 setPunctuationSuggestions(); 1858 } 1859 if (ProductionFlag.IS_INTERNAL) { 1860 Utils.Stats.onSeparator((char)primaryCode, x, y); 1861 } 1862 1863 mKeyboardSwitcher.updateShiftState(); 1864 return didAutoCorrect; 1865 } 1866 1867 private CharSequence getTextWithUnderline(final String text) { 1868 return mIsAutoCorrectionIndicatorOn 1869 ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text) 1870 : text; 1871 } 1872 1873 private void handleClose() { 1874 commitTyped(LastComposedWord.NOT_A_SEPARATOR); 1875 requestHideSelf(0); 1876 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1877 if (mainKeyboardView != null) { 1878 mainKeyboardView.closing(); 1879 } 1880 } 1881 1882 // TODO: make this private 1883 // Outside LatinIME, only used by the test suite. 1884 @UsedForTesting 1885 boolean isShowingPunctuationList() { 1886 if (mSuggestionStripView == null) return false; 1887 return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions(); 1888 } 1889 1890 private boolean isSuggestionsStripVisible() { 1891 if (mSuggestionStripView == null) 1892 return false; 1893 if (mSuggestionStripView.isShowingAddToDictionaryHint()) 1894 return true; 1895 if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation)) 1896 return false; 1897 if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()) 1898 return true; 1899 return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation); 1900 } 1901 1902 private void clearSuggestionStrip() { 1903 setSuggestionStrip(SuggestedWords.EMPTY, false); 1904 setAutoCorrectionIndicator(false); 1905 } 1906 1907 private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) { 1908 if (mSuggestionStripView != null) { 1909 mSuggestionStripView.setSuggestions(words); 1910 mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection); 1911 } 1912 } 1913 1914 private void setAutoCorrectionIndicator(final boolean newAutoCorrectionIndicator) { 1915 // Put a blue underline to a word in TextView which will be auto-corrected. 1916 if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator 1917 && mWordComposer.isComposingWord()) { 1918 mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator; 1919 final CharSequence textWithUnderline = 1920 getTextWithUnderline(mWordComposer.getTypedWord()); 1921 // TODO: when called from an updateSuggestionStrip() call that results from a posted 1922 // message, this is called outside any batch edit. Potentially, this may result in some 1923 // janky flickering of the screen, although the display speed makes it unlikely in 1924 // the practice. 1925 mConnection.setComposingText(textWithUnderline, 1); 1926 } 1927 } 1928 1929 private void updateSuggestionStrip() { 1930 mHandler.cancelUpdateSuggestionStrip(); 1931 1932 // Check if we have a suggestion engine attached. 1933 if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) { 1934 if (mWordComposer.isComposingWord()) { 1935 Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not " 1936 + "requested!"); 1937 mWordComposer.setAutoCorrection(mWordComposer.getTypedWord()); 1938 } 1939 return; 1940 } 1941 1942 if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) { 1943 setPunctuationSuggestions(); 1944 return; 1945 } 1946 1947 final SuggestedWords suggestedWords = getSuggestedWords(Suggest.SESSION_TYPING); 1948 final String typedWord = mWordComposer.getTypedWord(); 1949 showSuggestionStrip(suggestedWords, typedWord); 1950 } 1951 1952 private SuggestedWords getSuggestedWords(final int sessionId) { 1953 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1954 if (keyboard == null || mSuggest == null) { 1955 return SuggestedWords.EMPTY; 1956 } 1957 final String typedWord = mWordComposer.getTypedWord(); 1958 // Get the word on which we should search the bigrams. If we are composing a word, it's 1959 // whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we 1960 // should just skip whitespace if any, so 1. 1961 // TODO: this is slow (2-way IPC) - we should probably cache this instead. 1962 final String prevWord = 1963 mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 1964 mWordComposer.isComposingWord() ? 2 : 1); 1965 final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer, 1966 prevWord, keyboard.getProximityInfo(), mCurrentSettings.mCorrectionEnabled, 1967 sessionId); 1968 return maybeRetrieveOlderSuggestions(typedWord, suggestedWords); 1969 } 1970 1971 private SuggestedWords maybeRetrieveOlderSuggestions(final String typedWord, 1972 final SuggestedWords suggestedWords) { 1973 // TODO: consolidate this into getSuggestedWords 1974 // We update the suggestion strip only when we have some suggestions to show, i.e. when 1975 // the suggestion count is > 1; else, we leave the old suggestions, with the typed word 1976 // replaced with the new one. However, when the word is a dictionary word, or when the 1977 // length of the typed word is 1 or 0 (after a deletion typically), we do want to remove the 1978 // old suggestions. Also, if we are showing the "add to dictionary" hint, we need to 1979 // revert to suggestions - although it is unclear how we can come here if it's displayed. 1980 if (suggestedWords.size() > 1 || typedWord.length() <= 1 1981 || !suggestedWords.mTypedWordValid 1982 || mSuggestionStripView.isShowingAddToDictionaryHint()) { 1983 return suggestedWords; 1984 } else { 1985 SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions(); 1986 if (previousSuggestions == mCurrentSettings.mSuggestPuncList) { 1987 previousSuggestions = SuggestedWords.EMPTY; 1988 } 1989 final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions = 1990 SuggestedWords.getTypedWordAndPreviousSuggestions( 1991 typedWord, previousSuggestions); 1992 return new SuggestedWords(typedWordAndPreviousSuggestions, 1993 false /* typedWordValid */, 1994 false /* hasAutoCorrectionCandidate */, 1995 false /* isPunctuationSuggestions */, 1996 true /* isObsoleteSuggestions */, 1997 false /* isPrediction */); 1998 } 1999 } 2000 2001 private void showSuggestionStrip(final SuggestedWords suggestedWords, final String typedWord) { 2002 if (suggestedWords.isEmpty()) { 2003 clearSuggestionStrip(); 2004 return; 2005 } 2006 final String autoCorrection; 2007 if (suggestedWords.mWillAutoCorrect) { 2008 autoCorrection = suggestedWords.getWord(1); 2009 } else { 2010 autoCorrection = typedWord; 2011 } 2012 mWordComposer.setAutoCorrection(autoCorrection); 2013 final boolean isAutoCorrection = suggestedWords.willAutoCorrect(); 2014 setSuggestionStrip(suggestedWords, isAutoCorrection); 2015 setAutoCorrectionIndicator(isAutoCorrection); 2016 setSuggestionStripShown(isSuggestionsStripVisible()); 2017 } 2018 2019 private void commitCurrentAutoCorrection(final String separatorString) { 2020 // Complete any pending suggestions query first 2021 if (mHandler.hasPendingUpdateSuggestions()) { 2022 updateSuggestionStrip(); 2023 } 2024 final String typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull(); 2025 final String typedWord = mWordComposer.getTypedWord(); 2026 final String autoCorrection = (typedAutoCorrection != null) 2027 ? typedAutoCorrection : typedWord; 2028 if (autoCorrection != null) { 2029 if (TextUtils.isEmpty(typedWord)) { 2030 throw new RuntimeException("We have an auto-correction but the typed word " 2031 + "is empty? Impossible! I must commit suicide."); 2032 } 2033 if (ProductionFlag.IS_INTERNAL) { 2034 Stats.onAutoCorrection( 2035 typedWord, autoCorrection.toString(), separatorString, mWordComposer); 2036 } 2037 mExpectingUpdateSelection = true; 2038 commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD, 2039 separatorString); 2040 if (!typedWord.equals(autoCorrection)) { 2041 // This will make the correction flash for a short while as a visual clue 2042 // to the user that auto-correction happened. It has no other effect; in particular 2043 // note that this won't affect the text inside the text field AT ALL: it only makes 2044 // the segment of text starting at the supplied index and running for the length 2045 // of the auto-correction flash. At this moment, the "typedWord" argument is 2046 // ignored by TextView. 2047 mConnection.commitCorrection( 2048 new CorrectionInfo(mLastSelectionEnd - typedWord.length(), 2049 typedWord, autoCorrection)); 2050 } 2051 } 2052 } 2053 2054 // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 2055 // interface 2056 @Override 2057 public void pickSuggestionManually(final int index, final String suggestion) { 2058 final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions(); 2059 // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput 2060 if (suggestion.length() == 1 && isShowingPunctuationList()) { 2061 // Word separators are suggested before the user inputs something. 2062 // So, LatinImeLogger logs "" as a user's input. 2063 LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords); 2064 // Rely on onCodeInput to do the complicated swapping/stripping logic consistently. 2065 final int primaryCode = suggestion.charAt(0); 2066 onCodeInput(primaryCode, 2067 Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE); 2068 if (ProductionFlag.IS_EXPERIMENTAL) { 2069 ResearchLogger.latinIME_punctuationSuggestion(index, suggestion); 2070 } 2071 return; 2072 } 2073 2074 mConnection.beginBatchEdit(); 2075 if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0 2076 // In the batch input mode, a manually picked suggested word should just replace 2077 // the current batch input text and there is no need for a phantom space. 2078 && !mWordComposer.isBatchMode()) { 2079 int firstChar = Character.codePointAt(suggestion, 0); 2080 if ((!mCurrentSettings.isWeakSpaceStripper(firstChar)) 2081 && (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) { 2082 promotePhantomSpace(); 2083 } 2084 } 2085 2086 if (mCurrentSettings.isApplicationSpecifiedCompletionsOn() 2087 && mApplicationSpecifiedCompletions != null 2088 && index >= 0 && index < mApplicationSpecifiedCompletions.length) { 2089 if (mSuggestionStripView != null) { 2090 mSuggestionStripView.clear(); 2091 } 2092 mKeyboardSwitcher.updateShiftState(); 2093 resetComposingState(true /* alsoResetLastComposedWord */); 2094 final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index]; 2095 mConnection.commitCompletion(completionInfo); 2096 mConnection.endBatchEdit(); 2097 return; 2098 } 2099 2100 // We need to log before we commit, because the word composer will store away the user 2101 // typed word. 2102 final String replacedWord = mWordComposer.getTypedWord().toString(); 2103 LatinImeLogger.logOnManualSuggestion(replacedWord, 2104 suggestion.toString(), index, suggestedWords); 2105 mExpectingUpdateSelection = true; 2106 commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK, 2107 LastComposedWord.NOT_A_SEPARATOR); 2108 if (ProductionFlag.IS_EXPERIMENTAL) { 2109 ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion); 2110 } 2111 mConnection.endBatchEdit(); 2112 // Don't allow cancellation of manual pick 2113 mLastComposedWord.deactivate(); 2114 // Space state must be updated before calling updateShiftState 2115 mSpaceState = SPACE_STATE_PHANTOM; 2116 mKeyboardSwitcher.updateShiftState(); 2117 2118 // We should show the "Touch again to save" hint if the user pressed the first entry 2119 // AND it's in none of our current dictionaries (main, user or otherwise). 2120 // Please note that if mSuggest is null, it means that everything is off: suggestion 2121 // and correction, so we shouldn't try to show the hint 2122 final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null 2123 // If the suggestion is not in the dictionary, the hint should be shown. 2124 && !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true); 2125 2126 if (ProductionFlag.IS_INTERNAL) { 2127 Stats.onSeparator((char)Constants.CODE_SPACE, 2128 Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); 2129 } 2130 if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) { 2131 mSuggestionStripView.showAddToDictionaryHint( 2132 suggestion, mCurrentSettings.mHintToSaveText); 2133 } else { 2134 // If we're not showing the "Touch again to save", then update the suggestion strip. 2135 mHandler.postUpdateSuggestionStrip(); 2136 } 2137 } 2138 2139 /** 2140 * Commits the chosen word to the text field and saves it for later retrieval. 2141 */ 2142 private void commitChosenWord(final String chosenWord, final int commitType, 2143 final String separatorString) { 2144 final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions(); 2145 mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan( 2146 this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1); 2147 // Add the word to the user history dictionary 2148 final String prevWord = addToUserHistoryDictionary(chosenWord); 2149 // TODO: figure out here if this is an auto-correct or if the best word is actually 2150 // what user typed. Note: currently this is done much later in 2151 // LastComposedWord#didCommitTypedWord by string equality of the remembered 2152 // strings. 2153 mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(), 2154 separatorString, prevWord); 2155 } 2156 2157 private void setPunctuationSuggestions() { 2158 if (mCurrentSettings.mBigramPredictionEnabled) { 2159 clearSuggestionStrip(); 2160 } else { 2161 setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false); 2162 } 2163 setAutoCorrectionIndicator(false); 2164 setSuggestionStripShown(isSuggestionsStripVisible()); 2165 } 2166 2167 private String addToUserHistoryDictionary(final String suggestion) { 2168 if (TextUtils.isEmpty(suggestion)) return null; 2169 if (mSuggest == null) return null; 2170 2171 // If correction is not enabled, we don't add words to the user history dictionary. 2172 // That's to avoid unintended additions in some sensitive fields, or fields that 2173 // expect to receive non-words. 2174 if (!mCurrentSettings.mCorrectionEnabled) return null; 2175 2176 final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary; 2177 if (userHistoryDictionary != null) { 2178 final CharSequence prevWord 2179 = mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2); 2180 final String secondWord; 2181 if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) { 2182 secondWord = suggestion.toLowerCase(mSubtypeSwitcher.getCurrentSubtypeLocale()); 2183 } else { 2184 secondWord = suggestion; 2185 } 2186 // We demote unrecognized words (frequency < 0, below) by specifying them as "invalid". 2187 // We don't add words with 0-frequency (assuming they would be profanity etc.). 2188 final int maxFreq = AutoCorrection.getMaxFrequency( 2189 mSuggest.getUnigramDictionaries(), suggestion); 2190 if (maxFreq == 0) return null; 2191 final String prevWordString = (null == prevWord) ? null : prevWord.toString(); 2192 userHistoryDictionary.addToUserHistory(prevWordString, secondWord, maxFreq > 0); 2193 return prevWordString; 2194 } 2195 return null; 2196 } 2197 2198 /** 2199 * Check if the cursor is actually at the end of a word. If so, restart suggestions on this 2200 * word, else do nothing. 2201 */ 2202 private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() { 2203 final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings); 2204 if (null != word) { 2205 restartSuggestionsOnWordBeforeCursor(word); 2206 } 2207 } 2208 2209 private void restartSuggestionsOnWordBeforeCursor(final CharSequence word) { 2210 mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard()); 2211 final int length = word.length(); 2212 mConnection.deleteSurroundingText(length, 0); 2213 mConnection.setComposingText(word, 1); 2214 mHandler.postUpdateSuggestionStrip(); 2215 } 2216 2217 private void revertCommit() { 2218 final String previousWord = mLastComposedWord.mPrevWord; 2219 final String originallyTypedWord = mLastComposedWord.mTypedWord; 2220 final String committedWord = mLastComposedWord.mCommittedWord; 2221 final int cancelLength = committedWord.length(); 2222 final int separatorLength = LastComposedWord.getSeparatorLength( 2223 mLastComposedWord.mSeparatorString); 2224 // TODO: should we check our saved separator against the actual contents of the text view? 2225 final int deleteLength = cancelLength + separatorLength; 2226 if (DEBUG) { 2227 if (mWordComposer.isComposingWord()) { 2228 throw new RuntimeException("revertCommit, but we are composing a word"); 2229 } 2230 final CharSequence wordBeforeCursor = 2231 mConnection.getTextBeforeCursor(deleteLength, 0) 2232 .subSequence(0, cancelLength); 2233 if (!TextUtils.equals(committedWord, wordBeforeCursor)) { 2234 throw new RuntimeException("revertCommit check failed: we thought we were " 2235 + "reverting \"" + committedWord 2236 + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); 2237 } 2238 } 2239 mConnection.deleteSurroundingText(deleteLength, 0); 2240 if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) { 2241 mUserHistoryDictionary.cancelAddingUserHistory( 2242 previousWord.toString(), committedWord.toString()); 2243 } 2244 mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1); 2245 if (ProductionFlag.IS_INTERNAL) { 2246 Stats.onSeparator(mLastComposedWord.mSeparatorString, 2247 Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); 2248 } 2249 if (ProductionFlag.IS_EXPERIMENTAL) { 2250 ResearchLogger.latinIME_revertCommit(originallyTypedWord); 2251 } 2252 // Don't restart suggestion yet. We'll restart if the user deletes the 2253 // separator. 2254 mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; 2255 // We have a separator between the word and the cursor: we should show predictions. 2256 mHandler.postUpdateSuggestionStrip(); 2257 } 2258 2259 // This essentially inserts a space, and that's it. 2260 public void promotePhantomSpace() { 2261 if (mCurrentSettings.shouldInsertSpacesAutomatically()) { 2262 sendKeyCodePoint(Constants.CODE_SPACE); 2263 } 2264 } 2265 2266 // Used by the RingCharBuffer 2267 public boolean isWordSeparator(final int code) { 2268 return mCurrentSettings.isWordSeparator(code); 2269 } 2270 2271 // TODO: Make this private 2272 // Outside LatinIME, only used by the {@link InputTestsBase} test suite. 2273 @UsedForTesting 2274 void loadKeyboard() { 2275 // When the device locale is changed in SetupWizard etc., this method may get called via 2276 // onConfigurationChanged before SoftInputWindow is shown. 2277 initSuggest(); 2278 loadSettings(); 2279 if (mKeyboardSwitcher.getMainKeyboardView() != null) { 2280 // Reload keyboard because the current language has been changed. 2281 mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings); 2282 } 2283 // Since we just changed languages, we should re-evaluate suggestions with whatever word 2284 // we are currently composing. If we are not composing anything, we may want to display 2285 // predictions or punctuation signs (which is done by the updateSuggestionStrip anyway). 2286 mHandler.postUpdateSuggestionStrip(); 2287 } 2288 2289 // Callback called by PointerTracker through the KeyboardActionListener. This is called when a 2290 // key is depressed; release matching call is onReleaseKey below. 2291 @Override 2292 public void onPressKey(final int primaryCode) { 2293 mKeyboardSwitcher.onPressKey(primaryCode); 2294 } 2295 2296 // Callback by PointerTracker through the KeyboardActionListener. This is called when a key 2297 // is released; press matching call is onPressKey above. 2298 @Override 2299 public void onReleaseKey(final int primaryCode, final boolean withSliding) { 2300 mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding); 2301 2302 // If accessibility is on, ensure the user receives keyboard state updates. 2303 if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) { 2304 switch (primaryCode) { 2305 case Constants.CODE_SHIFT: 2306 AccessibleKeyboardViewProxy.getInstance().notifyShiftState(); 2307 break; 2308 case Constants.CODE_SWITCH_ALPHA_SYMBOL: 2309 AccessibleKeyboardViewProxy.getInstance().notifySymbolsState(); 2310 break; 2311 } 2312 } 2313 2314 if (Constants.CODE_DELETE == primaryCode) { 2315 // This is a stopgap solution to avoid leaving a high surrogate alone in a text view. 2316 // In the future, we need to deprecate deteleSurroundingText() and have a surrogate 2317 // pair-friendly way of deleting characters in InputConnection. 2318 // TODO: use getCodePointBeforeCursor instead to improve performance 2319 final CharSequence lastChar = mConnection.getTextBeforeCursor(1, 0); 2320 if (!TextUtils.isEmpty(lastChar) && Character.isHighSurrogate(lastChar.charAt(0))) { 2321 mConnection.deleteSurroundingText(1, 0); 2322 } 2323 } 2324 } 2325 2326 // receive ringer mode change and network state change. 2327 private BroadcastReceiver mReceiver = new BroadcastReceiver() { 2328 @Override 2329 public void onReceive(final Context context, final Intent intent) { 2330 final String action = intent.getAction(); 2331 if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 2332 mSubtypeSwitcher.onNetworkStateChanged(intent); 2333 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { 2334 mKeyboardSwitcher.onRingerModeChanged(); 2335 } 2336 } 2337 }; 2338 2339 private void launchSettings() { 2340 handleClose(); 2341 launchSubActivity(SettingsActivity.class); 2342 } 2343 2344 // Called from debug code only 2345 public void launchDebugSettings() { 2346 handleClose(); 2347 launchSubActivity(DebugSettingsActivity.class); 2348 } 2349 2350 public void launchKeyboardedDialogActivity(final Class<? extends Activity> activityClass) { 2351 // Put the text in the attached EditText into a safe, saved state before switching to a 2352 // new activity that will also use the soft keyboard. 2353 commitTyped(LastComposedWord.NOT_A_SEPARATOR); 2354 launchSubActivity(activityClass); 2355 } 2356 2357 private void launchSubActivity(final Class<? extends Activity> activityClass) { 2358 Intent intent = new Intent(); 2359 intent.setClass(LatinIME.this, activityClass); 2360 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2361 startActivity(intent); 2362 } 2363 2364 private void showSubtypeSelectorAndSettings() { 2365 final CharSequence title = getString(R.string.english_ime_input_options); 2366 final CharSequence[] items = new CharSequence[] { 2367 // TODO: Should use new string "Select active input modes". 2368 getString(R.string.language_selection_title), 2369 getString(R.string.english_ime_settings), 2370 }; 2371 final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { 2372 @Override 2373 public void onClick(DialogInterface di, int position) { 2374 di.dismiss(); 2375 switch (position) { 2376 case 0: 2377 Intent intent = CompatUtils.getInputLanguageSelectionIntent( 2378 mRichImm.getInputMethodIdOfThisIme(), 2379 Intent.FLAG_ACTIVITY_NEW_TASK 2380 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 2381 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 2382 startActivity(intent); 2383 break; 2384 case 1: 2385 launchSettings(); 2386 break; 2387 } 2388 } 2389 }; 2390 final AlertDialog.Builder builder = new AlertDialog.Builder(this) 2391 .setItems(items, listener) 2392 .setTitle(title); 2393 showOptionDialog(builder.create()); 2394 } 2395 2396 public void showOptionDialog(final AlertDialog dialog) { 2397 final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken(); 2398 if (windowToken == null) { 2399 return; 2400 } 2401 2402 dialog.setCancelable(true); 2403 dialog.setCanceledOnTouchOutside(true); 2404 2405 final Window window = dialog.getWindow(); 2406 final WindowManager.LayoutParams lp = window.getAttributes(); 2407 lp.token = windowToken; 2408 lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; 2409 window.setAttributes(lp); 2410 window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 2411 2412 mOptionsDialog = dialog; 2413 dialog.show(); 2414 } 2415 2416 public void debugDumpStateAndCrashWithException(final String context) { 2417 final StringBuilder s = new StringBuilder(); 2418 s.append("Target application : ").append(mTargetApplicationInfo.name) 2419 .append("\nPackage : ").append(mTargetApplicationInfo.packageName) 2420 .append("\nTarget app sdk version : ") 2421 .append(mTargetApplicationInfo.targetSdkVersion) 2422 .append("\nAttributes : ").append(mCurrentSettings.getInputAttributesDebugString()) 2423 .append("\nContext : ").append(context); 2424 throw new RuntimeException(s.toString()); 2425 } 2426 2427 @Override 2428 protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) { 2429 super.dump(fd, fout, args); 2430 2431 final Printer p = new PrintWriterPrinter(fout); 2432 p.println("LatinIME state :"); 2433 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 2434 final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; 2435 p.println(" Keyboard mode = " + keyboardMode); 2436 p.println(" mIsSuggestionsSuggestionsRequested = " 2437 + mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)); 2438 p.println(" mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled); 2439 p.println(" isComposingWord=" + mWordComposer.isComposingWord()); 2440 p.println(" mSoundOn=" + mCurrentSettings.mSoundOn); 2441 p.println(" mVibrateOn=" + mCurrentSettings.mVibrateOn); 2442 p.println(" mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn); 2443 p.println(" inputAttributes=" + mCurrentSettings.getInputAttributesDebugString()); 2444 } 2445} 2446