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