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