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