LatinIME.java revision f1accd4f04b13f764e1ffa7c7964e4b7c41ddf4b
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(settingsValues, 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 SettingsValues currentSettingsValues = mSettings.getCurrent(); 776 mLastEditorChangeInfo = new EditorChangeInfo( 777 currentSettingsValues.isSameInputType(editorInfo), 778 currentSettingsValues.hasSameOrientation(getResources().getConfiguration())); 779 } 780 781 @SuppressWarnings("deprecation") 782 private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { 783 super.onStartInputView(editorInfo, restarting); 784 mRichImm.clearSubtypeCaches(); 785 final KeyboardSwitcher switcher = mKeyboardSwitcher; 786 switcher.updateKeyboardTheme(); 787 final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); 788 789 if (editorInfo == null) { 790 Log.e(TAG, "Null EditorInfo in onStartInputView()"); 791 if (DebugFlags.DEBUG_ENABLED) { 792 throw new NullPointerException("Null EditorInfo in onStartInputView()"); 793 } 794 return; 795 } 796 if (DEBUG) { 797 Log.d(TAG, "onStartInputView: editorInfo:" 798 + String.format("inputType=0x%08x imeOptions=0x%08x", 799 editorInfo.inputType, editorInfo.imeOptions)); 800 Log.d(TAG, "All caps = " 801 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) 802 + ", sentence caps = " 803 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) 804 + ", word caps = " 805 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); 806 } 807 Log.i(TAG, "Starting input. Cursor position = " 808 + editorInfo.initialSelStart + "," + editorInfo.initialSelEnd); 809 // TODO: Consolidate these checks with {@link InputAttributes}. 810 if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { 811 Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); 812 Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); 813 } 814 if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { 815 Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); 816 Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); 817 } 818 819 // In landscape mode, this method gets called without the input view being created. 820 if (mainKeyboardView == null) { 821 return; 822 } 823 824 // Forward this event to the accessibility utilities, if enabled. 825 final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); 826 if (accessUtils.isTouchExplorationEnabled()) { 827 accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); 828 } 829 830 final boolean inputTypeChanged = !mLastEditorChangeInfo.mIsSameInputType; 831 final boolean isDifferentTextField = !restarting || inputTypeChanged; 832 if (isDifferentTextField) { 833 mSubtypeSwitcher.updateParametersOnStartInputView(); 834 } 835 836 // The EditorInfo might have a flag that affects fullscreen mode. 837 // Note: This call should be done by InputMethodService? 838 updateFullscreenMode(); 839 840 // The app calling setText() has the effect of clearing the composing 841 // span, so we should reset our state unconditionally, even if restarting is true. 842 // We also tell the input logic about the combining rules for the current subtype, so 843 // it can adjust its combiners if needed. 844 mInputLogic.startInput(mSubtypeSwitcher.getCombiningRulesExtraValueOfCurrentSubtype()); 845 846 // Note: the following does a round-trip IPC on the main thread: be careful 847 final Locale currentLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 848 final Suggest suggest = mInputLogic.mSuggest; 849 if (null != currentLocale && !currentLocale.equals(suggest.getLocale())) { 850 // TODO: Do this automatically. 851 resetSuggest(); 852 } 853 854 // TODO[IL]: Can the following be moved to InputLogic#startInput? 855 final boolean canReachInputConnection; 856 if (!mInputLogic.mConnection.resetCachesUponCursorMoveAndReturnSuccess( 857 editorInfo.initialSelStart, editorInfo.initialSelEnd, 858 false /* shouldFinishComposition */)) { 859 // Sometimes, while rotating, for some reason the framework tells the app we are not 860 // connected to it and that means we can't refresh the cache. In this case, schedule a 861 // refresh later. 862 // We try resetting the caches up to 5 times before giving up. 863 mHandler.postResetCaches(isDifferentTextField, 5 /* remainingTries */); 864 // mLastSelection{Start,End} are reset later in this method, don't need to do it here 865 canReachInputConnection = false; 866 } else { 867 // When rotating, initialSelStart and initialSelEnd sometimes are lying. Make a best 868 // effort to work around this bug. 869 mInputLogic.mConnection.tryFixLyingCursorPosition(); 870 mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 871 true /* shouldDelay */); 872 canReachInputConnection = true; 873 } 874 875 if (isDifferentTextField || !mLastEditorChangeInfo.mHasSameOrientation) { 876 loadSettings(); 877 } 878 final SettingsValues currentSettingsValues = mSettings.getCurrent(); 879 if (isDifferentTextField) { 880 mainKeyboardView.closing(); 881 882 if (currentSettingsValues.mAutoCorrectionEnabledPerUserSettings) { 883 suggest.setAutoCorrectionThreshold( 884 currentSettingsValues.mAutoCorrectionThreshold); 885 } 886 887 switcher.loadKeyboard(editorInfo, currentSettingsValues, getCurrentAutoCapsState(), 888 getCurrentRecapitalizeState()); 889 if (!canReachInputConnection) { 890 // If we can't reach the input connection, we will call loadKeyboard again later, 891 // so we need to save its state now. The call will be done in #retryResetCaches. 892 switcher.saveKeyboardState(); 893 } 894 } else if (restarting) { 895 // TODO: Come up with a more comprehensive way to reset the keyboard layout when 896 // a keyboard layout set doesn't get reloaded in this method. 897 switcher.resetKeyboardStateToAlphabet(getCurrentAutoCapsState(), 898 getCurrentRecapitalizeState()); 899 // In apps like Talk, we come here when the text is sent and the field gets emptied and 900 // we need to re-evaluate the shift state, but not the whole layout which would be 901 // disruptive. 902 // Space state must be updated before calling updateShiftState 903 switcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 904 getCurrentRecapitalizeState()); 905 } 906 // This will set the punctuation suggestions if next word suggestion is off; 907 // otherwise it will clear the suggestion strip. 908 setNeutralSuggestionStrip(); 909 910 mHandler.cancelUpdateSuggestionStrip(); 911 912 mainKeyboardView.setMainDictionaryAvailability( 913 mDictionaryFacilitator.hasInitializedMainDictionary()); 914 mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn, 915 currentSettingsValues.mKeyPreviewPopupDismissDelay); 916 mainKeyboardView.setSlidingKeyInputPreviewEnabled( 917 currentSettingsValues.mSlidingKeyInputPreviewEnabled); 918 mainKeyboardView.setGestureHandlingEnabledByUser( 919 currentSettingsValues.mGestureInputEnabled, 920 currentSettingsValues.mGestureTrailEnabled, 921 currentSettingsValues.mGestureFloatingPreviewTextEnabled); 922 923 // Contextual dictionary should be updated for the current application. 924 mContextualDictionaryUpdater.onStartInputView(editorInfo.packageName); 925 if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); 926 } 927 928 @Override 929 public void onWindowHidden() { 930 super.onWindowHidden(); 931 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 932 if (mainKeyboardView != null) { 933 mainKeyboardView.closing(); 934 } 935 } 936 937 private void onFinishInputInternal() { 938 super.onFinishInput(); 939 940 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 941 if (mainKeyboardView != null) { 942 mainKeyboardView.closing(); 943 } 944 } 945 946 private void onFinishInputViewInternal(final boolean finishingInput) { 947 super.onFinishInputView(finishingInput); 948 mKeyboardSwitcher.deallocateMemory(); 949 // Remove pending messages related to update suggestions 950 mHandler.cancelUpdateSuggestionStrip(); 951 // Should do the following in onFinishInputInternal but until JB MR2 it's not called :( 952 mInputLogic.finishInput(); 953 } 954 955 @Override 956 public void onUpdateSelection(final int oldSelStart, final int oldSelEnd, 957 final int newSelStart, final int newSelEnd, 958 final int composingSpanStart, final int composingSpanEnd) { 959 super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, 960 composingSpanStart, composingSpanEnd); 961 if (DEBUG) { 962 Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd 963 + ", nss=" + newSelStart + ", nse=" + newSelEnd 964 + ", cs=" + composingSpanStart + ", ce=" + composingSpanEnd); 965 } 966 967 // If the keyboard is not visible, we don't need to do all the housekeeping work, as it 968 // will be reset when the keyboard shows up anyway. 969 // TODO: revisit this when LatinIME supports hardware keyboards. 970 // NOTE: the test harness subclasses LatinIME and overrides isInputViewShown(). 971 // TODO: find a better way to simulate actual execution. 972 if (isInputViewShown() && 973 mInputLogic.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd)) { 974 mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 975 getCurrentRecapitalizeState()); 976 } 977 } 978 979 @Override 980 public void onUpdateCursor(final Rect rect) { 981 if (DEBUG) { 982 Log.i(TAG, "onUpdateCursor:" + rect.toShortString()); 983 } 984 super.onUpdateCursor(rect); 985 } 986 987 /** 988 * This is called when the user has clicked on the extracted text view, 989 * when running in fullscreen mode. The default implementation hides 990 * the suggestions view when this happens, but only if the extracted text 991 * editor has a vertical scroll bar because its text doesn't fit. 992 * Here we override the behavior due to the possibility that a re-correction could 993 * cause the suggestions strip to disappear and re-appear. 994 */ 995 @Override 996 public void onExtractedTextClicked() { 997 if (mSettings.getCurrent().needsToLookupSuggestions()) { 998 return; 999 } 1000 1001 super.onExtractedTextClicked(); 1002 } 1003 1004 /** 1005 * This is called when the user has performed a cursor movement in the 1006 * extracted text view, when it is running in fullscreen mode. The default 1007 * implementation hides the suggestions view when a vertical movement 1008 * happens, but only if the extracted text editor has a vertical scroll bar 1009 * because its text doesn't fit. 1010 * Here we override the behavior due to the possibility that a re-correction could 1011 * cause the suggestions strip to disappear and re-appear. 1012 */ 1013 @Override 1014 public void onExtractedCursorMovement(final int dx, final int dy) { 1015 if (mSettings.getCurrent().needsToLookupSuggestions()) { 1016 return; 1017 } 1018 1019 super.onExtractedCursorMovement(dx, dy); 1020 } 1021 1022 @Override 1023 public void hideWindow() { 1024 mKeyboardSwitcher.onHideWindow(); 1025 1026 if (TRACE) Debug.stopMethodTracing(); 1027 if (isShowingOptionDialog()) { 1028 mOptionsDialog.dismiss(); 1029 mOptionsDialog = null; 1030 } 1031 super.hideWindow(); 1032 } 1033 1034 @Override 1035 public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) { 1036 if (DEBUG) { 1037 Log.i(TAG, "Received completions:"); 1038 if (applicationSpecifiedCompletions != null) { 1039 for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { 1040 Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); 1041 } 1042 } 1043 } 1044 if (!mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) { 1045 return; 1046 } 1047 // If we have an update request in flight, we need to cancel it so it does not override 1048 // these completions. 1049 mHandler.cancelUpdateSuggestionStrip(); 1050 if (applicationSpecifiedCompletions == null) { 1051 setNeutralSuggestionStrip(); 1052 return; 1053 } 1054 1055 final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords = 1056 SuggestedWords.getFromApplicationSpecifiedCompletions( 1057 applicationSpecifiedCompletions); 1058 final SuggestedWords suggestedWords = new SuggestedWords(applicationSuggestedWords, 1059 null /* rawSuggestions */, false /* typedWordValid */, false /* willAutoCorrect */, 1060 false /* isObsoleteSuggestions */, false /* isPrediction */); 1061 // When in fullscreen mode, show completions generated by the application forcibly 1062 setSuggestedWords(suggestedWords); 1063 } 1064 1065 private int getAdjustedBackingViewHeight() { 1066 final int currentHeight = mKeyPreviewBackingView.getHeight(); 1067 if (currentHeight > 0) { 1068 return currentHeight; 1069 } 1070 1071 final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView(); 1072 if (visibleKeyboardView == null) { 1073 return 0; 1074 } 1075 // TODO: !!!!!!!!!!!!!!!!!!!! Handle different backing view heights between the main !!! 1076 // keyboard and the emoji keyboard. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1077 final int keyboardHeight = visibleKeyboardView.getHeight(); 1078 final int suggestionsHeight = mSuggestionStripView.getHeight(); 1079 final int displayHeight = getResources().getDisplayMetrics().heightPixels; 1080 final Rect rect = new Rect(); 1081 mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect); 1082 final int notificationBarHeight = rect.top; 1083 final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight 1084 - keyboardHeight; 1085 1086 final LayoutParams params = mKeyPreviewBackingView.getLayoutParams(); 1087 params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight); 1088 mKeyPreviewBackingView.setLayoutParams(params); 1089 return params.height; 1090 } 1091 1092 @Override 1093 public void onComputeInsets(final InputMethodService.Insets outInsets) { 1094 super.onComputeInsets(outInsets); 1095 final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView(); 1096 if (visibleKeyboardView == null || !hasSuggestionStripView()) { 1097 return; 1098 } 1099 final int adjustedBackingHeight = getAdjustedBackingViewHeight(); 1100 final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE); 1101 final int backingHeight = backingGone ? 0 : adjustedBackingHeight; 1102 // In fullscreen mode, the height of the extract area managed by InputMethodService should 1103 // be considered. 1104 // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}. 1105 final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0; 1106 final int suggestionsHeight = (mSuggestionStripView.getVisibility() == View.GONE) ? 0 1107 : mSuggestionStripView.getHeight(); 1108 final int extraHeight = extractHeight + backingHeight + suggestionsHeight; 1109 int visibleTopY = extraHeight; 1110 // Need to set touchable region only if input view is being shown 1111 if (visibleKeyboardView.isShown()) { 1112 // Note that the height of Emoji layout is the same as the height of the main keyboard 1113 // and the suggestion strip 1114 if (mKeyboardSwitcher.isShowingEmojiPalettes() 1115 || mSuggestionStripView.getVisibility() == View.VISIBLE) { 1116 visibleTopY -= suggestionsHeight; 1117 } 1118 final int touchY = mKeyboardSwitcher.isShowingMoreKeysPanel() ? 0 : visibleTopY; 1119 final int touchWidth = visibleKeyboardView.getWidth(); 1120 final int touchHeight = visibleKeyboardView.getHeight() + extraHeight 1121 // Extend touchable region below the keyboard. 1122 + EXTENDED_TOUCHABLE_REGION_HEIGHT; 1123 outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; 1124 outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight); 1125 } 1126 outInsets.contentTopInsets = visibleTopY; 1127 outInsets.visibleTopInsets = visibleTopY; 1128 } 1129 1130 @Override 1131 public boolean onEvaluateFullscreenMode() { 1132 // Reread resource value here, because this method is called by the framework as needed. 1133 final boolean isFullscreenModeAllowed = Settings.readUseFullscreenMode(getResources()); 1134 if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) { 1135 // TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI 1136 // implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI 1137 // without NO_FULLSCREEN doesn't work as expected. Because of this we need this 1138 // hack for now. Let's get rid of this once the framework gets fixed. 1139 final EditorInfo ei = getCurrentInputEditorInfo(); 1140 return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0)); 1141 } else { 1142 return false; 1143 } 1144 } 1145 1146 @Override 1147 public void updateFullscreenMode() { 1148 super.updateFullscreenMode(); 1149 1150 if (mKeyPreviewBackingView == null) return; 1151 // In fullscreen mode, no need to have extra space to show the key preview. 1152 // If not, we should have extra space above the keyboard to show the key preview. 1153 mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE); 1154 } 1155 1156 private int getCurrentAutoCapsState() { 1157 return mInputLogic.getCurrentAutoCapsState(mSettings.getCurrent()); 1158 } 1159 1160 private int getCurrentRecapitalizeState() { 1161 return mInputLogic.getCurrentRecapitalizeState(); 1162 } 1163 1164 public Locale getCurrentSubtypeLocale() { 1165 return mSubtypeSwitcher.getCurrentSubtypeLocale(); 1166 } 1167 1168 /** 1169 * @param codePoints code points to get coordinates for. 1170 * @return x,y coordinates for this keyboard, as a flattened array. 1171 */ 1172 public int[] getCoordinatesForCurrentKeyboard(final int[] codePoints) { 1173 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1174 if (null == keyboard) { 1175 return CoordinateUtils.newCoordinateArray(codePoints.length, 1176 Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); 1177 } else { 1178 return keyboard.getCoordinates(codePoints); 1179 } 1180 } 1181 1182 // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is 1183 // pressed. 1184 @Override 1185 public void addWordToUserDictionary(final String word) { 1186 if (TextUtils.isEmpty(word)) { 1187 // Probably never supposed to happen, but just in case. 1188 return; 1189 } 1190 final String wordToEdit; 1191 if (CapsModeUtils.isAutoCapsMode(mInputLogic.mLastComposedWord.mCapitalizedMode)) { 1192 wordToEdit = word.toLowerCase(getCurrentSubtypeLocale()); 1193 } else { 1194 wordToEdit = word; 1195 } 1196 mDictionaryFacilitator.addWordToUserDictionary(this /* context */, wordToEdit); 1197 } 1198 1199 // Callback for the {@link SuggestionStripView}, to call when the important notice strip is 1200 // pressed. 1201 @Override 1202 public void showImportantNoticeContents() { 1203 showOptionDialog(new ImportantNoticeDialog(this /* context */, this /* listener */)); 1204 } 1205 1206 // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener} 1207 @Override 1208 public void onClickSettingsOfImportantNoticeDialog(final int nextVersion) { 1209 launchSettings(); 1210 } 1211 1212 // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener} 1213 @Override 1214 public void onUserAcknowledgmentOfImportantNoticeDialog(final int nextVersion) { 1215 setNeutralSuggestionStrip(); 1216 } 1217 1218 public void displaySettingsDialog() { 1219 if (isShowingOptionDialog()) { 1220 return; 1221 } 1222 showSubtypeSelectorAndSettings(); 1223 } 1224 1225 @Override 1226 public boolean onCustomRequest(final int requestCode) { 1227 if (isShowingOptionDialog()) return false; 1228 switch (requestCode) { 1229 case Constants.CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER: 1230 if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { 1231 mRichImm.getInputMethodManager().showInputMethodPicker(); 1232 return true; 1233 } 1234 return false; 1235 } 1236 return false; 1237 } 1238 1239 private boolean isShowingOptionDialog() { 1240 return mOptionsDialog != null && mOptionsDialog.isShowing(); 1241 } 1242 1243 // TODO: Revise the language switch key behavior to make it much smarter and more reasonable. 1244 public void switchToNextSubtype() { 1245 final IBinder token = getWindow().getWindow().getAttributes().token; 1246 if (shouldSwitchToOtherInputMethods()) { 1247 mRichImm.switchToNextInputMethod(token, false /* onlyCurrentIme */); 1248 return; 1249 } 1250 mSubtypeState.switchSubtype(token, mRichImm); 1251 } 1252 1253 // Implementation of {@link KeyboardActionListener}. 1254 @Override 1255 public void onCodeInput(final int codePoint, final int x, final int y, 1256 final boolean isKeyRepeat) { 1257 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1258 // x and y include some padding, but everything down the line (especially native 1259 // code) needs the coordinates in the keyboard frame. 1260 // TODO: We should reconsider which coordinate system should be used to represent 1261 // keyboard event. Also we should pull this up -- LatinIME has no business doing 1262 // this transformation, it should be done already before calling onCodeInput. 1263 final int keyX = mainKeyboardView.getKeyX(x); 1264 final int keyY = mainKeyboardView.getKeyY(y); 1265 final int codeToSend; 1266 if (Constants.CODE_SHIFT == codePoint) { 1267 // TODO: Instead of checking for alphabetic keyboard here, separate keycodes for 1268 // alphabetic shift and shift while in symbol layout. 1269 final Keyboard currentKeyboard = mKeyboardSwitcher.getKeyboard(); 1270 if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) { 1271 codeToSend = codePoint; 1272 } else { 1273 codeToSend = Constants.CODE_SYMBOL_SHIFT; 1274 } 1275 } else { 1276 codeToSend = codePoint; 1277 } 1278 if (Constants.CODE_SHORTCUT == codePoint) { 1279 mSubtypeSwitcher.switchToShortcutIME(this); 1280 // Still call the *#onCodeInput methods for readability. 1281 } 1282 final Event event = createSoftwareKeypressEvent(codeToSend, keyX, keyY, isKeyRepeat); 1283 final InputTransaction completeInputTransaction = 1284 mInputLogic.onCodeInput(mSettings.getCurrent(), event, 1285 mKeyboardSwitcher.getKeyboardShiftMode(), 1286 mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler); 1287 updateStateAfterInputTransaction(completeInputTransaction); 1288 mKeyboardSwitcher.onCodeInput(codePoint, getCurrentAutoCapsState(), 1289 getCurrentRecapitalizeState()); 1290 } 1291 1292 // A helper method to split the code point and the key code. Ultimately, they should not be 1293 // squashed into the same variable, and this method should be removed. 1294 private static Event createSoftwareKeypressEvent(final int keyCodeOrCodePoint, final int keyX, 1295 final int keyY, final boolean isKeyRepeat) { 1296 final int keyCode; 1297 final int codePoint; 1298 if (keyCodeOrCodePoint <= 0) { 1299 keyCode = keyCodeOrCodePoint; 1300 codePoint = Event.NOT_A_CODE_POINT; 1301 } else { 1302 keyCode = Event.NOT_A_KEY_CODE; 1303 codePoint = keyCodeOrCodePoint; 1304 } 1305 return Event.createSoftwareKeypressEvent(codePoint, keyCode, keyX, keyY, isKeyRepeat); 1306 } 1307 1308 // Called from PointerTracker through the KeyboardActionListener interface 1309 @Override 1310 public void onTextInput(final String rawText) { 1311 // TODO: have the keyboard pass the correct key code when we need it. 1312 final Event event = Event.createSoftwareTextEvent(rawText, Event.NOT_A_KEY_CODE); 1313 final InputTransaction completeInputTransaction = 1314 mInputLogic.onTextInput(mSettings.getCurrent(), event, 1315 mKeyboardSwitcher.getKeyboardShiftMode(), mHandler); 1316 updateStateAfterInputTransaction(completeInputTransaction); 1317 mKeyboardSwitcher.onCodeInput(Constants.CODE_OUTPUT_TEXT, getCurrentAutoCapsState(), 1318 getCurrentRecapitalizeState()); 1319 } 1320 1321 @Override 1322 public void onStartBatchInput() { 1323 mInputLogic.onStartBatchInput(mSettings.getCurrent(), mKeyboardSwitcher, mHandler); 1324 } 1325 1326 @Override 1327 public void onUpdateBatchInput(final InputPointers batchPointers) { 1328 mInputLogic.onUpdateBatchInput(mSettings.getCurrent(), batchPointers, mKeyboardSwitcher); 1329 } 1330 1331 @Override 1332 public void onEndBatchInput(final InputPointers batchPointers) { 1333 mInputLogic.onEndBatchInput(batchPointers); 1334 } 1335 1336 @Override 1337 public void onCancelBatchInput() { 1338 mInputLogic.onCancelBatchInput(mHandler); 1339 } 1340 1341 // This method must run on the UI Thread. 1342 private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, 1343 final boolean dismissGestureFloatingPreviewText) { 1344 showSuggestionStrip(suggestedWords); 1345 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1346 mainKeyboardView.showGestureFloatingPreviewText(suggestedWords); 1347 if (dismissGestureFloatingPreviewText) { 1348 mainKeyboardView.dismissGestureFloatingPreviewText(); 1349 } 1350 } 1351 1352 // Called from PointerTracker through the KeyboardActionListener interface 1353 @Override 1354 public void onFinishSlidingInput() { 1355 // User finished sliding input. 1356 mKeyboardSwitcher.onFinishSlidingInput(getCurrentAutoCapsState(), 1357 getCurrentRecapitalizeState()); 1358 } 1359 1360 // Called from PointerTracker through the KeyboardActionListener interface 1361 @Override 1362 public void onCancelInput() { 1363 // User released a finger outside any key 1364 // Nothing to do so far. 1365 } 1366 1367 public boolean hasSuggestionStripView() { 1368 return null != mSuggestionStripView; 1369 } 1370 1371 @Override 1372 public boolean isShowingAddToDictionaryHint() { 1373 return hasSuggestionStripView() && mSuggestionStripView.isShowingAddToDictionaryHint(); 1374 } 1375 1376 @Override 1377 public void dismissAddToDictionaryHint() { 1378 if (!hasSuggestionStripView()) { 1379 return; 1380 } 1381 mSuggestionStripView.dismissAddToDictionaryHint(); 1382 } 1383 1384 private void setSuggestedWords(final SuggestedWords suggestedWords) { 1385 mInputLogic.setSuggestedWords(suggestedWords); 1386 // TODO: Modify this when we support suggestions with hard keyboard 1387 if (!hasSuggestionStripView()) { 1388 return; 1389 } 1390 if (!onEvaluateInputViewShown()) { 1391 return; 1392 } 1393 1394 final SettingsValues currentSettingsValues = mSettings.getCurrent(); 1395 final boolean shouldShowImportantNotice = 1396 ImportantNoticeUtils.shouldShowImportantNotice(this); 1397 final boolean shouldShowSuggestionCandidates = 1398 currentSettingsValues.mInputAttributes.mShouldShowSuggestions 1399 && currentSettingsValues.isSuggestionsEnabledPerUserSettings(); 1400 final boolean shouldShowSuggestionsStripUnlessPassword = shouldShowImportantNotice 1401 || currentSettingsValues.mShowsVoiceInputKey 1402 || shouldShowSuggestionCandidates 1403 || currentSettingsValues.isApplicationSpecifiedCompletionsOn(); 1404 final boolean shouldShowSuggestionsStrip = shouldShowSuggestionsStripUnlessPassword 1405 && !currentSettingsValues.mInputAttributes.mIsPasswordField; 1406 mSuggestionStripView.updateVisibility(shouldShowSuggestionsStrip, isFullscreenMode()); 1407 if (!shouldShowSuggestionsStrip) { 1408 return; 1409 } 1410 1411 final boolean isEmptyApplicationSpecifiedCompletions = 1412 currentSettingsValues.isApplicationSpecifiedCompletionsOn() 1413 && suggestedWords.isEmpty(); 1414 final boolean noSuggestionsToShow = (SuggestedWords.EMPTY == suggestedWords) 1415 || suggestedWords.isPunctuationSuggestions() 1416 || isEmptyApplicationSpecifiedCompletions; 1417 if (shouldShowImportantNotice && noSuggestionsToShow) { 1418 if (mSuggestionStripView.maybeShowImportantNoticeTitle()) { 1419 return; 1420 } 1421 } 1422 1423 if (currentSettingsValues.isSuggestionsEnabledPerUserSettings() 1424 // We should clear suggestions if there is no suggestion to show. 1425 || noSuggestionsToShow 1426 || currentSettingsValues.isApplicationSpecifiedCompletionsOn()) { 1427 mSuggestionStripView.setSuggestions(suggestedWords, 1428 SubtypeLocaleUtils.isRtlLanguage(mSubtypeSwitcher.getCurrentSubtype())); 1429 } 1430 } 1431 1432 // TODO[IL]: Move this out of LatinIME. 1433 public void getSuggestedWords(final int sessionId, final int sequenceNumber, 1434 final OnGetSuggestedWordsCallback callback) { 1435 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1436 if (keyboard == null) { 1437 callback.onGetSuggestedWords(SuggestedWords.EMPTY); 1438 return; 1439 } 1440 mInputLogic.getSuggestedWords(mSettings.getCurrent(), keyboard.getProximityInfo(), 1441 mKeyboardSwitcher.getKeyboardShiftMode(), sessionId, sequenceNumber, callback); 1442 } 1443 1444 @Override 1445 public void showSuggestionStrip(final SuggestedWords sourceSuggestedWords) { 1446 final SuggestedWords suggestedWords = 1447 sourceSuggestedWords.isEmpty() ? SuggestedWords.EMPTY : sourceSuggestedWords; 1448 if (SuggestedWords.EMPTY == suggestedWords) { 1449 setNeutralSuggestionStrip(); 1450 } else { 1451 setSuggestedWords(suggestedWords); 1452 } 1453 // Cache the auto-correction in accessibility code so we can speak it if the user 1454 // touches a key that will insert it. 1455 AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords, 1456 sourceSuggestedWords.mTypedWord); 1457 } 1458 1459 // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 1460 // interface 1461 @Override 1462 public void pickSuggestionManually(final SuggestedWordInfo suggestionInfo) { 1463 final InputTransaction completeInputTransaction = mInputLogic.onPickSuggestionManually( 1464 mSettings.getCurrent(), suggestionInfo, 1465 mKeyboardSwitcher.getKeyboardShiftMode(), 1466 mKeyboardSwitcher.getCurrentKeyboardScriptId(), 1467 mHandler); 1468 updateStateAfterInputTransaction(completeInputTransaction); 1469 } 1470 1471 @Override 1472 public void showAddToDictionaryHint(final String word) { 1473 if (!hasSuggestionStripView()) { 1474 return; 1475 } 1476 mSuggestionStripView.showAddToDictionaryHint(word); 1477 } 1478 1479 // This will show either an empty suggestion strip (if prediction is enabled) or 1480 // punctuation suggestions (if it's disabled). 1481 @Override 1482 public void setNeutralSuggestionStrip() { 1483 final SettingsValues currentSettings = mSettings.getCurrent(); 1484 final SuggestedWords neutralSuggestions = currentSettings.mBigramPredictionEnabled 1485 ? SuggestedWords.EMPTY : currentSettings.mSpacingAndPunctuations.mSuggestPuncList; 1486 setSuggestedWords(neutralSuggestions); 1487 } 1488 1489 // TODO: Make this private 1490 // Outside LatinIME, only used by the {@link InputTestsBase} test suite. 1491 @UsedForTesting 1492 void loadKeyboard() { 1493 // Since we are switching languages, the most urgent thing is to let the keyboard graphics 1494 // update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on 1495 // the screen. Anything we do right now will delay this, so wait until the next frame 1496 // before we do the rest, like reopening dictionaries and updating suggestions. So we 1497 // post a message. 1498 mHandler.postReopenDictionaries(); 1499 loadSettings(); 1500 if (mKeyboardSwitcher.getMainKeyboardView() != null) { 1501 // Reload keyboard because the current language has been changed. 1502 mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent(), 1503 getCurrentAutoCapsState(), getCurrentRecapitalizeState()); 1504 } 1505 } 1506 1507 /** 1508 * After an input transaction has been executed, some state must be updated. This includes 1509 * the shift state of the keyboard and suggestions. This method looks at the finished 1510 * inputTransaction to find out what is necessary and updates the state accordingly. 1511 * @param inputTransaction The transaction that has been executed. 1512 */ 1513 private void updateStateAfterInputTransaction(final InputTransaction inputTransaction) { 1514 switch (inputTransaction.getRequiredShiftUpdate()) { 1515 case InputTransaction.SHIFT_UPDATE_LATER: 1516 mHandler.postUpdateShiftState(); 1517 break; 1518 case InputTransaction.SHIFT_UPDATE_NOW: 1519 mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 1520 getCurrentRecapitalizeState()); 1521 break; 1522 default: // SHIFT_NO_UPDATE 1523 } 1524 if (inputTransaction.requiresUpdateSuggestions()) { 1525 mHandler.postUpdateSuggestionStrip(); 1526 } 1527 if (inputTransaction.didAffectContents()) { 1528 mSubtypeState.setCurrentSubtypeHasBeenUsed(); 1529 } 1530 } 1531 1532 private void hapticAndAudioFeedback(final int code, final int repeatCount) { 1533 final MainKeyboardView keyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1534 if (keyboardView != null && keyboardView.isInDraggingFinger()) { 1535 // No need to feedback while finger is dragging. 1536 return; 1537 } 1538 if (repeatCount > 0) { 1539 if (code == Constants.CODE_DELETE && !mInputLogic.mConnection.canDeleteCharacters()) { 1540 // No need to feedback when repeat delete key will have no effect. 1541 return; 1542 } 1543 // TODO: Use event time that the last feedback has been generated instead of relying on 1544 // a repeat count to thin out feedback. 1545 if (repeatCount % PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT == 0) { 1546 return; 1547 } 1548 } 1549 final AudioAndHapticFeedbackManager feedbackManager = 1550 AudioAndHapticFeedbackManager.getInstance(); 1551 if (repeatCount == 0) { 1552 // TODO: Reconsider how to perform haptic feedback when repeating key. 1553 feedbackManager.performHapticFeedback(keyboardView); 1554 } 1555 feedbackManager.performAudioFeedback(code); 1556 } 1557 1558 // Callback of the {@link KeyboardActionListener}. This is called when a key is depressed; 1559 // release matching call is {@link #onReleaseKey(int,boolean)} below. 1560 @Override 1561 public void onPressKey(final int primaryCode, final int repeatCount, 1562 final boolean isSinglePointer) { 1563 mKeyboardSwitcher.onPressKey(primaryCode, isSinglePointer, getCurrentAutoCapsState(), 1564 getCurrentRecapitalizeState()); 1565 hapticAndAudioFeedback(primaryCode, repeatCount); 1566 } 1567 1568 // Callback of the {@link KeyboardActionListener}. This is called when a key is released; 1569 // press matching call is {@link #onPressKey(int,int,boolean)} above. 1570 @Override 1571 public void onReleaseKey(final int primaryCode, final boolean withSliding) { 1572 mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding, getCurrentAutoCapsState(), 1573 getCurrentRecapitalizeState()); 1574 } 1575 1576 private HardwareEventDecoder getHardwareKeyEventDecoder(final int deviceId) { 1577 final HardwareEventDecoder decoder = mHardwareEventDecoders.get(deviceId); 1578 if (null != decoder) return decoder; 1579 // TODO: create the decoder according to the specification 1580 final HardwareEventDecoder newDecoder = new HardwareKeyboardEventDecoder(deviceId); 1581 mHardwareEventDecoders.put(deviceId, newDecoder); 1582 return newDecoder; 1583 } 1584 1585 // Hooks for hardware keyboard 1586 @Override 1587 public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) { 1588 if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { 1589 return super.onKeyDown(keyCode, keyEvent); 1590 } 1591 final Event event = getHardwareKeyEventDecoder( 1592 keyEvent.getDeviceId()).decodeHardwareKey(keyEvent); 1593 // If the event is not handled by LatinIME, we just pass it to the parent implementation. 1594 // If it's handled, we return true because we did handle it. 1595 if (event.isHandled()) { 1596 mInputLogic.onCodeInput(mSettings.getCurrent(), event, 1597 mKeyboardSwitcher.getKeyboardShiftMode(), 1598 // TODO: this is not necessarily correct for a hardware keyboard right now 1599 mKeyboardSwitcher.getCurrentKeyboardScriptId(), 1600 mHandler); 1601 return true; 1602 } 1603 return super.onKeyDown(keyCode, keyEvent); 1604 } 1605 1606 @Override 1607 public boolean onKeyUp(final int keyCode, final KeyEvent event) { 1608 final long keyIdentifier = event.getDeviceId() << 32 + event.getKeyCode(); 1609 if (mInputLogic.mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) { 1610 return true; 1611 } 1612 return super.onKeyUp(keyCode, event); 1613 } 1614 1615 // onKeyDown and onKeyUp are the main events we are interested in. There are two more events 1616 // related to handling of hardware key events that we may want to implement in the future: 1617 // boolean onKeyLongPress(final int keyCode, final KeyEvent event); 1618 // boolean onKeyMultiple(final int keyCode, final int count, final KeyEvent event); 1619 1620 // receive ringer mode change and network state change. 1621 private final BroadcastReceiver mConnectivityAndRingerModeChangeReceiver = 1622 new BroadcastReceiver() { 1623 @Override 1624 public void onReceive(final Context context, final Intent intent) { 1625 final String action = intent.getAction(); 1626 if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { 1627 mSubtypeSwitcher.onNetworkStateChanged(intent); 1628 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { 1629 AudioAndHapticFeedbackManager.getInstance().onRingerModeChanged(); 1630 } 1631 } 1632 }; 1633 1634 private void launchSettings() { 1635 mInputLogic.commitTyped(mSettings.getCurrent(), LastComposedWord.NOT_A_SEPARATOR); 1636 requestHideSelf(0); 1637 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1638 if (mainKeyboardView != null) { 1639 mainKeyboardView.closing(); 1640 } 1641 final Intent intent = new Intent(); 1642 intent.setClass(LatinIME.this, SettingsActivity.class); 1643 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 1644 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 1645 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 1646 intent.putExtra(SettingsActivity.EXTRA_SHOW_HOME_AS_UP, false); 1647 startActivity(intent); 1648 } 1649 1650 private void showSubtypeSelectorAndSettings() { 1651 final CharSequence title = getString(R.string.english_ime_input_options); 1652 // TODO: Should use new string "Select active input modes". 1653 final CharSequence languageSelectionTitle = getString(R.string.language_selection_title); 1654 final CharSequence[] items = new CharSequence[] { 1655 languageSelectionTitle, 1656 getString(ApplicationUtils.getActivityTitleResId(this, SettingsActivity.class)) 1657 }; 1658 final OnClickListener listener = new OnClickListener() { 1659 @Override 1660 public void onClick(DialogInterface di, int position) { 1661 di.dismiss(); 1662 switch (position) { 1663 case 0: 1664 final Intent intent = IntentUtils.getInputLanguageSelectionIntent( 1665 mRichImm.getInputMethodIdOfThisIme(), 1666 Intent.FLAG_ACTIVITY_NEW_TASK 1667 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 1668 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 1669 intent.putExtra(Intent.EXTRA_TITLE, languageSelectionTitle); 1670 startActivity(intent); 1671 break; 1672 case 1: 1673 launchSettings(); 1674 break; 1675 } 1676 } 1677 }; 1678 final AlertDialog.Builder builder = new AlertDialog.Builder( 1679 DialogUtils.getPlatformDialogThemeContext(this)); 1680 builder.setItems(items, listener).setTitle(title); 1681 final AlertDialog dialog = builder.create(); 1682 dialog.setCancelable(true /* cancelable */); 1683 dialog.setCanceledOnTouchOutside(true /* cancelable */); 1684 showOptionDialog(dialog); 1685 } 1686 1687 // TODO: Move this method out of {@link LatinIME}. 1688 private void showOptionDialog(final AlertDialog dialog) { 1689 final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken(); 1690 if (windowToken == null) { 1691 return; 1692 } 1693 1694 final Window window = dialog.getWindow(); 1695 final WindowManager.LayoutParams lp = window.getAttributes(); 1696 lp.token = windowToken; 1697 lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; 1698 window.setAttributes(lp); 1699 window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 1700 1701 mOptionsDialog = dialog; 1702 dialog.show(); 1703 } 1704 1705 // TODO: can this be removed somehow without breaking the tests? 1706 @UsedForTesting 1707 /* package for test */ SuggestedWords getSuggestedWordsForTest() { 1708 // You may not use this method for anything else than debug 1709 return DEBUG ? mInputLogic.mSuggestedWords : null; 1710 } 1711 1712 // DO NOT USE THIS for any other purpose than testing. This is information private to LatinIME. 1713 @UsedForTesting 1714 /* package for test */ void waitForLoadingDictionaries(final long timeout, final TimeUnit unit) 1715 throws InterruptedException { 1716 mDictionaryFacilitator.waitForLoadingDictionariesForTesting(timeout, unit); 1717 } 1718 1719 // DO NOT USE THIS for any other purpose than testing. This can break the keyboard badly. 1720 @UsedForTesting 1721 /* package for test */ void replaceDictionariesForTest(final Locale locale) { 1722 final SettingsValues settingsValues = mSettings.getCurrent(); 1723 mDictionaryFacilitator.resetDictionaries(this, locale, 1724 settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, 1725 false /* forceReloadMainDictionary */, this /* listener */); 1726 } 1727 1728 // DO NOT USE THIS for any other purpose than testing. 1729 @UsedForTesting 1730 /* package for test */ void clearPersonalizedDictionariesForTest() { 1731 mDictionaryFacilitator.clearUserHistoryDictionary(); 1732 mDictionaryFacilitator.clearPersonalizationDictionary(); 1733 } 1734 1735 @UsedForTesting 1736 /* package for test */ List<InputMethodSubtype> getEnabledSubtypesForTest() { 1737 return (mRichImm != null) ? mRichImm.getMyEnabledInputMethodSubtypeList( 1738 true /* allowsImplicitlySelectedSubtypes */) : new ArrayList<InputMethodSubtype>(); 1739 } 1740 1741 public void dumpDictionaryForDebug(final String dictName) { 1742 if (mDictionaryFacilitator.getLocale() == null) { 1743 resetSuggest(); 1744 } 1745 mDictionaryFacilitator.dumpDictionaryForDebug(dictName); 1746 } 1747 1748 public void debugDumpStateAndCrashWithException(final String context) { 1749 final SettingsValues settingsValues = mSettings.getCurrent(); 1750 final StringBuilder s = new StringBuilder(settingsValues.toString()); 1751 s.append("\nAttributes : ").append(settingsValues.mInputAttributes) 1752 .append("\nContext : ").append(context); 1753 throw new RuntimeException(s.toString()); 1754 } 1755 1756 @Override 1757 protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) { 1758 super.dump(fd, fout, args); 1759 1760 final Printer p = new PrintWriterPrinter(fout); 1761 p.println("LatinIME state :"); 1762 p.println(" VersionCode = " + ApplicationUtils.getVersionCode(this)); 1763 p.println(" VersionName = " + ApplicationUtils.getVersionName(this)); 1764 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1765 final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; 1766 p.println(" Keyboard mode = " + keyboardMode); 1767 final SettingsValues settingsValues = mSettings.getCurrent(); 1768 p.println(settingsValues.dump()); 1769 // TODO: Dump all settings values 1770 } 1771 1772 public boolean shouldSwitchToOtherInputMethods() { 1773 // TODO: Revisit here to reorganize the settings. Probably we can/should use different 1774 // strategy once the implementation of 1775 // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well. 1776 final boolean fallbackValue = mSettings.getCurrent().mIncludesOtherImesInLanguageSwitchList; 1777 final IBinder token = getWindow().getWindow().getAttributes().token; 1778 if (token == null) { 1779 return fallbackValue; 1780 } 1781 return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue); 1782 } 1783 1784 public boolean shouldShowLanguageSwitchKey() { 1785 // TODO: Revisit here to reorganize the settings. Probably we can/should use different 1786 // strategy once the implementation of 1787 // {@link InputMethodManager#shouldOfferSwitchingToNextInputMethod} is defined well. 1788 final boolean fallbackValue = mSettings.getCurrent().isLanguageSwitchKeyEnabled(); 1789 final IBinder token = getWindow().getWindow().getAttributes().token; 1790 if (token == null) { 1791 return fallbackValue; 1792 } 1793 return mRichImm.shouldOfferSwitchingToNextInputMethod(token, fallbackValue); 1794 } 1795} 1796