LatinIME.java revision 9395014e76877fc9ef060a3fe54a9e06f0036d6d
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 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.AlertDialog; 24import android.content.BroadcastReceiver; 25import android.content.Context; 26import android.content.DialogInterface; 27import android.content.DialogInterface.OnClickListener; 28import android.content.Intent; 29import android.content.IntentFilter; 30import android.content.res.Configuration; 31import android.content.res.Resources; 32import android.inputmethodservice.InputMethodService; 33import android.media.AudioManager; 34import android.net.ConnectivityManager; 35import android.os.Debug; 36import android.os.IBinder; 37import android.os.Message; 38import android.preference.PreferenceManager; 39import android.text.InputType; 40import android.text.TextUtils; 41import android.util.Log; 42import android.util.PrintWriterPrinter; 43import android.util.Printer; 44import android.util.SparseArray; 45import android.view.Gravity; 46import android.view.KeyEvent; 47import android.view.View; 48import android.view.ViewGroup.LayoutParams; 49import android.view.Window; 50import android.view.WindowManager; 51import android.view.inputmethod.CompletionInfo; 52import android.view.inputmethod.CursorAnchorInfo; 53import android.view.inputmethod.EditorInfo; 54import android.view.inputmethod.InputMethod; 55import android.view.inputmethod.InputMethodSubtype; 56 57import com.android.inputmethod.accessibility.AccessibilityUtils; 58import com.android.inputmethod.annotations.UsedForTesting; 59import com.android.inputmethod.compat.CursorAnchorInfoCompatWrapper; 60import com.android.inputmethod.compat.InputMethodServiceCompatUtils; 61import com.android.inputmethod.dictionarypack.DictionaryPackConstants; 62import com.android.inputmethod.event.Event; 63import com.android.inputmethod.event.HardwareEventDecoder; 64import com.android.inputmethod.event.HardwareKeyboardEventDecoder; 65import com.android.inputmethod.event.InputTransaction; 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.MainKeyboardView; 71import com.android.inputmethod.keyboard.TextDecoratorUi; 72import com.android.inputmethod.latin.Suggest.OnGetSuggestedWordsCallback; 73import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo; 74import com.android.inputmethod.latin.define.DebugFlags; 75import com.android.inputmethod.latin.define.ProductionFlags; 76import com.android.inputmethod.latin.inputlogic.InputLogic; 77import com.android.inputmethod.latin.personalization.ContextualDictionaryUpdater; 78import com.android.inputmethod.latin.personalization.DictionaryDecayBroadcastReciever; 79import com.android.inputmethod.latin.personalization.PersonalizationDictionaryUpdater; 80import com.android.inputmethod.latin.personalization.PersonalizationHelper; 81import com.android.inputmethod.latin.settings.Settings; 82import com.android.inputmethod.latin.settings.SettingsActivity; 83import com.android.inputmethod.latin.settings.SettingsValues; 84import com.android.inputmethod.latin.suggestions.SuggestionStripView; 85import com.android.inputmethod.latin.suggestions.SuggestionStripViewAccessor; 86import com.android.inputmethod.latin.utils.ApplicationUtils; 87import com.android.inputmethod.latin.utils.CapsModeUtils; 88import com.android.inputmethod.latin.utils.CoordinateUtils; 89import com.android.inputmethod.latin.utils.DialogUtils; 90import com.android.inputmethod.latin.utils.DistracterFilterCheckingExactMatchesAndSuggestions; 91import com.android.inputmethod.latin.utils.ImportantNoticeUtils; 92import com.android.inputmethod.latin.utils.IntentUtils; 93import com.android.inputmethod.latin.utils.JniUtils; 94import com.android.inputmethod.latin.utils.LeakGuardHandlerWrapper; 95import com.android.inputmethod.latin.utils.StatsUtils; 96import com.android.inputmethod.latin.utils.SubtypeLocaleUtils; 97import com.android.inputmethod.latin.utils.ViewLayoutUtils; 98 99import java.io.FileDescriptor; 100import java.io.PrintWriter; 101import java.util.ArrayList; 102import java.util.List; 103import java.util.Locale; 104import java.util.concurrent.TimeUnit; 105 106/** 107 * Input method implementation for Qwerty'ish keyboard. 108 */ 109public class LatinIME extends InputMethodService implements KeyboardActionListener, 110 SuggestionStripView.Listener, SuggestionStripViewAccessor, 111 DictionaryFacilitator.DictionaryInitializationListener, 112 ImportantNoticeDialog.ImportantNoticeDialogListener { 113 private static final String TAG = LatinIME.class.getSimpleName(); 114 private static final boolean TRACE = false; 115 private static boolean DEBUG = false; 116 117 private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; 118 119 private static final int PENDING_IMS_CALLBACK_DURATION = 800; 120 121 private static final int DELAY_WAIT_FOR_DICTIONARY_LOAD = 2000; // 2s 122 123 private static final int PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT = 2; 124 125 /** 126 * The name of the scheme used by the Package Manager to warn of a new package installation, 127 * replacement or removal. 128 */ 129 private static final String SCHEME_PACKAGE = "package"; 130 131 private final Settings mSettings; 132 private final DictionaryFacilitator mDictionaryFacilitator = 133 new DictionaryFacilitator( 134 new DistracterFilterCheckingExactMatchesAndSuggestions(this /* context */)); 135 // TODO: Move from LatinIME. 136 private final PersonalizationDictionaryUpdater mPersonalizationDictionaryUpdater = 137 new PersonalizationDictionaryUpdater(this /* context */, mDictionaryFacilitator); 138 private final ContextualDictionaryUpdater mContextualDictionaryUpdater = 139 new ContextualDictionaryUpdater(this /* context */, mDictionaryFacilitator, 140 new Runnable() { 141 @Override 142 public void run() { 143 mHandler.postUpdateSuggestionStrip(SuggestedWords.INPUT_STYLE_NONE); 144 } 145 }); 146 private final InputLogic mInputLogic = new InputLogic(this /* LatinIME */, 147 this /* SuggestionStripViewAccessor */, mDictionaryFacilitator); 148 // We expect to have only one decoder in almost all cases, hence the default capacity of 1. 149 // If it turns out we need several, it will get grown seamlessly. 150 final SparseArray<HardwareEventDecoder> mHardwareEventDecoders = new SparseArray<>(1); 151 152 // TODO: Move these {@link View}s to {@link KeyboardSwitcher}. 153 private View mInputView; 154 private SuggestionStripView mSuggestionStripView; 155 156 private RichInputMethodManager mRichImm; 157 @UsedForTesting final KeyboardSwitcher mKeyboardSwitcher; 158 private final SubtypeSwitcher mSubtypeSwitcher; 159 private final SubtypeState mSubtypeState = new SubtypeState(); 160 private final SpecialKeyDetector mSpecialKeyDetector; 161 162 // Object for reacting to adding/removing a dictionary pack. 163 private final BroadcastReceiver mDictionaryPackInstallReceiver = 164 new DictionaryPackInstallBroadcastReceiver(this); 165 166 private final BroadcastReceiver mDictionaryDumpBroadcastReceiver = 167 new DictionaryDumpBroadcastReceiver(this); 168 169 private AlertDialog mOptionsDialog; 170 171 private final boolean mIsHardwareAcceleratedDrawingEnabled; 172 173 public final UIHandler mHandler = new UIHandler(this); 174 175 public static final class UIHandler extends LeakGuardHandlerWrapper<LatinIME> { 176 private static final int MSG_UPDATE_SHIFT_STATE = 0; 177 private static final int MSG_PENDING_IMS_CALLBACK = 1; 178 private static final int MSG_UPDATE_SUGGESTION_STRIP = 2; 179 private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3; 180 private static final int MSG_RESUME_SUGGESTIONS = 4; 181 private static final int MSG_REOPEN_DICTIONARIES = 5; 182 private static final int MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED = 6; 183 private static final int MSG_RESET_CACHES = 7; 184 private static final int MSG_WAIT_FOR_DICTIONARY_LOAD = 8; 185 private static final int MSG_SHOW_COMMIT_INDICATOR = 9; 186 // Update this when adding new messages 187 private static final int MSG_LAST = MSG_SHOW_COMMIT_INDICATOR; 188 189 private static final int ARG1_NOT_GESTURE_INPUT = 0; 190 private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1; 191 private static final int ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT = 2; 192 private static final int ARG2_UNUSED = 0; 193 private static final int ARG1_FALSE = 0; 194 private static final int ARG1_TRUE = 1; 195 196 private int mDelayInMillisecondsToUpdateSuggestions; 197 private int mDelayInMillisecondsToUpdateShiftState; 198 private int mDelayInMillisecondsToShowCommitIndicator; 199 200 public UIHandler(final LatinIME ownerInstance) { 201 super(ownerInstance); 202 } 203 204 public void onCreate() { 205 final LatinIME latinIme = getOwnerInstance(); 206 if (latinIme == null) { 207 return; 208 } 209 final Resources res = latinIme.getResources(); 210 mDelayInMillisecondsToUpdateSuggestions = res.getInteger( 211 R.integer.config_delay_in_milliseconds_to_update_suggestions); 212 mDelayInMillisecondsToUpdateShiftState = res.getInteger( 213 R.integer.config_delay_in_milliseconds_to_update_shift_state); 214 mDelayInMillisecondsToShowCommitIndicator = res.getInteger( 215 R.integer.text_decorator_delay_in_milliseconds_to_show_commit_indicator); 216 } 217 218 @Override 219 public void handleMessage(final Message msg) { 220 final LatinIME latinIme = getOwnerInstance(); 221 if (latinIme == null) { 222 return; 223 } 224 final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher; 225 switch (msg.what) { 226 case MSG_UPDATE_SUGGESTION_STRIP: 227 cancelUpdateSuggestionStrip(); 228 latinIme.mInputLogic.performUpdateSuggestionStripSync( 229 latinIme.mSettings.getCurrent(), msg.arg1 /* inputStyle */); 230 break; 231 case MSG_UPDATE_SHIFT_STATE: 232 switcher.requestUpdatingShiftState(latinIme.getCurrentAutoCapsState(), 233 latinIme.getCurrentRecapitalizeState()); 234 break; 235 case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP: 236 if (msg.arg1 == ARG1_NOT_GESTURE_INPUT) { 237 final SuggestedWords suggestedWords = (SuggestedWords) msg.obj; 238 latinIme.showSuggestionStrip(suggestedWords); 239 } else { 240 latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords) msg.obj, 241 msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT); 242 } 243 break; 244 case MSG_RESUME_SUGGESTIONS: 245 latinIme.mInputLogic.restartSuggestionsOnWordTouchedByCursor( 246 latinIme.mSettings.getCurrent(), 247 msg.arg1 == ARG1_TRUE /* shouldIncludeResumedWordInSuggestions */, 248 latinIme.mKeyboardSwitcher.getCurrentKeyboardScriptId()); 249 break; 250 case MSG_REOPEN_DICTIONARIES: 251 // We need to re-evaluate the currently composing word in case the script has 252 // changed. 253 postWaitForDictionaryLoad(); 254 latinIme.resetSuggest(); 255 break; 256 case MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED: 257 latinIme.mInputLogic.onUpdateTailBatchInputCompleted( 258 latinIme.mSettings.getCurrent(), 259 (SuggestedWords) msg.obj, latinIme.mKeyboardSwitcher); 260 break; 261 case MSG_RESET_CACHES: 262 final SettingsValues settingsValues = latinIme.mSettings.getCurrent(); 263 if (latinIme.mInputLogic.retryResetCachesAndReturnSuccess( 264 msg.arg1 == ARG1_TRUE /* tryResumeSuggestions */, 265 msg.arg2 /* remainingTries */, this /* handler */)) { 266 // If we were able to reset the caches, then we can reload the keyboard. 267 // Otherwise, we'll do it when we can. 268 latinIme.mKeyboardSwitcher.loadKeyboard(latinIme.getCurrentInputEditorInfo(), 269 settingsValues, latinIme.getCurrentAutoCapsState(), 270 latinIme.getCurrentRecapitalizeState()); 271 } 272 break; 273 case MSG_SHOW_COMMIT_INDICATOR: 274 // Protocol of MSG_SET_COMMIT_INDICATOR_ENABLED: 275 // - what: MSG_SHOW_COMMIT_INDICATOR 276 // - arg1: not used. 277 // - arg2: not used. 278 // - obj: the Runnable object to be called back. 279 ((Runnable) msg.obj).run(); 280 break; 281 case MSG_WAIT_FOR_DICTIONARY_LOAD: 282 Log.i(TAG, "Timeout waiting for dictionary load"); 283 break; 284 } 285 } 286 287 public void postUpdateSuggestionStrip(final int inputStyle) { 288 sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP, inputStyle, 289 0 /* ignored */), mDelayInMillisecondsToUpdateSuggestions); 290 } 291 292 public void postReopenDictionaries() { 293 sendMessage(obtainMessage(MSG_REOPEN_DICTIONARIES)); 294 } 295 296 public void postResumeSuggestions(final boolean shouldIncludeResumedWordInSuggestions, 297 final boolean shouldDelay) { 298 final LatinIME latinIme = getOwnerInstance(); 299 if (latinIme == null) { 300 return; 301 } 302 if (!latinIme.mSettings.getCurrent().isSuggestionsEnabledPerUserSettings()) { 303 return; 304 } 305 removeMessages(MSG_RESUME_SUGGESTIONS); 306 if (shouldDelay) { 307 sendMessageDelayed(obtainMessage(MSG_RESUME_SUGGESTIONS, 308 shouldIncludeResumedWordInSuggestions ? ARG1_TRUE : ARG1_FALSE, 309 0 /* ignored */), mDelayInMillisecondsToUpdateSuggestions); 310 } else { 311 sendMessage(obtainMessage(MSG_RESUME_SUGGESTIONS, 312 shouldIncludeResumedWordInSuggestions ? ARG1_TRUE : ARG1_FALSE, 313 0 /* ignored */)); 314 } 315 } 316 317 public void postResetCaches(final boolean tryResumeSuggestions, final int remainingTries) { 318 removeMessages(MSG_RESET_CACHES); 319 sendMessage(obtainMessage(MSG_RESET_CACHES, tryResumeSuggestions ? 1 : 0, 320 remainingTries, null)); 321 } 322 323 public void postWaitForDictionaryLoad() { 324 sendMessageDelayed(obtainMessage(MSG_WAIT_FOR_DICTIONARY_LOAD), 325 DELAY_WAIT_FOR_DICTIONARY_LOAD); 326 } 327 328 public void cancelWaitForDictionaryLoad() { 329 removeMessages(MSG_WAIT_FOR_DICTIONARY_LOAD); 330 } 331 332 public boolean hasPendingWaitForDictionaryLoad() { 333 return hasMessages(MSG_WAIT_FOR_DICTIONARY_LOAD); 334 } 335 336 public void cancelUpdateSuggestionStrip() { 337 removeMessages(MSG_UPDATE_SUGGESTION_STRIP); 338 } 339 340 public boolean hasPendingUpdateSuggestions() { 341 return hasMessages(MSG_UPDATE_SUGGESTION_STRIP); 342 } 343 344 public boolean hasPendingReopenDictionaries() { 345 return hasMessages(MSG_REOPEN_DICTIONARIES); 346 } 347 348 public void postUpdateShiftState() { 349 removeMessages(MSG_UPDATE_SHIFT_STATE); 350 sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), 351 mDelayInMillisecondsToUpdateShiftState); 352 } 353 354 @UsedForTesting 355 public void removeAllMessages() { 356 for (int i = 0; i <= MSG_LAST; ++i) { 357 removeMessages(i); 358 } 359 } 360 361 public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, 362 final boolean dismissGestureFloatingPreviewText) { 363 removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); 364 final int arg1 = dismissGestureFloatingPreviewText 365 ? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT 366 : ARG1_SHOW_GESTURE_FLOATING_PREVIEW_TEXT; 367 obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, 368 ARG2_UNUSED, suggestedWords).sendToTarget(); 369 } 370 371 public void showSuggestionStrip(final SuggestedWords suggestedWords) { 372 removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); 373 obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, 374 ARG1_NOT_GESTURE_INPUT, ARG2_UNUSED, suggestedWords).sendToTarget(); 375 } 376 377 public void showTailBatchInputResult(final SuggestedWords suggestedWords) { 378 obtainMessage(MSG_UPDATE_TAIL_BATCH_INPUT_COMPLETED, suggestedWords).sendToTarget(); 379 } 380 381 /** 382 * Posts a delayed task to show the commit indicator. 383 * 384 * <p>Only one task can exist in the queue. When this method is called, any prior task that 385 * has not yet fired will be canceled.</p> 386 * @param task the runnable object that will be fired when the delayed task is dispatched. 387 */ 388 public void postShowCommitIndicatorTask(final Runnable task) { 389 removeMessages(MSG_SHOW_COMMIT_INDICATOR); 390 sendMessageDelayed(obtainMessage(MSG_SHOW_COMMIT_INDICATOR, task), 391 mDelayInMillisecondsToShowCommitIndicator); 392 } 393 394 // Working variables for the following methods. 395 private boolean mIsOrientationChanging; 396 private boolean mPendingSuccessiveImsCallback; 397 private boolean mHasPendingStartInput; 398 private boolean mHasPendingFinishInputView; 399 private boolean mHasPendingFinishInput; 400 private EditorInfo mAppliedEditorInfo; 401 402 public void startOrientationChanging() { 403 removeMessages(MSG_PENDING_IMS_CALLBACK); 404 resetPendingImsCallback(); 405 mIsOrientationChanging = true; 406 final LatinIME latinIme = getOwnerInstance(); 407 if (latinIme == null) { 408 return; 409 } 410 if (latinIme.isInputViewShown()) { 411 latinIme.mKeyboardSwitcher.saveKeyboardState(); 412 } 413 } 414 415 private void resetPendingImsCallback() { 416 mHasPendingFinishInputView = false; 417 mHasPendingFinishInput = false; 418 mHasPendingStartInput = false; 419 } 420 421 private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo, 422 boolean restarting) { 423 if (mHasPendingFinishInputView) { 424 latinIme.onFinishInputViewInternal(mHasPendingFinishInput); 425 } 426 if (mHasPendingFinishInput) { 427 latinIme.onFinishInputInternal(); 428 } 429 if (mHasPendingStartInput) { 430 latinIme.onStartInputInternal(editorInfo, restarting); 431 } 432 resetPendingImsCallback(); 433 } 434 435 public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { 436 if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { 437 // Typically this is the second onStartInput after orientation changed. 438 mHasPendingStartInput = true; 439 } else { 440 if (mIsOrientationChanging && restarting) { 441 // This is the first onStartInput after orientation changed. 442 mIsOrientationChanging = false; 443 mPendingSuccessiveImsCallback = true; 444 } 445 final LatinIME latinIme = getOwnerInstance(); 446 if (latinIme != null) { 447 executePendingImsCallback(latinIme, editorInfo, restarting); 448 latinIme.onStartInputInternal(editorInfo, restarting); 449 } 450 } 451 } 452 453 public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { 454 if (hasMessages(MSG_PENDING_IMS_CALLBACK) 455 && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) { 456 // Typically this is the second onStartInputView after orientation changed. 457 resetPendingImsCallback(); 458 } else { 459 if (mPendingSuccessiveImsCallback) { 460 // This is the first onStartInputView after orientation changed. 461 mPendingSuccessiveImsCallback = false; 462 resetPendingImsCallback(); 463 sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK), 464 PENDING_IMS_CALLBACK_DURATION); 465 } 466 final LatinIME latinIme = getOwnerInstance(); 467 if (latinIme != null) { 468 executePendingImsCallback(latinIme, editorInfo, restarting); 469 latinIme.onStartInputViewInternal(editorInfo, restarting); 470 mAppliedEditorInfo = editorInfo; 471 } 472 } 473 } 474 475 public void onFinishInputView(final boolean finishingInput) { 476 if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { 477 // Typically this is the first onFinishInputView after orientation changed. 478 mHasPendingFinishInputView = true; 479 } else { 480 final LatinIME latinIme = getOwnerInstance(); 481 if (latinIme != null) { 482 latinIme.onFinishInputViewInternal(finishingInput); 483 mAppliedEditorInfo = null; 484 } 485 } 486 } 487 488 public void onFinishInput() { 489 if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { 490 // Typically this is the first onFinishInput after orientation changed. 491 mHasPendingFinishInput = true; 492 } else { 493 final LatinIME latinIme = getOwnerInstance(); 494 if (latinIme != null) { 495 executePendingImsCallback(latinIme, null, false); 496 latinIme.onFinishInputInternal(); 497 } 498 } 499 } 500 } 501 502 static final class SubtypeState { 503 private InputMethodSubtype mLastActiveSubtype; 504 private boolean mCurrentSubtypeHasBeenUsed; 505 506 public void setCurrentSubtypeHasBeenUsed() { 507 mCurrentSubtypeHasBeenUsed = true; 508 } 509 510 public void switchSubtype(final IBinder token, final RichInputMethodManager richImm) { 511 final InputMethodSubtype currentSubtype = richImm.getInputMethodManager() 512 .getCurrentInputMethodSubtype(); 513 final InputMethodSubtype lastActiveSubtype = mLastActiveSubtype; 514 final boolean currentSubtypeHasBeenUsed = mCurrentSubtypeHasBeenUsed; 515 if (currentSubtypeHasBeenUsed) { 516 mLastActiveSubtype = currentSubtype; 517 mCurrentSubtypeHasBeenUsed = false; 518 } 519 if (currentSubtypeHasBeenUsed 520 && richImm.checkIfSubtypeBelongsToThisImeAndEnabled(lastActiveSubtype) 521 && !currentSubtype.equals(lastActiveSubtype)) { 522 richImm.setInputMethodAndSubtype(token, lastActiveSubtype); 523 return; 524 } 525 richImm.switchToNextInputMethod(token, true /* onlyCurrentIme */); 526 } 527 } 528 529 // Loading the native library eagerly to avoid unexpected UnsatisfiedLinkError at the initial 530 // JNI call as much as possible. 531 static { 532 JniUtils.loadNativeLibrary(); 533 } 534 535 public LatinIME() { 536 super(); 537 mSettings = Settings.getInstance(); 538 mSubtypeSwitcher = SubtypeSwitcher.getInstance(); 539 mKeyboardSwitcher = KeyboardSwitcher.getInstance(); 540 mSpecialKeyDetector = new SpecialKeyDetector(this); 541 mIsHardwareAcceleratedDrawingEnabled = 542 InputMethodServiceCompatUtils.enableHardwareAcceleration(this); 543 Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled); 544 } 545 546 @Override 547 public void onCreate() { 548 Settings.init(this); 549 DebugFlags.init(PreferenceManager.getDefaultSharedPreferences(this)); 550 RichInputMethodManager.init(this); 551 mRichImm = RichInputMethodManager.getInstance(); 552 SubtypeSwitcher.init(this); 553 KeyboardSwitcher.init(this); 554 AudioAndHapticFeedbackManager.init(this); 555 AccessibilityUtils.init(this); 556 StatsUtils.init(this); 557 558 super.onCreate(); 559 560 mHandler.onCreate(); 561 DEBUG = DebugFlags.DEBUG_ENABLED; 562 563 // TODO: Resolve mutual dependencies of {@link #loadSettings()} and {@link #initSuggest()}. 564 loadSettings(); 565 resetSuggest(); 566 567 // Register to receive ringer mode change and network state change. 568 // Also receive installation and removal of a dictionary pack. 569 final IntentFilter filter = new IntentFilter(); 570 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 571 filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); 572 registerReceiver(mConnectivityAndRingerModeChangeReceiver, filter); 573 574 final IntentFilter packageFilter = new IntentFilter(); 575 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 576 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 577 packageFilter.addDataScheme(SCHEME_PACKAGE); 578 registerReceiver(mDictionaryPackInstallReceiver, packageFilter); 579 580 final IntentFilter newDictFilter = new IntentFilter(); 581 newDictFilter.addAction(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION); 582 registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); 583 584 final IntentFilter dictDumpFilter = new IntentFilter(); 585 dictDumpFilter.addAction(DictionaryDumpBroadcastReceiver.DICTIONARY_DUMP_INTENT_ACTION); 586 registerReceiver(mDictionaryDumpBroadcastReceiver, dictDumpFilter); 587 588 DictionaryDecayBroadcastReciever.setUpIntervalAlarmForDictionaryDecaying(this); 589 590 StatsUtils.onCreate(mSettings.getCurrent()); 591 } 592 593 // Has to be package-visible for unit tests 594 @UsedForTesting 595 void loadSettings() { 596 final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 597 final EditorInfo editorInfo = getCurrentInputEditorInfo(); 598 final InputAttributes inputAttributes = new InputAttributes( 599 editorInfo, isFullscreenMode(), getPackageName()); 600 mSettings.loadSettings(this, locale, inputAttributes); 601 final SettingsValues currentSettingsValues = mSettings.getCurrent(); 602 AudioAndHapticFeedbackManager.getInstance().onSettingsChanged(currentSettingsValues); 603 // This method is called on startup and language switch, before the new layout has 604 // been displayed. Opening dictionaries never affects responsivity as dictionaries are 605 // asynchronously loaded. 606 if (!mHandler.hasPendingReopenDictionaries()) { 607 resetSuggestForLocale(locale); 608 } 609 mDictionaryFacilitator.updateEnabledSubtypes(mRichImm.getMyEnabledInputMethodSubtypeList( 610 true /* allowsImplicitlySelectedSubtypes */)); 611 refreshPersonalizationDictionarySession(currentSettingsValues); 612 StatsUtils.onLoadSettings(currentSettingsValues); 613 } 614 615 private void refreshPersonalizationDictionarySession( 616 final SettingsValues currentSettingsValues) { 617 mPersonalizationDictionaryUpdater.onLoadSettings( 618 currentSettingsValues.mUsePersonalizedDicts, 619 mSubtypeSwitcher.isSystemLocaleSameAsLocaleOfAllEnabledSubtypesOfEnabledImes()); 620 mContextualDictionaryUpdater.onLoadSettings(currentSettingsValues.mUsePersonalizedDicts); 621 final boolean shouldKeepUserHistoryDictionaries; 622 if (currentSettingsValues.mUsePersonalizedDicts) { 623 shouldKeepUserHistoryDictionaries = true; 624 } else { 625 shouldKeepUserHistoryDictionaries = false; 626 } 627 if (!shouldKeepUserHistoryDictionaries) { 628 // Remove user history dictionaries. 629 PersonalizationHelper.removeAllUserHistoryDictionaries(this); 630 mDictionaryFacilitator.clearUserHistoryDictionary(); 631 } 632 } 633 634 // Note that this method is called from a non-UI thread. 635 @Override 636 public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) { 637 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 638 if (mainKeyboardView != null) { 639 mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable); 640 } 641 if (mHandler.hasPendingWaitForDictionaryLoad()) { 642 mHandler.cancelWaitForDictionaryLoad(); 643 mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 644 false /* shouldDelay */); 645 } 646 } 647 648 private void resetSuggest() { 649 final Locale switcherSubtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 650 final String switcherLocaleStr = switcherSubtypeLocale.toString(); 651 final Locale subtypeLocale; 652 if (TextUtils.isEmpty(switcherLocaleStr)) { 653 // This happens in very rare corner cases - for example, immediately after a switch 654 // to LatinIME has been requested, about a frame later another switch happens. In this 655 // case, we are about to go down but we still don't know it, however the system tells 656 // us there is no current subtype so the locale is the empty string. Take the best 657 // possible guess instead -- it's bound to have no consequences, and we have no way 658 // of knowing anyway. 659 Log.e(TAG, "System is reporting no current subtype."); 660 subtypeLocale = getResources().getConfiguration().locale; 661 } else { 662 subtypeLocale = switcherSubtypeLocale; 663 } 664 resetSuggestForLocale(subtypeLocale); 665 } 666 667 /** 668 * Reset suggest by loading dictionaries for the locale and the current settings values. 669 * 670 * @param locale the locale 671 */ 672 private void resetSuggestForLocale(final Locale locale) { 673 final SettingsValues settingsValues = mSettings.getCurrent(); 674 mDictionaryFacilitator.resetDictionaries(this /* context */, locale, 675 settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, 676 false /* forceReloadMainDictionary */, this); 677 if (settingsValues.mAutoCorrectionEnabledPerUserSettings) { 678 mInputLogic.mSuggest.setAutoCorrectionThreshold( 679 settingsValues.mAutoCorrectionThreshold); 680 } 681 } 682 683 /** 684 * Reset suggest by loading the main dictionary of the current locale. 685 */ 686 /* package private */ void resetSuggestMainDict() { 687 final SettingsValues settingsValues = mSettings.getCurrent(); 688 mDictionaryFacilitator.resetDictionaries(this /* context */, 689 mDictionaryFacilitator.getLocale(), settingsValues.mUseContactsDict, 690 settingsValues.mUsePersonalizedDicts, true /* forceReloadMainDictionary */, this); 691 } 692 693 @Override 694 public void onDestroy() { 695 mDictionaryFacilitator.closeDictionaries(); 696 mPersonalizationDictionaryUpdater.onDestroy(); 697 mContextualDictionaryUpdater.onDestroy(); 698 mSettings.onDestroy(); 699 unregisterReceiver(mConnectivityAndRingerModeChangeReceiver); 700 unregisterReceiver(mDictionaryPackInstallReceiver); 701 unregisterReceiver(mDictionaryDumpBroadcastReceiver); 702 StatsUtils.onDestroy(); 703 super.onDestroy(); 704 } 705 706 @UsedForTesting 707 public void recycle() { 708 unregisterReceiver(mDictionaryPackInstallReceiver); 709 unregisterReceiver(mDictionaryDumpBroadcastReceiver); 710 unregisterReceiver(mConnectivityAndRingerModeChangeReceiver); 711 mInputLogic.recycle(); 712 } 713 714 @Override 715 public void onConfigurationChanged(final Configuration conf) { 716 SettingsValues settingsValues = mSettings.getCurrent(); 717 if (settingsValues.mDisplayOrientation != conf.orientation) { 718 mHandler.startOrientationChanging(); 719 mInputLogic.onOrientationChange(mSettings.getCurrent()); 720 } 721 if (settingsValues.mHasHardwareKeyboard != Settings.readHasHardwareKeyboard(conf)) { 722 // If the state of having a hardware keyboard changed, then we want to reload the 723 // settings to adjust for that. 724 // TODO: we should probably do this unconditionally here, rather than only when we 725 // have a change in hardware keyboard configuration. 726 loadSettings(); 727 settingsValues = mSettings.getCurrent(); 728 if (settingsValues.mHasHardwareKeyboard) { 729 // We call cleanupInternalStateForFinishInput() because it's the right thing to do; 730 // however, it seems at the moment the framework is passing us a seemingly valid 731 // but actually non-functional InputConnection object. So if this bug ever gets 732 // fixed we'll be able to remove the composition, but until it is this code is 733 // actually not doing much. 734 cleanupInternalStateForFinishInput(); 735 } 736 } 737 // TODO: Remove this test. 738 if (!conf.locale.equals(mPersonalizationDictionaryUpdater.getLocale())) { 739 refreshPersonalizationDictionarySession(settingsValues); 740 } 741 super.onConfigurationChanged(conf); 742 } 743 744 @Override 745 public View onCreateInputView() { 746 return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled); 747 } 748 749 @Override 750 public void setInputView(final View view) { 751 super.setInputView(view); 752 mInputView = view; 753 mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view); 754 if (hasSuggestionStripView()) { 755 mSuggestionStripView.setListener(this, view); 756 } 757 mInputLogic.setTextDecoratorUi(new TextDecoratorUi(this, view)); 758 } 759 760 @Override 761 public void setCandidatesView(final View view) { 762 // To ensure that CandidatesView will never be set. 763 return; 764 } 765 766 @Override 767 public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { 768 mHandler.onStartInput(editorInfo, restarting); 769 } 770 771 @Override 772 public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { 773 mHandler.onStartInputView(editorInfo, restarting); 774 } 775 776 @Override 777 public void onFinishInputView(final boolean finishingInput) { 778 mHandler.onFinishInputView(finishingInput); 779 } 780 781 @Override 782 public void onFinishInput() { 783 mHandler.onFinishInput(); 784 } 785 786 @Override 787 public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) { 788 // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() 789 // is not guaranteed. It may even be called at the same time on a different thread. 790 mSubtypeSwitcher.onSubtypeChanged(subtype); 791 mInputLogic.onSubtypeChanged(SubtypeLocaleUtils.getCombiningRulesExtraValue(subtype), 792 mSettings.getCurrent()); 793 loadKeyboard(); 794 } 795 796 private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { 797 super.onStartInput(editorInfo, restarting); 798 } 799 800 @SuppressWarnings("deprecation") 801 private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { 802 super.onStartInputView(editorInfo, restarting); 803 mRichImm.clearSubtypeCaches(); 804 final KeyboardSwitcher switcher = mKeyboardSwitcher; 805 switcher.updateKeyboardTheme(); 806 final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); 807 // If we are starting input in a different text field from before, we'll have to reload 808 // settings, so currentSettingsValues can't be final. 809 SettingsValues currentSettingsValues = mSettings.getCurrent(); 810 811 if (editorInfo == null) { 812 Log.e(TAG, "Null EditorInfo in onStartInputView()"); 813 if (DebugFlags.DEBUG_ENABLED) { 814 throw new NullPointerException("Null EditorInfo in onStartInputView()"); 815 } 816 return; 817 } 818 if (DEBUG) { 819 Log.d(TAG, "onStartInputView: editorInfo:" 820 + String.format("inputType=0x%08x imeOptions=0x%08x", 821 editorInfo.inputType, editorInfo.imeOptions)); 822 Log.d(TAG, "All caps = " 823 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) 824 + ", sentence caps = " 825 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) 826 + ", word caps = " 827 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); 828 } 829 Log.i(TAG, "Starting input. Cursor position = " 830 + editorInfo.initialSelStart + "," + editorInfo.initialSelEnd); 831 // TODO: Consolidate these checks with {@link InputAttributes}. 832 if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { 833 Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); 834 Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); 835 } 836 if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { 837 Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); 838 Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); 839 } 840 841 // In landscape mode, this method gets called without the input view being created. 842 if (mainKeyboardView == null) { 843 return; 844 } 845 846 // Forward this event to the accessibility utilities, if enabled. 847 final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); 848 if (accessUtils.isTouchExplorationEnabled()) { 849 accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); 850 } 851 852 final boolean inputTypeChanged = !currentSettingsValues.isSameInputType(editorInfo); 853 final boolean isDifferentTextField = !restarting || inputTypeChanged; 854 if (isDifferentTextField) { 855 mSubtypeSwitcher.updateParametersOnStartInputView(); 856 } 857 858 // The EditorInfo might have a flag that affects fullscreen mode. 859 // Note: This call should be done by InputMethodService? 860 updateFullscreenMode(); 861 862 // ALERT: settings have not been reloaded and there is a chance they may be stale. 863 // In the practice, if it is, we should have gotten onConfigurationChanged so it should 864 // be fine, but this is horribly confusing and must be fixed AS SOON AS POSSIBLE. 865 866 // In some cases the input connection has not been reset yet and we can't access it. In 867 // this case we will need to call loadKeyboard() later, when it's accessible, so that we 868 // can go into the correct mode, so we need to do some housekeeping here. 869 final boolean needToCallLoadKeyboardLater; 870 final Suggest suggest = mInputLogic.mSuggest; 871 if (!currentSettingsValues.mHasHardwareKeyboard) { 872 // The app calling setText() has the effect of clearing the composing 873 // span, so we should reset our state unconditionally, even if restarting is true. 874 // We also tell the input logic about the combining rules for the current subtype, so 875 // it can adjust its combiners if needed. 876 mInputLogic.startInput(mSubtypeSwitcher.getCombiningRulesExtraValueOfCurrentSubtype(), 877 currentSettingsValues); 878 879 // Note: the following does a round-trip IPC on the main thread: be careful 880 final Locale currentLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 881 if (null != currentLocale && !currentLocale.equals(suggest.getLocale())) { 882 // TODO: Do this automatically. 883 resetSuggest(); 884 } 885 886 // TODO[IL]: Can the following be moved to InputLogic#startInput? 887 if (!mInputLogic.mConnection.resetCachesUponCursorMoveAndReturnSuccess( 888 editorInfo.initialSelStart, editorInfo.initialSelEnd, 889 false /* shouldFinishComposition */)) { 890 // Sometimes, while rotating, for some reason the framework tells the app we are not 891 // connected to it and that means we can't refresh the cache. In this case, schedule 892 // a refresh later. 893 // We try resetting the caches up to 5 times before giving up. 894 mHandler.postResetCaches(isDifferentTextField, 5 /* remainingTries */); 895 // mLastSelection{Start,End} are reset later in this method, no need to do it here 896 needToCallLoadKeyboardLater = true; 897 } else { 898 // When rotating, initialSelStart and initialSelEnd sometimes are lying. Make a best 899 // effort to work around this bug. 900 mInputLogic.mConnection.tryFixLyingCursorPosition(); 901 mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 902 true /* shouldDelay */); 903 needToCallLoadKeyboardLater = false; 904 } 905 } else { 906 // If we have a hardware keyboard we don't need to call loadKeyboard later anyway. 907 needToCallLoadKeyboardLater = false; 908 } 909 910 if (isDifferentTextField || 911 !currentSettingsValues.hasSameOrientation(getResources().getConfiguration())) { 912 loadSettings(); 913 } 914 if (isDifferentTextField) { 915 mainKeyboardView.closing(); 916 currentSettingsValues = mSettings.getCurrent(); 917 918 if (currentSettingsValues.mAutoCorrectionEnabledPerUserSettings) { 919 suggest.setAutoCorrectionThreshold( 920 currentSettingsValues.mAutoCorrectionThreshold); 921 } 922 923 switcher.loadKeyboard(editorInfo, currentSettingsValues, getCurrentAutoCapsState(), 924 getCurrentRecapitalizeState()); 925 if (needToCallLoadKeyboardLater) { 926 // If we need to call loadKeyboard again later, we need to save its state now. The 927 // later call will be done in #retryResetCaches. 928 switcher.saveKeyboardState(); 929 } 930 } else if (restarting) { 931 // TODO: Come up with a more comprehensive way to reset the keyboard layout when 932 // a keyboard layout set doesn't get reloaded in this method. 933 switcher.resetKeyboardStateToAlphabet(getCurrentAutoCapsState(), 934 getCurrentRecapitalizeState()); 935 // In apps like Talk, we come here when the text is sent and the field gets emptied and 936 // we need to re-evaluate the shift state, but not the whole layout which would be 937 // disruptive. 938 // Space state must be updated before calling updateShiftState 939 switcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 940 getCurrentRecapitalizeState()); 941 } 942 // This will set the punctuation suggestions if next word suggestion is off; 943 // otherwise it will clear the suggestion strip. 944 setNeutralSuggestionStrip(); 945 946 mHandler.cancelUpdateSuggestionStrip(); 947 948 mainKeyboardView.setMainDictionaryAvailability( 949 mDictionaryFacilitator.hasInitializedMainDictionary()); 950 mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn, 951 currentSettingsValues.mKeyPreviewPopupDismissDelay); 952 mainKeyboardView.setSlidingKeyInputPreviewEnabled( 953 currentSettingsValues.mSlidingKeyInputPreviewEnabled); 954 mainKeyboardView.setGestureHandlingEnabledByUser( 955 currentSettingsValues.mGestureInputEnabled, 956 currentSettingsValues.mGestureTrailEnabled, 957 currentSettingsValues.mGestureFloatingPreviewTextEnabled); 958 959 // Contextual dictionary should be updated for the current application. 960 mContextualDictionaryUpdater.onStartInputView(editorInfo.packageName); 961 if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); 962 } 963 964 @Override 965 public void onWindowHidden() { 966 super.onWindowHidden(); 967 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 968 if (mainKeyboardView != null) { 969 mainKeyboardView.closing(); 970 } 971 } 972 973 private void onFinishInputInternal() { 974 super.onFinishInput(); 975 976 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 977 if (mainKeyboardView != null) { 978 mainKeyboardView.closing(); 979 } 980 } 981 982 private void onFinishInputViewInternal(final boolean finishingInput) { 983 super.onFinishInputView(finishingInput); 984 cleanupInternalStateForFinishInput(); 985 } 986 987 private void cleanupInternalStateForFinishInput() { 988 mKeyboardSwitcher.deallocateMemory(); 989 // Remove pending messages related to update suggestions 990 mHandler.cancelUpdateSuggestionStrip(); 991 // Should do the following in onFinishInputInternal but until JB MR2 it's not called :( 992 mInputLogic.finishInput(); 993 } 994 995 @Override 996 public void onUpdateSelection(final int oldSelStart, final int oldSelEnd, 997 final int newSelStart, final int newSelEnd, 998 final int composingSpanStart, final int composingSpanEnd) { 999 super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, 1000 composingSpanStart, composingSpanEnd); 1001 if (DEBUG) { 1002 Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd 1003 + ", nss=" + newSelStart + ", nse=" + newSelEnd 1004 + ", cs=" + composingSpanStart + ", ce=" + composingSpanEnd); 1005 } 1006 1007 // This call happens when we have a hardware keyboard as well as when we don't. While we 1008 // don't support hardware keyboards yet we should avoid doing the processing associated 1009 // with cursor movement when we have a hardware keyboard since we are not in charge. 1010 final SettingsValues settingsValues = mSettings.getCurrent(); 1011 if ((!settingsValues.mHasHardwareKeyboard || ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) 1012 && mInputLogic.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd)) { 1013 mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 1014 getCurrentRecapitalizeState()); 1015 } 1016 } 1017 1018 // We cannot mark this method as @Override until new SDK becomes publicly available. 1019 // @Override 1020 public void onUpdateCursorAnchorInfo(final CursorAnchorInfo info) { 1021 if (ProductionFlags.ENABLE_CURSOR_ANCHOR_INFO_CALLBACK) { 1022 mInputLogic.onUpdateCursorAnchorInfo(CursorAnchorInfoCompatWrapper.fromObject(info)); 1023 } 1024 } 1025 1026 /** 1027 * This is called when the user has clicked on the extracted text view, 1028 * when running in fullscreen mode. The default implementation hides 1029 * the suggestions view when this happens, but only if the extracted text 1030 * editor has a vertical scroll bar because its text doesn't fit. 1031 * Here we override the behavior due to the possibility that a re-correction could 1032 * cause the suggestions strip to disappear and re-appear. 1033 */ 1034 @Override 1035 public void onExtractedTextClicked() { 1036 if (mSettings.getCurrent().needsToLookupSuggestions()) { 1037 return; 1038 } 1039 1040 super.onExtractedTextClicked(); 1041 } 1042 1043 /** 1044 * This is called when the user has performed a cursor movement in the 1045 * extracted text view, when it is running in fullscreen mode. The default 1046 * implementation hides the suggestions view when a vertical movement 1047 * happens, but only if the extracted text editor has a vertical scroll bar 1048 * because its text doesn't fit. 1049 * Here we override the behavior due to the possibility that a re-correction could 1050 * cause the suggestions strip to disappear and re-appear. 1051 */ 1052 @Override 1053 public void onExtractedCursorMovement(final int dx, final int dy) { 1054 if (mSettings.getCurrent().needsToLookupSuggestions()) { 1055 return; 1056 } 1057 1058 super.onExtractedCursorMovement(dx, dy); 1059 } 1060 1061 @Override 1062 public void hideWindow() { 1063 mKeyboardSwitcher.onHideWindow(); 1064 1065 if (TRACE) Debug.stopMethodTracing(); 1066 if (isShowingOptionDialog()) { 1067 mOptionsDialog.dismiss(); 1068 mOptionsDialog = null; 1069 } 1070 super.hideWindow(); 1071 } 1072 1073 @Override 1074 public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) { 1075 if (DEBUG) { 1076 Log.i(TAG, "Received completions:"); 1077 if (applicationSpecifiedCompletions != null) { 1078 for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { 1079 Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); 1080 } 1081 } 1082 } 1083 if (!mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) { 1084 return; 1085 } 1086 // If we have an update request in flight, we need to cancel it so it does not override 1087 // these completions. 1088 mHandler.cancelUpdateSuggestionStrip(); 1089 if (applicationSpecifiedCompletions == null) { 1090 setNeutralSuggestionStrip(); 1091 return; 1092 } 1093 1094 final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords = 1095 SuggestedWords.getFromApplicationSpecifiedCompletions( 1096 applicationSpecifiedCompletions); 1097 final SuggestedWords suggestedWords = new SuggestedWords(applicationSuggestedWords, 1098 null /* rawSuggestions */, false /* typedWordValid */, false /* willAutoCorrect */, 1099 false /* isObsoleteSuggestions */, 1100 SuggestedWords.INPUT_STYLE_APPLICATION_SPECIFIED /* inputStyle */); 1101 // When in fullscreen mode, show completions generated by the application forcibly 1102 setSuggestedWords(suggestedWords); 1103 } 1104 1105 @Override 1106 public void onComputeInsets(final InputMethodService.Insets outInsets) { 1107 super.onComputeInsets(outInsets); 1108 final SettingsValues settingsValues = mSettings.getCurrent(); 1109 final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView(); 1110 if (visibleKeyboardView == null || !hasSuggestionStripView()) { 1111 return; 1112 } 1113 final int inputHeight = mInputView.getHeight(); 1114 final boolean hasHardwareKeyboard = settingsValues.mHasHardwareKeyboard; 1115 if (hasHardwareKeyboard && visibleKeyboardView.getVisibility() == View.GONE) { 1116 // If there is a hardware keyboard and a visible software keyboard view has been hidden, 1117 // no visual element will be shown on the screen. 1118 outInsets.touchableInsets = inputHeight; 1119 outInsets.visibleTopInsets = inputHeight; 1120 return; 1121 } 1122 final int suggestionsHeight = (!mKeyboardSwitcher.isShowingEmojiPalettes() 1123 && mSuggestionStripView.getVisibility() == View.VISIBLE) 1124 ? mSuggestionStripView.getHeight() : 0; 1125 final int visibleTopY = inputHeight - visibleKeyboardView.getHeight() - suggestionsHeight; 1126 mSuggestionStripView.setMoreSuggestionsHeight(visibleTopY); 1127 // Need to set touchable region only if a keyboard view is being shown. 1128 if (visibleKeyboardView.isShown()) { 1129 final int touchLeft = 0; 1130 final int touchTop = mKeyboardSwitcher.isShowingMoreKeysPanel() ? 0 : visibleTopY; 1131 final int touchRight = visibleKeyboardView.getWidth(); 1132 final int touchBottom = inputHeight 1133 // Extend touchable region below the keyboard. 1134 + EXTENDED_TOUCHABLE_REGION_HEIGHT; 1135 outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; 1136 outInsets.touchableRegion.set(touchLeft, touchTop, touchRight, touchBottom); 1137 } 1138 outInsets.contentTopInsets = visibleTopY; 1139 outInsets.visibleTopInsets = visibleTopY; 1140 } 1141 1142 @Override 1143 public boolean onEvaluateInputViewShown() { 1144 // Always show {@link InputView}. 1145 return true; 1146 } 1147 1148 @Override 1149 public boolean onShowInputRequested(final int flags, final boolean configChange) { 1150 final SettingsValues settingsValues = mSettings.getCurrent(); 1151 if ((flags & InputMethod.SHOW_EXPLICIT) == 0 && settingsValues.mHasHardwareKeyboard) { 1152 // Even when IME is implicitly shown and physical keyboard is connected, we should 1153 // show {@link InputView}. 1154 // See {@link InputMethodService#onShowInputRequested(int,boolean)}. 1155 return true; 1156 } 1157 return super.onShowInputRequested(flags, configChange); 1158 } 1159 1160 @Override 1161 public boolean onEvaluateFullscreenMode() { 1162 final SettingsValues settingsValues = mSettings.getCurrent(); 1163 if (settingsValues.mHasHardwareKeyboard) { 1164 // If there is a hardware keyboard, disable full screen mode. 1165 return false; 1166 } 1167 // Reread resource value here, because this method is called by the framework as needed. 1168 final boolean isFullscreenModeAllowed = Settings.readUseFullscreenMode(getResources()); 1169 if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) { 1170 // TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI 1171 // implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI 1172 // without NO_FULLSCREEN doesn't work as expected. Because of this we need this 1173 // hack for now. Let's get rid of this once the framework gets fixed. 1174 final EditorInfo ei = getCurrentInputEditorInfo(); 1175 return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0)); 1176 } else { 1177 return false; 1178 } 1179 } 1180 1181 @Override 1182 public void updateFullscreenMode() { 1183 // Override layout parameters to expand {@link SoftInputWindow} to the entire screen. 1184 // See {@link InputMethodService#setinputView(View) and 1185 // {@link SoftInputWindow#updateWidthHeight(WindowManager.LayoutParams)}. 1186 final Window window = getWindow().getWindow(); 1187 ViewLayoutUtils.updateLayoutHeightOf(window, LayoutParams.MATCH_PARENT); 1188 // This method may be called before {@link #setInputView(View)}. 1189 if (mInputView != null) { 1190 // In non-fullscreen mode, {@link InputView} and its parent inputArea should expand to 1191 // the entire screen and be placed at the bottom of {@link SoftInputWindow}. 1192 // In fullscreen mode, these shouldn't expand to the entire screen and should be 1193 // coexistent with {@link #mExtractedArea} above. 1194 // See {@link InputMethodService#setInputView(View) and 1195 // com.android.internal.R.layout.input_method.xml. 1196 final int layoutHeight = isFullscreenMode() 1197 ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT; 1198 final View inputArea = window.findViewById(android.R.id.inputArea); 1199 ViewLayoutUtils.updateLayoutHeightOf(inputArea, layoutHeight); 1200 ViewLayoutUtils.updateLayoutGravityOf(inputArea, Gravity.BOTTOM); 1201 ViewLayoutUtils.updateLayoutHeightOf(mInputView, layoutHeight); 1202 } 1203 super.updateFullscreenMode(); 1204 mInputLogic.onUpdateFullscreenMode(isFullscreenMode()); 1205 } 1206 1207 private int getCurrentAutoCapsState() { 1208 return mInputLogic.getCurrentAutoCapsState(mSettings.getCurrent()); 1209 } 1210 1211 private int getCurrentRecapitalizeState() { 1212 return mInputLogic.getCurrentRecapitalizeState(); 1213 } 1214 1215 public Locale getCurrentSubtypeLocale() { 1216 return mSubtypeSwitcher.getCurrentSubtypeLocale(); 1217 } 1218 1219 /** 1220 * @param codePoints code points to get coordinates for. 1221 * @return x,y coordinates for this keyboard, as a flattened array. 1222 */ 1223 public int[] getCoordinatesForCurrentKeyboard(final int[] codePoints) { 1224 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1225 if (null == keyboard) { 1226 return CoordinateUtils.newCoordinateArray(codePoints.length, 1227 Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); 1228 } else { 1229 return keyboard.getCoordinates(codePoints); 1230 } 1231 } 1232 1233 // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is 1234 // pressed. 1235 @Override 1236 public void addWordToUserDictionary(final String word) { 1237 if (TextUtils.isEmpty(word)) { 1238 // Probably never supposed to happen, but just in case. 1239 return; 1240 } 1241 final String wordToEdit; 1242 if (CapsModeUtils.isAutoCapsMode(mInputLogic.mLastComposedWord.mCapitalizedMode)) { 1243 wordToEdit = word.toLowerCase(getCurrentSubtypeLocale()); 1244 } else { 1245 wordToEdit = word; 1246 } 1247 mDictionaryFacilitator.addWordToUserDictionary(this /* context */, wordToEdit); 1248 mInputLogic.onAddWordToUserDictionary(); 1249 } 1250 1251 // Callback for the {@link SuggestionStripView}, to call when the important notice strip is 1252 // pressed. 1253 @Override 1254 public void showImportantNoticeContents() { 1255 showOptionDialog(new ImportantNoticeDialog(this /* context */, this /* listener */)); 1256 } 1257 1258 // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener} 1259 @Override 1260 public void onClickSettingsOfImportantNoticeDialog(final int nextVersion) { 1261 launchSettings(); 1262 } 1263 1264 // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener} 1265 @Override 1266 public void onUserAcknowledgmentOfImportantNoticeDialog(final int nextVersion) { 1267 setNeutralSuggestionStrip(); 1268 } 1269 1270 public void displaySettingsDialog() { 1271 if (isShowingOptionDialog()) { 1272 return; 1273 } 1274 showSubtypeSelectorAndSettings(); 1275 } 1276 1277 @Override 1278 public boolean onCustomRequest(final int requestCode) { 1279 if (isShowingOptionDialog()) return false; 1280 switch (requestCode) { 1281 case Constants.CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER: 1282 if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { 1283 mRichImm.getInputMethodManager().showInputMethodPicker(); 1284 return true; 1285 } 1286 return false; 1287 } 1288 return false; 1289 } 1290 1291 private boolean isShowingOptionDialog() { 1292 return mOptionsDialog != null && mOptionsDialog.isShowing(); 1293 } 1294 1295 // TODO: Revise the language switch key behavior to make it much smarter and more reasonable. 1296 public void switchToNextSubtype() { 1297 final IBinder token = getWindow().getWindow().getAttributes().token; 1298 if (shouldSwitchToOtherInputMethods()) { 1299 mRichImm.switchToNextInputMethod(token, false /* onlyCurrentIme */); 1300 return; 1301 } 1302 mSubtypeState.switchSubtype(token, mRichImm); 1303 } 1304 1305 // Implementation of {@link KeyboardActionListener}. 1306 @Override 1307 public void onCodeInput(final int codePoint, final int x, final int y, 1308 final boolean isKeyRepeat) { 1309 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1310 // x and y include some padding, but everything down the line (especially native 1311 // code) needs the coordinates in the keyboard frame. 1312 // TODO: We should reconsider which coordinate system should be used to represent 1313 // keyboard event. Also we should pull this up -- LatinIME has no business doing 1314 // this transformation, it should be done already before calling onCodeInput. 1315 final int keyX = mainKeyboardView.getKeyX(x); 1316 final int keyY = mainKeyboardView.getKeyY(y); 1317 final int codeToSend; 1318 if (Constants.CODE_SHIFT == codePoint) { 1319 // TODO: Instead of checking for alphabetic keyboard here, separate keycodes for 1320 // alphabetic shift and shift while in symbol layout. 1321 final Keyboard currentKeyboard = mKeyboardSwitcher.getKeyboard(); 1322 if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) { 1323 codeToSend = codePoint; 1324 } else { 1325 codeToSend = Constants.CODE_SYMBOL_SHIFT; 1326 } 1327 } else { 1328 codeToSend = codePoint; 1329 } 1330 if (Constants.CODE_SHORTCUT == codePoint) { 1331 mSubtypeSwitcher.switchToShortcutIME(this); 1332 // Still call the *#onCodeInput methods for readability. 1333 } 1334 final Event event = createSoftwareKeypressEvent(codeToSend, keyX, keyY, isKeyRepeat); 1335 final InputTransaction completeInputTransaction = 1336 mInputLogic.onCodeInput(mSettings.getCurrent(), event, 1337 mKeyboardSwitcher.getKeyboardShiftMode(), 1338 mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler); 1339 updateStateAfterInputTransaction(completeInputTransaction); 1340 mKeyboardSwitcher.onCodeInput(codePoint, getCurrentAutoCapsState(), 1341 getCurrentRecapitalizeState()); 1342 } 1343 1344 // A helper method to split the code point and the key code. Ultimately, they should not be 1345 // squashed into the same variable, and this method should be removed. 1346 private static Event createSoftwareKeypressEvent(final int keyCodeOrCodePoint, final int keyX, 1347 final int keyY, final boolean isKeyRepeat) { 1348 final int keyCode; 1349 final int codePoint; 1350 if (keyCodeOrCodePoint <= 0) { 1351 keyCode = keyCodeOrCodePoint; 1352 codePoint = Event.NOT_A_CODE_POINT; 1353 } else { 1354 keyCode = Event.NOT_A_KEY_CODE; 1355 codePoint = keyCodeOrCodePoint; 1356 } 1357 return Event.createSoftwareKeypressEvent(codePoint, keyCode, keyX, keyY, isKeyRepeat); 1358 } 1359 1360 // Called from PointerTracker through the KeyboardActionListener interface 1361 @Override 1362 public void onTextInput(final String rawText) { 1363 // TODO: have the keyboard pass the correct key code when we need it. 1364 final Event event = Event.createSoftwareTextEvent(rawText, Event.NOT_A_KEY_CODE); 1365 final InputTransaction completeInputTransaction = 1366 mInputLogic.onTextInput(mSettings.getCurrent(), event, 1367 mKeyboardSwitcher.getKeyboardShiftMode(), mHandler); 1368 updateStateAfterInputTransaction(completeInputTransaction); 1369 mKeyboardSwitcher.onCodeInput(Constants.CODE_OUTPUT_TEXT, getCurrentAutoCapsState(), 1370 getCurrentRecapitalizeState()); 1371 } 1372 1373 @Override 1374 public void onStartBatchInput() { 1375 mInputLogic.onStartBatchInput(mSettings.getCurrent(), mKeyboardSwitcher, mHandler); 1376 } 1377 1378 @Override 1379 public void onUpdateBatchInput(final InputPointers batchPointers) { 1380 mInputLogic.onUpdateBatchInput(mSettings.getCurrent(), batchPointers, mKeyboardSwitcher); 1381 } 1382 1383 @Override 1384 public void onEndBatchInput(final InputPointers batchPointers) { 1385 mInputLogic.onEndBatchInput(batchPointers); 1386 } 1387 1388 @Override 1389 public void onCancelBatchInput() { 1390 mInputLogic.onCancelBatchInput(mHandler); 1391 } 1392 1393 // This method must run on the UI Thread. 1394 private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, 1395 final boolean dismissGestureFloatingPreviewText) { 1396 showSuggestionStrip(suggestedWords); 1397 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1398 mainKeyboardView.showGestureFloatingPreviewText(suggestedWords); 1399 if (dismissGestureFloatingPreviewText) { 1400 mainKeyboardView.dismissGestureFloatingPreviewText(); 1401 } 1402 } 1403 1404 // Called from PointerTracker through the KeyboardActionListener interface 1405 @Override 1406 public void onFinishSlidingInput() { 1407 // User finished sliding input. 1408 mKeyboardSwitcher.onFinishSlidingInput(getCurrentAutoCapsState(), 1409 getCurrentRecapitalizeState()); 1410 } 1411 1412 // Called from PointerTracker through the KeyboardActionListener interface 1413 @Override 1414 public void onCancelInput() { 1415 // User released a finger outside any key 1416 // Nothing to do so far. 1417 } 1418 1419 public boolean hasSuggestionStripView() { 1420 return null != mSuggestionStripView; 1421 } 1422 1423 @Override 1424 public boolean isShowingAddToDictionaryHint() { 1425 return hasSuggestionStripView() && mSuggestionStripView.isShowingAddToDictionaryHint(); 1426 } 1427 1428 @Override 1429 public void dismissAddToDictionaryHint() { 1430 if (!hasSuggestionStripView()) { 1431 return; 1432 } 1433 mSuggestionStripView.dismissAddToDictionaryHint(); 1434 } 1435 1436 private void setSuggestedWords(final SuggestedWords suggestedWords) { 1437 final SettingsValues currentSettingsValues = mSettings.getCurrent(); 1438 mInputLogic.setSuggestedWords(suggestedWords, currentSettingsValues, mHandler); 1439 // TODO: Modify this when we support suggestions with hard keyboard 1440 if (!hasSuggestionStripView()) { 1441 return; 1442 } 1443 if (!onEvaluateInputViewShown()) { 1444 return; 1445 } 1446 1447 final boolean shouldShowImportantNotice = 1448 ImportantNoticeUtils.shouldShowImportantNotice(this); 1449 final boolean shouldShowSuggestionCandidates = 1450 currentSettingsValues.mInputAttributes.mShouldShowSuggestions 1451 && currentSettingsValues.isSuggestionsEnabledPerUserSettings(); 1452 final boolean shouldShowSuggestionsStripUnlessPassword = shouldShowImportantNotice 1453 || currentSettingsValues.mShowsVoiceInputKey 1454 || shouldShowSuggestionCandidates 1455 || currentSettingsValues.isApplicationSpecifiedCompletionsOn(); 1456 final boolean shouldShowSuggestionsStrip = shouldShowSuggestionsStripUnlessPassword 1457 && !currentSettingsValues.mInputAttributes.mIsPasswordField; 1458 mSuggestionStripView.updateVisibility(shouldShowSuggestionsStrip, isFullscreenMode()); 1459 if (!shouldShowSuggestionsStrip) { 1460 return; 1461 } 1462 1463 final boolean isEmptyApplicationSpecifiedCompletions = 1464 currentSettingsValues.isApplicationSpecifiedCompletionsOn() 1465 && suggestedWords.isEmpty(); 1466 final boolean noSuggestionsToShow = (SuggestedWords.EMPTY == suggestedWords) 1467 || suggestedWords.isPunctuationSuggestions() 1468 || isEmptyApplicationSpecifiedCompletions; 1469 if (shouldShowImportantNotice && noSuggestionsToShow) { 1470 if (mSuggestionStripView.maybeShowImportantNoticeTitle()) { 1471 return; 1472 } 1473 } 1474 1475 if (currentSettingsValues.isSuggestionsEnabledPerUserSettings() 1476 // We should clear suggestions if there is no suggestion to show. 1477 || noSuggestionsToShow 1478 || currentSettingsValues.isApplicationSpecifiedCompletionsOn()) { 1479 mSuggestionStripView.setSuggestions(suggestedWords, 1480 SubtypeLocaleUtils.isRtlLanguage(mSubtypeSwitcher.getCurrentSubtype())); 1481 } 1482 } 1483 1484 // TODO[IL]: Move this out of LatinIME. 1485 public void getSuggestedWords(final int inputStyle, final int sequenceNumber, 1486 final OnGetSuggestedWordsCallback callback) { 1487 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1488 if (keyboard == null) { 1489 callback.onGetSuggestedWords(SuggestedWords.EMPTY); 1490 return; 1491 } 1492 mInputLogic.getSuggestedWords(mSettings.getCurrent(), keyboard.getProximityInfo(), 1493 mKeyboardSwitcher.getKeyboardShiftMode(), inputStyle, sequenceNumber, callback); 1494 } 1495 1496 @Override 1497 public void showSuggestionStrip(final SuggestedWords sourceSuggestedWords) { 1498 final SuggestedWords suggestedWords = 1499 sourceSuggestedWords.isEmpty() ? SuggestedWords.EMPTY : sourceSuggestedWords; 1500 if (SuggestedWords.EMPTY == suggestedWords) { 1501 setNeutralSuggestionStrip(); 1502 } else { 1503 setSuggestedWords(suggestedWords); 1504 } 1505 // Cache the auto-correction in accessibility code so we can speak it if the user 1506 // touches a key that will insert it. 1507 AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords, 1508 sourceSuggestedWords.mTypedWord); 1509 } 1510 1511 // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 1512 // interface 1513 @Override 1514 public void pickSuggestionManually(final SuggestedWordInfo suggestionInfo) { 1515 final InputTransaction completeInputTransaction = mInputLogic.onPickSuggestionManually( 1516 mSettings.getCurrent(), suggestionInfo, 1517 mKeyboardSwitcher.getKeyboardShiftMode(), 1518 mKeyboardSwitcher.getCurrentKeyboardScriptId(), 1519 mHandler); 1520 updateStateAfterInputTransaction(completeInputTransaction); 1521 } 1522 1523 @Override 1524 public void showAddToDictionaryHint(final String word) { 1525 if (!hasSuggestionStripView()) { 1526 return; 1527 } 1528 mSuggestionStripView.showAddToDictionaryHint(word); 1529 } 1530 1531 // This will show either an empty suggestion strip (if prediction is enabled) or 1532 // punctuation suggestions (if it's disabled). 1533 @Override 1534 public void setNeutralSuggestionStrip() { 1535 final SettingsValues currentSettings = mSettings.getCurrent(); 1536 final SuggestedWords neutralSuggestions = currentSettings.mBigramPredictionEnabled 1537 ? SuggestedWords.EMPTY : currentSettings.mSpacingAndPunctuations.mSuggestPuncList; 1538 setSuggestedWords(neutralSuggestions); 1539 } 1540 1541 // TODO: Make this private 1542 // Outside LatinIME, only used by the {@link InputTestsBase} test suite. 1543 @UsedForTesting 1544 void loadKeyboard() { 1545 // Since we are switching languages, the most urgent thing is to let the keyboard graphics 1546 // update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on 1547 // the screen. Anything we do right now will delay this, so wait until the next frame 1548 // before we do the rest, like reopening dictionaries and updating suggestions. So we 1549 // post a message. 1550 mHandler.postReopenDictionaries(); 1551 loadSettings(); 1552 if (mKeyboardSwitcher.getMainKeyboardView() != null) { 1553 // Reload keyboard because the current language has been changed. 1554 mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent(), 1555 getCurrentAutoCapsState(), getCurrentRecapitalizeState()); 1556 } 1557 } 1558 1559 /** 1560 * After an input transaction has been executed, some state must be updated. This includes 1561 * the shift state of the keyboard and suggestions. This method looks at the finished 1562 * inputTransaction to find out what is necessary and updates the state accordingly. 1563 * @param inputTransaction The transaction that has been executed. 1564 */ 1565 private void updateStateAfterInputTransaction(final InputTransaction inputTransaction) { 1566 switch (inputTransaction.getRequiredShiftUpdate()) { 1567 case InputTransaction.SHIFT_UPDATE_LATER: 1568 mHandler.postUpdateShiftState(); 1569 break; 1570 case InputTransaction.SHIFT_UPDATE_NOW: 1571 mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 1572 getCurrentRecapitalizeState()); 1573 break; 1574 default: // SHIFT_NO_UPDATE 1575 } 1576 if (inputTransaction.requiresUpdateSuggestions()) { 1577 final int inputStyle; 1578 if (inputTransaction.mEvent.isSuggestionStripPress()) { 1579 // Suggestion strip press: no input. 1580 inputStyle = SuggestedWords.INPUT_STYLE_NONE; 1581 } else if (inputTransaction.mEvent.isGesture()) { 1582 inputStyle = SuggestedWords.INPUT_STYLE_TAIL_BATCH; 1583 } else { 1584 inputStyle = SuggestedWords.INPUT_STYLE_TYPING; 1585 } 1586 mHandler.postUpdateSuggestionStrip(inputStyle); 1587 } 1588 if (inputTransaction.didAffectContents()) { 1589 mSubtypeState.setCurrentSubtypeHasBeenUsed(); 1590 } 1591 } 1592 1593 private void hapticAndAudioFeedback(final int code, final int repeatCount) { 1594 final MainKeyboardView keyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1595 if (keyboardView != null && keyboardView.isInDraggingFinger()) { 1596 // No need to feedback while finger is dragging. 1597 return; 1598 } 1599 if (repeatCount > 0) { 1600 if (code == Constants.CODE_DELETE && !mInputLogic.mConnection.canDeleteCharacters()) { 1601 // No need to feedback when repeat delete key will have no effect. 1602 return; 1603 } 1604 // TODO: Use event time that the last feedback has been generated instead of relying on 1605 // a repeat count to thin out feedback. 1606 if (repeatCount % PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT == 0) { 1607 return; 1608 } 1609 } 1610 final AudioAndHapticFeedbackManager feedbackManager = 1611 AudioAndHapticFeedbackManager.getInstance(); 1612 if (repeatCount == 0) { 1613 // TODO: Reconsider how to perform haptic feedback when repeating key. 1614 feedbackManager.performHapticFeedback(keyboardView); 1615 } 1616 feedbackManager.performAudioFeedback(code); 1617 } 1618 1619 // Callback of the {@link KeyboardActionListener}. This is called when a key is depressed; 1620 // release matching call is {@link #onReleaseKey(int,boolean)} below. 1621 @Override 1622 public void onPressKey(final int primaryCode, final int repeatCount, 1623 final boolean isSinglePointer) { 1624 mKeyboardSwitcher.onPressKey(primaryCode, isSinglePointer, getCurrentAutoCapsState(), 1625 getCurrentRecapitalizeState()); 1626 hapticAndAudioFeedback(primaryCode, repeatCount); 1627 } 1628 1629 // Callback of the {@link KeyboardActionListener}. This is called when a key is released; 1630 // press matching call is {@link #onPressKey(int,int,boolean)} above. 1631 @Override 1632 public void onReleaseKey(final int primaryCode, final boolean withSliding) { 1633 mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding, getCurrentAutoCapsState(), 1634 getCurrentRecapitalizeState()); 1635 } 1636 1637 private HardwareEventDecoder getHardwareKeyEventDecoder(final int deviceId) { 1638 final HardwareEventDecoder decoder = mHardwareEventDecoders.get(deviceId); 1639 if (null != decoder) return decoder; 1640 // TODO: create the decoder according to the specification 1641 final HardwareEventDecoder newDecoder = new HardwareKeyboardEventDecoder(deviceId); 1642 mHardwareEventDecoders.put(deviceId, newDecoder); 1643 return newDecoder; 1644 } 1645 1646 // Hooks for hardware keyboard 1647 @Override 1648 public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) { 1649 mSpecialKeyDetector.onKeyDown(keyEvent); 1650 if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { 1651 return super.onKeyDown(keyCode, keyEvent); 1652 } 1653 final Event event = getHardwareKeyEventDecoder( 1654 keyEvent.getDeviceId()).decodeHardwareKey(keyEvent); 1655 // If the event is not handled by LatinIME, we just pass it to the parent implementation. 1656 // If it's handled, we return true because we did handle it. 1657 if (event.isHandled()) { 1658 mInputLogic.onCodeInput(mSettings.getCurrent(), event, 1659 mKeyboardSwitcher.getKeyboardShiftMode(), 1660 // TODO: this is not necessarily correct for a hardware keyboard right now 1661 mKeyboardSwitcher.getCurrentKeyboardScriptId(), 1662 mHandler); 1663 return true; 1664 } 1665 return super.onKeyDown(keyCode, keyEvent); 1666 } 1667 1668 @Override 1669 public boolean onKeyUp(final int keyCode, final KeyEvent keyEvent) { 1670 mSpecialKeyDetector.onKeyUp(keyEvent); 1671 if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { 1672 return super.onKeyUp(keyCode, keyEvent); 1673 } 1674 final long keyIdentifier = keyEvent.getDeviceId() << 32 + keyEvent.getKeyCode(); 1675 if (mInputLogic.mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) { 1676 return true; 1677 } 1678 return super.onKeyUp(keyCode, keyEvent); 1679 } 1680 1681 // onKeyDown and onKeyUp are the main events we are interested in. There are two more events 1682 // related to handling of hardware key events that we may want to implement in the future: 1683 // boolean onKeyLongPress(final int keyCode, final KeyEvent event); 1684 // boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event); 1685 1686 // receive ringer mode change and network state change. 1687 private final BroadcastReceiver mConnectivityAndRingerModeChangeReceiver = 1688 new BroadcastReceiver() { 1689 @Override 1690 public void onReceive(final Context context, final Intent intent) { 1691 final String action = intent.getAction(); 1692 if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 1693 mSubtypeSwitcher.onNetworkStateChanged(intent); 1694 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { 1695 AudioAndHapticFeedbackManager.getInstance().onRingerModeChanged(); 1696 } 1697 } 1698 }; 1699 1700 private void launchSettings() { 1701 mInputLogic.commitTyped(mSettings.getCurrent(), LastComposedWord.NOT_A_SEPARATOR); 1702 requestHideSelf(0); 1703 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1704 if (mainKeyboardView != null) { 1705 mainKeyboardView.closing(); 1706 } 1707 final Intent intent = new Intent(); 1708 intent.setClass(LatinIME.this, SettingsActivity.class); 1709 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 1710 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 1711 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 1712 intent.putExtra(SettingsActivity.EXTRA_SHOW_HOME_AS_UP, false); 1713 startActivity(intent); 1714 } 1715 1716 private void showSubtypeSelectorAndSettings() { 1717 final CharSequence title = getString(R.string.english_ime_input_options); 1718 // TODO: Should use new string "Select active input modes". 1719 final CharSequence languageSelectionTitle = getString(R.string.language_selection_title); 1720 final CharSequence[] items = new CharSequence[] { 1721 languageSelectionTitle, 1722 getString(ApplicationUtils.getActivityTitleResId(this, SettingsActivity.class)) 1723 }; 1724 final OnClickListener listener = new OnClickListener() { 1725 @Override 1726 public void onClick(DialogInterface di, int position) { 1727 di.dismiss(); 1728 switch (position) { 1729 case 0: 1730 final Intent intent = IntentUtils.getInputLanguageSelectionIntent( 1731 mRichImm.getInputMethodIdOfThisIme(), 1732 Intent.FLAG_ACTIVITY_NEW_TASK 1733 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 1734 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 1735 intent.putExtra(Intent.EXTRA_TITLE, languageSelectionTitle); 1736 startActivity(intent); 1737 break; 1738 case 1: 1739 launchSettings(); 1740 break; 1741 } 1742 } 1743 }; 1744 final AlertDialog.Builder builder = new AlertDialog.Builder( 1745 DialogUtils.getPlatformDialogThemeContext(this)); 1746 builder.setItems(items, listener).setTitle(title); 1747 final AlertDialog dialog = builder.create(); 1748 dialog.setCancelable(true /* cancelable */); 1749 dialog.setCanceledOnTouchOutside(true /* cancelable */); 1750 showOptionDialog(dialog); 1751 } 1752 1753 // TODO: Move this method out of {@link LatinIME}. 1754 private void showOptionDialog(final AlertDialog dialog) { 1755 final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken(); 1756 if (windowToken == null) { 1757 return; 1758 } 1759 1760 final Window window = dialog.getWindow(); 1761 final WindowManager.LayoutParams lp = window.getAttributes(); 1762 lp.token = windowToken; 1763 lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; 1764 window.setAttributes(lp); 1765 window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 1766 1767 mOptionsDialog = dialog; 1768 dialog.show(); 1769 } 1770 1771 // TODO: can this be removed somehow without breaking the tests? 1772 @UsedForTesting 1773 /* package for test */ SuggestedWords getSuggestedWordsForTest() { 1774 // You may not use this method for anything else than debug 1775 return DEBUG ? mInputLogic.mSuggestedWords : null; 1776 } 1777 1778 // DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME. 1779 @UsedForTesting 1780 /* package for test */ void waitForLoadingDictionaries(final long timeout, final TimeUnit unit) 1781 throws InterruptedException { 1782 mDictionaryFacilitator.waitForLoadingDictionariesForTesting(timeout, unit); 1783 } 1784 1785 // DO NOT USE THIS for any other purpose than testing. This can break the keyboard badly. 1786 @UsedForTesting 1787 /* package for test */ void replaceDictionariesForTest(final Locale locale) { 1788 final SettingsValues settingsValues = mSettings.getCurrent(); 1789 mDictionaryFacilitator.resetDictionaries(this, locale, 1790 settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, 1791 false /* forceReloadMainDictionary */, this /* listener */); 1792 } 1793 1794 // DO NOT USE THIS for any other purpose than testing. 1795 @UsedForTesting 1796 /* package for test */ void clearPersonalizedDictionariesForTest() { 1797 mDictionaryFacilitator.clearUserHistoryDictionary(); 1798 mDictionaryFacilitator.clearPersonalizationDictionary(); 1799 } 1800 1801 @UsedForTesting 1802 /* package for test */ List<InputMethodSubtype> getEnabledSubtypesForTest() { 1803 return (mRichImm != null) ? mRichImm.getMyEnabledInputMethodSubtypeList( 1804 true /* allowsImplicitlySelectedSubtypes */) : new ArrayList<InputMethodSubtype>(); 1805 } 1806 1807 public void dumpDictionaryForDebug(final String dictName) { 1808 if (mDictionaryFacilitator.getLocale() == null) { 1809 resetSuggest(); 1810 } 1811 mDictionaryFacilitator.dumpDictionaryForDebug(dictName); 1812 } 1813 1814 public void debugDumpStateAndCrashWithException(final String context) { 1815 final SettingsValues settingsValues = mSettings.getCurrent(); 1816 final StringBuilder s = new StringBuilder(settingsValues.toString()); 1817 s.append("\nAttributes : ").append(settingsValues.mInputAttributes) 1818 .append("\nContext : ").append(context); 1819 throw new RuntimeException(s.toString()); 1820 } 1821 1822 @Override 1823 protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) { 1824 super.dump(fd, fout, args); 1825 1826 final Printer p = new PrintWriterPrinter(fout); 1827 p.println("LatinIME state :"); 1828 p.println(" VersionCode = " + ApplicationUtils.getVersionCode(this)); 1829 p.println(" VersionName = " + ApplicationUtils.getVersionName(this)); 1830 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1831 final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; 1832 p.println(" Keyboard mode = " + keyboardMode); 1833 final SettingsValues settingsValues = mSettings.getCurrent(); 1834 p.println(settingsValues.dump()); 1835 // TODO: Dump all settings values 1836 } 1837 1838 public boolean shouldSwitchToOtherInputMethods() { 1839 // TODO: Revisit here to reorganize the settings. Probably we can/should use different 1840 // strategy once the implementation of 1841 // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well. 1842 final boolean fallbackValue = mSettings.getCurrent().mIncludesOtherImesInLanguageSwitchList; 1843 final IBinder token = getWindow().getWindow().getAttributes().token; 1844 if (token == null) { 1845 return fallbackValue; 1846 } 1847 return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue); 1848 } 1849 1850 public boolean shouldShowLanguageSwitchKey() { 1851 // TODO: Revisit here to reorganize the settings. Probably we can/should use different 1852 // strategy once the implementation of 1853 // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well. 1854 final boolean fallbackValue = mSettings.getCurrent().isLanguageSwitchKeyEnabled(); 1855 final IBinder token = getWindow().getWindow().getAttributes().token; 1856 if (token == null) { 1857 return fallbackValue; 1858 } 1859 return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue); 1860 } 1861} 1862