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