LatinIME.java revision a696c924776cea07ec52ed9448dd16d813eddd72
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; 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 mSpecialKeyDetector = new SpecialKeyDetector(this); 521 mIsHardwareAcceleratedDrawingEnabled = 522 InputMethodServiceCompatUtils.enableHardwareAcceleration(this); 523 Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled); 524 } 525 526 @Override 527 public void onCreate() { 528 Settings.init(this); 529 DebugFlags.init(PreferenceManager.getDefaultSharedPreferences(this)); 530 RichInputMethodManager.init(this); 531 mRichImm = RichInputMethodManager.getInstance(); 532 SubtypeSwitcher.init(this); 533 KeyboardSwitcher.init(this); 534 AudioAndHapticFeedbackManager.init(this); 535 AccessibilityUtils.init(this); 536 StatsUtils.init(this); 537 538 super.onCreate(); 539 540 mHandler.onCreate(); 541 DEBUG = DebugFlags.DEBUG_ENABLED; 542 543 // TODO: Resolve mutual dependencies of {@link #loadSettings()} and {@link #initSuggest()}. 544 loadSettings(); 545 resetSuggest(); 546 547 // Register to receive ringer mode change and network state change. 548 // Also receive installation and removal of a dictionary pack. 549 final IntentFilter filter = new IntentFilter(); 550 filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 551 filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); 552 registerReceiver(mConnectivityAndRingerModeChangeReceiver, filter); 553 554 final IntentFilter packageFilter = new IntentFilter(); 555 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); 556 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 557 packageFilter.addDataScheme(SCHEME_PACKAGE); 558 registerReceiver(mDictionaryPackInstallReceiver, packageFilter); 559 560 final IntentFilter newDictFilter = new IntentFilter(); 561 newDictFilter.addAction(DictionaryPackConstants.NEW_DICTIONARY_INTENT_ACTION); 562 registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); 563 564 final IntentFilter dictDumpFilter = new IntentFilter(); 565 dictDumpFilter.addAction(DictionaryDumpBroadcastReceiver.DICTIONARY_DUMP_INTENT_ACTION); 566 registerReceiver(mDictionaryDumpBroadcastReceiver, dictDumpFilter); 567 568 DictionaryDecayBroadcastReciever.setUpIntervalAlarmForDictionaryDecaying(this); 569 570 StatsUtils.onCreate(mSettings.getCurrent()); 571 } 572 573 // Has to be package-visible for unit tests 574 @UsedForTesting 575 void loadSettings() { 576 final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 577 final EditorInfo editorInfo = getCurrentInputEditorInfo(); 578 final InputAttributes inputAttributes = new InputAttributes( 579 editorInfo, isFullscreenMode(), getPackageName()); 580 mSettings.loadSettings(this, locale, inputAttributes); 581 final SettingsValues currentSettingsValues = mSettings.getCurrent(); 582 AudioAndHapticFeedbackManager.getInstance().onSettingsChanged(currentSettingsValues); 583 // This method is called on startup and language switch, before the new layout has 584 // been displayed. Opening dictionaries never affects responsivity as dictionaries are 585 // asynchronously loaded. 586 if (!mHandler.hasPendingReopenDictionaries()) { 587 resetSuggestForLocale(locale); 588 } 589 mDictionaryFacilitator.updateEnabledSubtypes(mRichImm.getMyEnabledInputMethodSubtypeList( 590 true /* allowsImplicitlySelectedSubtypes */)); 591 refreshPersonalizationDictionarySession(currentSettingsValues); 592 StatsUtils.onLoadSettings(currentSettingsValues); 593 } 594 595 private void refreshPersonalizationDictionarySession( 596 final SettingsValues currentSettingsValues) { 597 mPersonalizationDictionaryUpdater.onLoadSettings( 598 currentSettingsValues.mUsePersonalizedDicts, 599 mSubtypeSwitcher.isSystemLocaleSameAsLocaleOfAllEnabledSubtypesOfEnabledImes()); 600 mContextualDictionaryUpdater.onLoadSettings(currentSettingsValues.mUsePersonalizedDicts); 601 final boolean shouldKeepUserHistoryDictionaries; 602 if (currentSettingsValues.mUsePersonalizedDicts) { 603 shouldKeepUserHistoryDictionaries = true; 604 } else { 605 shouldKeepUserHistoryDictionaries = false; 606 } 607 if (!shouldKeepUserHistoryDictionaries) { 608 // Remove user history dictionaries. 609 PersonalizationHelper.removeAllUserHistoryDictionaries(this); 610 mDictionaryFacilitator.clearUserHistoryDictionary(); 611 } 612 } 613 614 // Note that this method is called from a non-UI thread. 615 @Override 616 public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) { 617 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 618 if (mainKeyboardView != null) { 619 mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable); 620 } 621 if (mHandler.hasPendingWaitForDictionaryLoad()) { 622 mHandler.cancelWaitForDictionaryLoad(); 623 mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 624 false /* shouldDelay */); 625 } 626 } 627 628 private void resetSuggest() { 629 final Locale switcherSubtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 630 final String switcherLocaleStr = switcherSubtypeLocale.toString(); 631 final Locale subtypeLocale; 632 if (TextUtils.isEmpty(switcherLocaleStr)) { 633 // This happens in very rare corner cases - for example, immediately after a switch 634 // to LatinIME has been requested, about a frame later another switch happens. In this 635 // case, we are about to go down but we still don't know it, however the system tells 636 // us there is no current subtype so the locale is the empty string. Take the best 637 // possible guess instead -- it's bound to have no consequences, and we have no way 638 // of knowing anyway. 639 Log.e(TAG, "System is reporting no current subtype."); 640 subtypeLocale = getResources().getConfiguration().locale; 641 } else { 642 subtypeLocale = switcherSubtypeLocale; 643 } 644 resetSuggestForLocale(subtypeLocale); 645 } 646 647 /** 648 * Reset suggest by loading dictionaries for the locale and the current settings values. 649 * 650 * @param locale the locale 651 */ 652 private void resetSuggestForLocale(final Locale locale) { 653 final SettingsValues settingsValues = mSettings.getCurrent(); 654 mDictionaryFacilitator.resetDictionaries(this /* context */, locale, 655 settingsValues.mUseContactsDict, settingsValues.mUsePersonalizedDicts, 656 false /* forceReloadMainDictionary */, this); 657 if (settingsValues.mAutoCorrectionEnabledPerUserSettings) { 658 mInputLogic.mSuggest.setAutoCorrectionThreshold( 659 settingsValues.mAutoCorrectionThreshold); 660 } 661 } 662 663 /** 664 * Reset suggest by loading the main dictionary of the current locale. 665 */ 666 /* package private */ void resetSuggestMainDict() { 667 final SettingsValues settingsValues = mSettings.getCurrent(); 668 mDictionaryFacilitator.resetDictionaries(this /* context */, 669 mDictionaryFacilitator.getLocale(), settingsValues.mUseContactsDict, 670 settingsValues.mUsePersonalizedDicts, true /* forceReloadMainDictionary */, this); 671 } 672 673 @Override 674 public void onDestroy() { 675 mDictionaryFacilitator.closeDictionaries(); 676 mPersonalizationDictionaryUpdater.onDestroy(); 677 mContextualDictionaryUpdater.onDestroy(); 678 mSettings.onDestroy(); 679 unregisterReceiver(mConnectivityAndRingerModeChangeReceiver); 680 unregisterReceiver(mDictionaryPackInstallReceiver); 681 unregisterReceiver(mDictionaryDumpBroadcastReceiver); 682 StatsUtils.onDestroy(); 683 super.onDestroy(); 684 } 685 686 @UsedForTesting 687 public void recycle() { 688 unregisterReceiver(mDictionaryPackInstallReceiver); 689 unregisterReceiver(mDictionaryDumpBroadcastReceiver); 690 unregisterReceiver(mConnectivityAndRingerModeChangeReceiver); 691 mInputLogic.recycle(); 692 } 693 694 @Override 695 public void onConfigurationChanged(final Configuration conf) { 696 final SettingsValues settingsValues = mSettings.getCurrent(); 697 if (settingsValues.mDisplayOrientation != conf.orientation) { 698 mHandler.startOrientationChanging(); 699 mInputLogic.onOrientationChange(mSettings.getCurrent()); 700 } 701 // TODO: Remove this test. 702 if (!conf.locale.equals(mPersonalizationDictionaryUpdater.getLocale())) { 703 refreshPersonalizationDictionarySession(settingsValues); 704 } 705 super.onConfigurationChanged(conf); 706 } 707 708 @Override 709 public View onCreateInputView() { 710 return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled); 711 } 712 713 @Override 714 public void setInputView(final View view) { 715 super.setInputView(view); 716 mInputView = view; 717 mExtractArea = getWindow().getWindow().getDecorView() 718 .findViewById(android.R.id.extractArea); 719 mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing); 720 mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view); 721 if (hasSuggestionStripView()) { 722 mSuggestionStripView.setListener(this, view); 723 } 724 } 725 726 @Override 727 public void setCandidatesView(final View view) { 728 // To ensure that CandidatesView will never be set. 729 return; 730 } 731 732 @Override 733 public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { 734 mHandler.onStartInput(editorInfo, restarting); 735 } 736 737 @Override 738 public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { 739 mHandler.onStartInputView(editorInfo, restarting); 740 } 741 742 @Override 743 public void onFinishInputView(final boolean finishingInput) { 744 mHandler.onFinishInputView(finishingInput); 745 } 746 747 @Override 748 public void onFinishInput() { 749 mHandler.onFinishInput(); 750 } 751 752 @Override 753 public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) { 754 // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() 755 // is not guaranteed. It may even be called at the same time on a different thread. 756 mSubtypeSwitcher.onSubtypeChanged(subtype); 757 mInputLogic.onSubtypeChanged(SubtypeLocaleUtils.getCombiningRulesExtraValue(subtype)); 758 loadKeyboard(); 759 } 760 761 private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { 762 super.onStartInput(editorInfo, restarting); 763 } 764 765 @SuppressWarnings("deprecation") 766 private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { 767 super.onStartInputView(editorInfo, restarting); 768 mRichImm.clearSubtypeCaches(); 769 final KeyboardSwitcher switcher = mKeyboardSwitcher; 770 switcher.updateKeyboardTheme(); 771 final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); 772 // If we are starting input in a different text field from before, we'll have to reload 773 // settings, so currentSettingsValues can't be final. 774 SettingsValues currentSettingsValues = mSettings.getCurrent(); 775 776 if (editorInfo == null) { 777 Log.e(TAG, "Null EditorInfo in onStartInputView()"); 778 if (DebugFlags.DEBUG_ENABLED) { 779 throw new NullPointerException("Null EditorInfo in onStartInputView()"); 780 } 781 return; 782 } 783 if (DEBUG) { 784 Log.d(TAG, "onStartInputView: editorInfo:" 785 + String.format("inputType=0x%08x imeOptions=0x%08x", 786 editorInfo.inputType, editorInfo.imeOptions)); 787 Log.d(TAG, "All caps = " 788 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) 789 + ", sentence caps = " 790 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) 791 + ", word caps = " 792 + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); 793 } 794 Log.i(TAG, "Starting input. Cursor position = " 795 + editorInfo.initialSelStart + "," + editorInfo.initialSelEnd); 796 // TODO: Consolidate these checks with {@link InputAttributes}. 797 if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { 798 Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); 799 Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); 800 } 801 if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { 802 Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); 803 Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); 804 } 805 806 // In landscape mode, this method gets called without the input view being created. 807 if (mainKeyboardView == null) { 808 return; 809 } 810 811 // Forward this event to the accessibility utilities, if enabled. 812 final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); 813 if (accessUtils.isTouchExplorationEnabled()) { 814 accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); 815 } 816 817 final boolean inputTypeChanged = !currentSettingsValues.isSameInputType(editorInfo); 818 final boolean isDifferentTextField = !restarting || inputTypeChanged; 819 if (isDifferentTextField) { 820 mSubtypeSwitcher.updateParametersOnStartInputView(); 821 } 822 823 // The EditorInfo might have a flag that affects fullscreen mode. 824 // Note: This call should be done by InputMethodService? 825 updateFullscreenMode(); 826 827 // The app calling setText() has the effect of clearing the composing 828 // span, so we should reset our state unconditionally, even if restarting is true. 829 // We also tell the input logic about the combining rules for the current subtype, so 830 // it can adjust its combiners if needed. 831 mInputLogic.startInput(mSubtypeSwitcher.getCombiningRulesExtraValueOfCurrentSubtype()); 832 833 // Note: the following does a round-trip IPC on the main thread: be careful 834 final Locale currentLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); 835 final Suggest suggest = mInputLogic.mSuggest; 836 if (null != currentLocale && !currentLocale.equals(suggest.getLocale())) { 837 // TODO: Do this automatically. 838 resetSuggest(); 839 } 840 841 // TODO[IL]: Can the following be moved to InputLogic#startInput? 842 final boolean canReachInputConnection; 843 if (!mInputLogic.mConnection.resetCachesUponCursorMoveAndReturnSuccess( 844 editorInfo.initialSelStart, editorInfo.initialSelEnd, 845 false /* shouldFinishComposition */)) { 846 // Sometimes, while rotating, for some reason the framework tells the app we are not 847 // connected to it and that means we can't refresh the cache. In this case, schedule a 848 // refresh later. 849 // We try resetting the caches up to 5 times before giving up. 850 mHandler.postResetCaches(isDifferentTextField, 5 /* remainingTries */); 851 // mLastSelection{Start,End} are reset later in this method, don't need to do it here 852 canReachInputConnection = false; 853 } else { 854 // When rotating, initialSelStart and initialSelEnd sometimes are lying. Make a best 855 // effort to work around this bug. 856 mInputLogic.mConnection.tryFixLyingCursorPosition(); 857 mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, 858 true /* shouldDelay */); 859 canReachInputConnection = true; 860 } 861 862 if (isDifferentTextField || 863 !currentSettingsValues.hasSameOrientation(getResources().getConfiguration())) { 864 loadSettings(); 865 } 866 if (isDifferentTextField) { 867 mainKeyboardView.closing(); 868 currentSettingsValues = mSettings.getCurrent(); 869 870 if (currentSettingsValues.mAutoCorrectionEnabledPerUserSettings) { 871 suggest.setAutoCorrectionThreshold( 872 currentSettingsValues.mAutoCorrectionThreshold); 873 } 874 875 switcher.loadKeyboard(editorInfo, currentSettingsValues, getCurrentAutoCapsState(), 876 getCurrentRecapitalizeState()); 877 if (!canReachInputConnection) { 878 // If we can't reach the input connection, we will call loadKeyboard again later, 879 // so we need to save its state now. The call will be done in #retryResetCaches. 880 switcher.saveKeyboardState(); 881 } 882 } else if (restarting) { 883 // TODO: Come up with a more comprehensive way to reset the keyboard layout when 884 // a keyboard layout set doesn't get reloaded in this method. 885 switcher.resetKeyboardStateToAlphabet(getCurrentAutoCapsState(), 886 getCurrentRecapitalizeState()); 887 // In apps like Talk, we come here when the text is sent and the field gets emptied and 888 // we need to re-evaluate the shift state, but not the whole layout which would be 889 // disruptive. 890 // Space state must be updated before calling updateShiftState 891 switcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 892 getCurrentRecapitalizeState()); 893 } 894 // This will set the punctuation suggestions if next word suggestion is off; 895 // otherwise it will clear the suggestion strip. 896 setNeutralSuggestionStrip(); 897 898 mHandler.cancelUpdateSuggestionStrip(); 899 900 mainKeyboardView.setMainDictionaryAvailability( 901 mDictionaryFacilitator.hasInitializedMainDictionary()); 902 mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn, 903 currentSettingsValues.mKeyPreviewPopupDismissDelay); 904 mainKeyboardView.setSlidingKeyInputPreviewEnabled( 905 currentSettingsValues.mSlidingKeyInputPreviewEnabled); 906 mainKeyboardView.setGestureHandlingEnabledByUser( 907 currentSettingsValues.mGestureInputEnabled, 908 currentSettingsValues.mGestureTrailEnabled, 909 currentSettingsValues.mGestureFloatingPreviewTextEnabled); 910 911 // Contextual dictionary should be updated for the current application. 912 mContextualDictionaryUpdater.onStartInputView(editorInfo.packageName); 913 if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); 914 } 915 916 @Override 917 public void onWindowHidden() { 918 super.onWindowHidden(); 919 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 920 if (mainKeyboardView != null) { 921 mainKeyboardView.closing(); 922 } 923 } 924 925 private void onFinishInputInternal() { 926 super.onFinishInput(); 927 928 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 929 if (mainKeyboardView != null) { 930 mainKeyboardView.closing(); 931 } 932 } 933 934 private void onFinishInputViewInternal(final boolean finishingInput) { 935 super.onFinishInputView(finishingInput); 936 mKeyboardSwitcher.deallocateMemory(); 937 // Remove pending messages related to update suggestions 938 mHandler.cancelUpdateSuggestionStrip(); 939 // Should do the following in onFinishInputInternal but until JB MR2 it's not called :( 940 mInputLogic.finishInput(); 941 } 942 943 @Override 944 public void onUpdateSelection(final int oldSelStart, final int oldSelEnd, 945 final int newSelStart, final int newSelEnd, 946 final int composingSpanStart, final int composingSpanEnd) { 947 super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, 948 composingSpanStart, composingSpanEnd); 949 if (DEBUG) { 950 Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd 951 + ", nss=" + newSelStart + ", nse=" + newSelEnd 952 + ", cs=" + composingSpanStart + ", ce=" + composingSpanEnd); 953 } 954 955 // If the keyboard is not visible, we don't need to do all the housekeeping work, as it 956 // will be reset when the keyboard shows up anyway. 957 // TODO: revisit this when LatinIME supports hardware keyboards. 958 // NOTE: the test harness subclasses LatinIME and overrides isInputViewShown(). 959 // TODO: find a better way to simulate actual execution. 960 if (isInputViewShown() && 961 mInputLogic.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd)) { 962 mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 963 getCurrentRecapitalizeState()); 964 } 965 } 966 967 @Override 968 public void onUpdateCursor(final Rect rect) { 969 if (DEBUG) { 970 Log.i(TAG, "onUpdateCursor:" + rect.toShortString()); 971 } 972 super.onUpdateCursor(rect); 973 } 974 975 /** 976 * This is called when the user has clicked on the extracted text view, 977 * when running in fullscreen mode. The default implementation hides 978 * the suggestions view when this happens, but only if the extracted text 979 * editor has a vertical scroll bar because its text doesn't fit. 980 * Here we override the behavior due to the possibility that a re-correction could 981 * cause the suggestions strip to disappear and re-appear. 982 */ 983 @Override 984 public void onExtractedTextClicked() { 985 if (mSettings.getCurrent().needsToLookupSuggestions()) { 986 return; 987 } 988 989 super.onExtractedTextClicked(); 990 } 991 992 /** 993 * This is called when the user has performed a cursor movement in the 994 * extracted text view, when it is running in fullscreen mode. The default 995 * implementation hides the suggestions view when a vertical movement 996 * happens, but only if the extracted text editor has a vertical scroll bar 997 * because its text doesn't fit. 998 * Here we override the behavior due to the possibility that a re-correction could 999 * cause the suggestions strip to disappear and re-appear. 1000 */ 1001 @Override 1002 public void onExtractedCursorMovement(final int dx, final int dy) { 1003 if (mSettings.getCurrent().needsToLookupSuggestions()) { 1004 return; 1005 } 1006 1007 super.onExtractedCursorMovement(dx, dy); 1008 } 1009 1010 @Override 1011 public void hideWindow() { 1012 mKeyboardSwitcher.onHideWindow(); 1013 1014 if (TRACE) Debug.stopMethodTracing(); 1015 if (isShowingOptionDialog()) { 1016 mOptionsDialog.dismiss(); 1017 mOptionsDialog = null; 1018 } 1019 super.hideWindow(); 1020 } 1021 1022 @Override 1023 public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) { 1024 if (DEBUG) { 1025 Log.i(TAG, "Received completions:"); 1026 if (applicationSpecifiedCompletions != null) { 1027 for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { 1028 Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); 1029 } 1030 } 1031 } 1032 if (!mSettings.getCurrent().isApplicationSpecifiedCompletionsOn()) { 1033 return; 1034 } 1035 // If we have an update request in flight, we need to cancel it so it does not override 1036 // these completions. 1037 mHandler.cancelUpdateSuggestionStrip(); 1038 if (applicationSpecifiedCompletions == null) { 1039 setNeutralSuggestionStrip(); 1040 return; 1041 } 1042 1043 final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords = 1044 SuggestedWords.getFromApplicationSpecifiedCompletions( 1045 applicationSpecifiedCompletions); 1046 final SuggestedWords suggestedWords = new SuggestedWords(applicationSuggestedWords, 1047 null /* rawSuggestions */, false /* typedWordValid */, false /* willAutoCorrect */, 1048 false /* isObsoleteSuggestions */, false /* isPrediction */); 1049 // When in fullscreen mode, show completions generated by the application forcibly 1050 setSuggestedWords(suggestedWords); 1051 } 1052 1053 private int getAdjustedBackingViewHeight() { 1054 final int currentHeight = mKeyPreviewBackingView.getHeight(); 1055 if (currentHeight > 0) { 1056 return currentHeight; 1057 } 1058 1059 final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView(); 1060 if (visibleKeyboardView == null) { 1061 return 0; 1062 } 1063 // TODO: !!!!!!!!!!!!!!!!!!!! Handle different backing view heights between the main !!! 1064 // keyboard and the emoji keyboard. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 1065 final int keyboardHeight = visibleKeyboardView.getHeight(); 1066 final int suggestionsHeight = mSuggestionStripView.getHeight(); 1067 final int displayHeight = getResources().getDisplayMetrics().heightPixels; 1068 final Rect rect = new Rect(); 1069 mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect); 1070 final int notificationBarHeight = rect.top; 1071 final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight 1072 - keyboardHeight; 1073 1074 final LayoutParams params = mKeyPreviewBackingView.getLayoutParams(); 1075 params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight); 1076 mKeyPreviewBackingView.setLayoutParams(params); 1077 return params.height; 1078 } 1079 1080 @Override 1081 public void onComputeInsets(final InputMethodService.Insets outInsets) { 1082 super.onComputeInsets(outInsets); 1083 final View visibleKeyboardView = mKeyboardSwitcher.getVisibleKeyboardView(); 1084 if (visibleKeyboardView == null || !hasSuggestionStripView()) { 1085 return; 1086 } 1087 final boolean hasHardwareKeyboard = mKeyboardSwitcher.hasHardwareKeyboard(); 1088 if (hasHardwareKeyboard && visibleKeyboardView.getVisibility() == View.GONE) { 1089 // If there is a hardware keyboard and a visible software keyboard view has been hidden, 1090 // no visual element will be shown on the screen. 1091 outInsets.touchableInsets = mInputView.getHeight(); 1092 outInsets.visibleTopInsets = mInputView.getHeight(); 1093 return; 1094 } 1095 final int adjustedBackingHeight = getAdjustedBackingViewHeight(); 1096 final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE); 1097 final int backingHeight = backingGone ? 0 : adjustedBackingHeight; 1098 // In fullscreen mode, the height of the extract area managed by InputMethodService should 1099 // be considered. 1100 // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}. 1101 final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0; 1102 final int suggestionsHeight = (mSuggestionStripView.getVisibility() == View.GONE) ? 0 1103 : mSuggestionStripView.getHeight(); 1104 final int extraHeight = extractHeight + backingHeight + suggestionsHeight; 1105 int visibleTopY = extraHeight; 1106 // Need to set touchable region only if input view is being shown 1107 if (visibleKeyboardView.isShown()) { 1108 // Note that the height of Emoji layout is the same as the height of the main keyboard 1109 // and the suggestion strip 1110 if (mKeyboardSwitcher.isShowingEmojiPalettes() 1111 || mSuggestionStripView.getVisibility() == View.VISIBLE) { 1112 visibleTopY -= suggestionsHeight; 1113 } 1114 final int touchY = mKeyboardSwitcher.isShowingMoreKeysPanel() ? 0 : visibleTopY; 1115 final int touchWidth = visibleKeyboardView.getWidth(); 1116 final int touchHeight = visibleKeyboardView.getHeight() + extraHeight 1117 // Extend touchable region below the keyboard. 1118 + EXTENDED_TOUCHABLE_REGION_HEIGHT; 1119 outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; 1120 outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight); 1121 } 1122 outInsets.contentTopInsets = visibleTopY; 1123 outInsets.visibleTopInsets = visibleTopY; 1124 } 1125 1126 @Override 1127 public boolean onEvaluateInputViewShown() { 1128 // Always show {@link InputView}. 1129 return true; 1130 } 1131 1132 @Override 1133 public boolean onEvaluateFullscreenMode() { 1134 if (mKeyboardSwitcher.hasHardwareKeyboard()) { 1135 // If there is a hardware keyboard, disable full screen mode. 1136 return false; 1137 } 1138 // Reread resource value here, because this method is called by the framework as needed. 1139 final boolean isFullscreenModeAllowed = Settings.readUseFullscreenMode(getResources()); 1140 if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) { 1141 // TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI 1142 // implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI 1143 // without NO_FULLSCREEN doesn't work as expected. Because of this we need this 1144 // hack for now. Let's get rid of this once the framework gets fixed. 1145 final EditorInfo ei = getCurrentInputEditorInfo(); 1146 return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0)); 1147 } else { 1148 return false; 1149 } 1150 } 1151 1152 @Override 1153 public void updateFullscreenMode() { 1154 super.updateFullscreenMode(); 1155 1156 if (mKeyPreviewBackingView == null) return; 1157 // In fullscreen mode, no need to have extra space to show the key preview. 1158 // If not, we should have extra space above the keyboard to show the key preview. 1159 mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE); 1160 } 1161 1162 private int getCurrentAutoCapsState() { 1163 return mInputLogic.getCurrentAutoCapsState(mSettings.getCurrent()); 1164 } 1165 1166 private int getCurrentRecapitalizeState() { 1167 return mInputLogic.getCurrentRecapitalizeState(); 1168 } 1169 1170 public Locale getCurrentSubtypeLocale() { 1171 return mSubtypeSwitcher.getCurrentSubtypeLocale(); 1172 } 1173 1174 /** 1175 * @param codePoints code points to get coordinates for. 1176 * @return x,y coordinates for this keyboard, as a flattened array. 1177 */ 1178 public int[] getCoordinatesForCurrentKeyboard(final int[] codePoints) { 1179 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1180 if (null == keyboard) { 1181 return CoordinateUtils.newCoordinateArray(codePoints.length, 1182 Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); 1183 } else { 1184 return keyboard.getCoordinates(codePoints); 1185 } 1186 } 1187 1188 // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is 1189 // pressed. 1190 @Override 1191 public void addWordToUserDictionary(final String word) { 1192 if (TextUtils.isEmpty(word)) { 1193 // Probably never supposed to happen, but just in case. 1194 return; 1195 } 1196 final String wordToEdit; 1197 if (CapsModeUtils.isAutoCapsMode(mInputLogic.mLastComposedWord.mCapitalizedMode)) { 1198 wordToEdit = word.toLowerCase(getCurrentSubtypeLocale()); 1199 } else { 1200 wordToEdit = word; 1201 } 1202 mDictionaryFacilitator.addWordToUserDictionary(this /* context */, wordToEdit); 1203 } 1204 1205 // Callback for the {@link SuggestionStripView}, to call when the important notice strip is 1206 // pressed. 1207 @Override 1208 public void showImportantNoticeContents() { 1209 showOptionDialog(new ImportantNoticeDialog(this /* context */, this /* listener */)); 1210 } 1211 1212 // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener} 1213 @Override 1214 public void onClickSettingsOfImportantNoticeDialog(final int nextVersion) { 1215 launchSettings(); 1216 } 1217 1218 // Implement {@link ImportantNoticeDialog.ImportantNoticeDialogListener} 1219 @Override 1220 public void onUserAcknowledgmentOfImportantNoticeDialog(final int nextVersion) { 1221 setNeutralSuggestionStrip(); 1222 } 1223 1224 public void displaySettingsDialog() { 1225 if (isShowingOptionDialog()) { 1226 return; 1227 } 1228 showSubtypeSelectorAndSettings(); 1229 } 1230 1231 @Override 1232 public boolean onCustomRequest(final int requestCode) { 1233 if (isShowingOptionDialog()) return false; 1234 switch (requestCode) { 1235 case Constants.CUSTOM_CODE_SHOW_INPUT_METHOD_PICKER: 1236 if (mRichImm.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { 1237 mRichImm.getInputMethodManager().showInputMethodPicker(); 1238 return true; 1239 } 1240 return false; 1241 } 1242 return false; 1243 } 1244 1245 private boolean isShowingOptionDialog() { 1246 return mOptionsDialog != null && mOptionsDialog.isShowing(); 1247 } 1248 1249 // TODO: Revise the language switch key behavior to make it much smarter and more reasonable. 1250 public void switchToNextSubtype() { 1251 final IBinder token = getWindow().getWindow().getAttributes().token; 1252 if (shouldSwitchToOtherInputMethods()) { 1253 mRichImm.switchToNextInputMethod(token, false /* onlyCurrentIme */); 1254 return; 1255 } 1256 mSubtypeState.switchSubtype(token, mRichImm); 1257 } 1258 1259 // Implementation of {@link KeyboardActionListener}. 1260 @Override 1261 public void onCodeInput(final int codePoint, final int x, final int y, 1262 final boolean isKeyRepeat) { 1263 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1264 // x and y include some padding, but everything down the line (especially native 1265 // code) needs the coordinates in the keyboard frame. 1266 // TODO: We should reconsider which coordinate system should be used to represent 1267 // keyboard event. Also we should pull this up -- LatinIME has no business doing 1268 // this transformation, it should be done already before calling onCodeInput. 1269 final int keyX = mainKeyboardView.getKeyX(x); 1270 final int keyY = mainKeyboardView.getKeyY(y); 1271 final int codeToSend; 1272 if (Constants.CODE_SHIFT == codePoint) { 1273 // TODO: Instead of checking for alphabetic keyboard here, separate keycodes for 1274 // alphabetic shift and shift while in symbol layout. 1275 final Keyboard currentKeyboard = mKeyboardSwitcher.getKeyboard(); 1276 if (null != currentKeyboard && currentKeyboard.mId.isAlphabetKeyboard()) { 1277 codeToSend = codePoint; 1278 } else { 1279 codeToSend = Constants.CODE_SYMBOL_SHIFT; 1280 } 1281 } else { 1282 codeToSend = codePoint; 1283 } 1284 if (Constants.CODE_SHORTCUT == codePoint) { 1285 mSubtypeSwitcher.switchToShortcutIME(this); 1286 // Still call the *#onCodeInput methods for readability. 1287 } 1288 final Event event = createSoftwareKeypressEvent(codeToSend, keyX, keyY, isKeyRepeat); 1289 final InputTransaction completeInputTransaction = 1290 mInputLogic.onCodeInput(mSettings.getCurrent(), event, 1291 mKeyboardSwitcher.getKeyboardShiftMode(), 1292 mKeyboardSwitcher.getCurrentKeyboardScriptId(), mHandler); 1293 updateStateAfterInputTransaction(completeInputTransaction); 1294 mKeyboardSwitcher.onCodeInput(codePoint, getCurrentAutoCapsState(), 1295 getCurrentRecapitalizeState()); 1296 } 1297 1298 // A helper method to split the code point and the key code. Ultimately, they should not be 1299 // squashed into the same variable, and this method should be removed. 1300 private static Event createSoftwareKeypressEvent(final int keyCodeOrCodePoint, final int keyX, 1301 final int keyY, final boolean isKeyRepeat) { 1302 final int keyCode; 1303 final int codePoint; 1304 if (keyCodeOrCodePoint <= 0) { 1305 keyCode = keyCodeOrCodePoint; 1306 codePoint = Event.NOT_A_CODE_POINT; 1307 } else { 1308 keyCode = Event.NOT_A_KEY_CODE; 1309 codePoint = keyCodeOrCodePoint; 1310 } 1311 return Event.createSoftwareKeypressEvent(codePoint, keyCode, keyX, keyY, isKeyRepeat); 1312 } 1313 1314 // Called from PointerTracker through the KeyboardActionListener interface 1315 @Override 1316 public void onTextInput(final String rawText) { 1317 // TODO: have the keyboard pass the correct key code when we need it. 1318 final Event event = Event.createSoftwareTextEvent(rawText, Event.NOT_A_KEY_CODE); 1319 final InputTransaction completeInputTransaction = 1320 mInputLogic.onTextInput(mSettings.getCurrent(), event, 1321 mKeyboardSwitcher.getKeyboardShiftMode(), mHandler); 1322 updateStateAfterInputTransaction(completeInputTransaction); 1323 mKeyboardSwitcher.onCodeInput(Constants.CODE_OUTPUT_TEXT, getCurrentAutoCapsState(), 1324 getCurrentRecapitalizeState()); 1325 } 1326 1327 @Override 1328 public void onStartBatchInput() { 1329 mInputLogic.onStartBatchInput(mSettings.getCurrent(), mKeyboardSwitcher, mHandler); 1330 } 1331 1332 @Override 1333 public void onUpdateBatchInput(final InputPointers batchPointers) { 1334 mInputLogic.onUpdateBatchInput(mSettings.getCurrent(), batchPointers, mKeyboardSwitcher); 1335 } 1336 1337 @Override 1338 public void onEndBatchInput(final InputPointers batchPointers) { 1339 mInputLogic.onEndBatchInput(batchPointers); 1340 } 1341 1342 @Override 1343 public void onCancelBatchInput() { 1344 mInputLogic.onCancelBatchInput(mHandler); 1345 } 1346 1347 // This method must run on the UI Thread. 1348 private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, 1349 final boolean dismissGestureFloatingPreviewText) { 1350 showSuggestionStrip(suggestedWords); 1351 final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1352 mainKeyboardView.showGestureFloatingPreviewText(suggestedWords); 1353 if (dismissGestureFloatingPreviewText) { 1354 mainKeyboardView.dismissGestureFloatingPreviewText(); 1355 } 1356 } 1357 1358 // Called from PointerTracker through the KeyboardActionListener interface 1359 @Override 1360 public void onFinishSlidingInput() { 1361 // User finished sliding input. 1362 mKeyboardSwitcher.onFinishSlidingInput(getCurrentAutoCapsState(), 1363 getCurrentRecapitalizeState()); 1364 } 1365 1366 // Called from PointerTracker through the KeyboardActionListener interface 1367 @Override 1368 public void onCancelInput() { 1369 // User released a finger outside any key 1370 // Nothing to do so far. 1371 } 1372 1373 public boolean hasSuggestionStripView() { 1374 return null != mSuggestionStripView; 1375 } 1376 1377 @Override 1378 public boolean isShowingAddToDictionaryHint() { 1379 return hasSuggestionStripView() && mSuggestionStripView.isShowingAddToDictionaryHint(); 1380 } 1381 1382 @Override 1383 public void dismissAddToDictionaryHint() { 1384 if (!hasSuggestionStripView()) { 1385 return; 1386 } 1387 mSuggestionStripView.dismissAddToDictionaryHint(); 1388 } 1389 1390 private void setSuggestedWords(final SuggestedWords suggestedWords) { 1391 mInputLogic.setSuggestedWords(suggestedWords); 1392 // TODO: Modify this when we support suggestions with hard keyboard 1393 if (!hasSuggestionStripView()) { 1394 return; 1395 } 1396 if (!onEvaluateInputViewShown()) { 1397 return; 1398 } 1399 1400 final SettingsValues currentSettingsValues = mSettings.getCurrent(); 1401 final boolean shouldShowImportantNotice = 1402 ImportantNoticeUtils.shouldShowImportantNotice(this); 1403 final boolean shouldShowSuggestionCandidates = 1404 currentSettingsValues.mInputAttributes.mShouldShowSuggestions 1405 && currentSettingsValues.isSuggestionsEnabledPerUserSettings(); 1406 final boolean shouldShowSuggestionsStripUnlessPassword = shouldShowImportantNotice 1407 || currentSettingsValues.mShowsVoiceInputKey 1408 || shouldShowSuggestionCandidates 1409 || currentSettingsValues.isApplicationSpecifiedCompletionsOn(); 1410 final boolean shouldShowSuggestionsStrip = shouldShowSuggestionsStripUnlessPassword 1411 && !currentSettingsValues.mInputAttributes.mIsPasswordField; 1412 mSuggestionStripView.updateVisibility(shouldShowSuggestionsStrip, isFullscreenMode()); 1413 if (!shouldShowSuggestionsStrip) { 1414 return; 1415 } 1416 1417 final boolean isEmptyApplicationSpecifiedCompletions = 1418 currentSettingsValues.isApplicationSpecifiedCompletionsOn() 1419 && suggestedWords.isEmpty(); 1420 final boolean noSuggestionsToShow = (SuggestedWords.EMPTY == suggestedWords) 1421 || suggestedWords.isPunctuationSuggestions() 1422 || isEmptyApplicationSpecifiedCompletions; 1423 if (shouldShowImportantNotice && noSuggestionsToShow) { 1424 if (mSuggestionStripView.maybeShowImportantNoticeTitle()) { 1425 return; 1426 } 1427 } 1428 1429 if (currentSettingsValues.isSuggestionsEnabledPerUserSettings() 1430 // We should clear suggestions if there is no suggestion to show. 1431 || noSuggestionsToShow 1432 || currentSettingsValues.isApplicationSpecifiedCompletionsOn()) { 1433 mSuggestionStripView.setSuggestions(suggestedWords, 1434 SubtypeLocaleUtils.isRtlLanguage(mSubtypeSwitcher.getCurrentSubtype())); 1435 } 1436 } 1437 1438 // TODO[IL]: Move this out of LatinIME. 1439 public void getSuggestedWords(final int sessionId, final int sequenceNumber, 1440 final OnGetSuggestedWordsCallback callback) { 1441 final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); 1442 if (keyboard == null) { 1443 callback.onGetSuggestedWords(SuggestedWords.EMPTY); 1444 return; 1445 } 1446 mInputLogic.getSuggestedWords(mSettings.getCurrent(), keyboard.getProximityInfo(), 1447 mKeyboardSwitcher.getKeyboardShiftMode(), sessionId, sequenceNumber, callback); 1448 } 1449 1450 @Override 1451 public void showSuggestionStrip(final SuggestedWords sourceSuggestedWords) { 1452 final SuggestedWords suggestedWords = 1453 sourceSuggestedWords.isEmpty() ? SuggestedWords.EMPTY : sourceSuggestedWords; 1454 if (SuggestedWords.EMPTY == suggestedWords) { 1455 setNeutralSuggestionStrip(); 1456 } else { 1457 setSuggestedWords(suggestedWords); 1458 } 1459 // Cache the auto-correction in accessibility code so we can speak it if the user 1460 // touches a key that will insert it. 1461 AccessibilityUtils.getInstance().setAutoCorrection(suggestedWords, 1462 sourceSuggestedWords.mTypedWord); 1463 } 1464 1465 // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} 1466 // interface 1467 @Override 1468 public void pickSuggestionManually(final SuggestedWordInfo suggestionInfo) { 1469 final InputTransaction completeInputTransaction = mInputLogic.onPickSuggestionManually( 1470 mSettings.getCurrent(), suggestionInfo, 1471 mKeyboardSwitcher.getKeyboardShiftMode(), 1472 mKeyboardSwitcher.getCurrentKeyboardScriptId(), 1473 mHandler); 1474 updateStateAfterInputTransaction(completeInputTransaction); 1475 } 1476 1477 @Override 1478 public void showAddToDictionaryHint(final String word) { 1479 if (!hasSuggestionStripView()) { 1480 return; 1481 } 1482 mSuggestionStripView.showAddToDictionaryHint(word); 1483 } 1484 1485 // This will show either an empty suggestion strip (if prediction is enabled) or 1486 // punctuation suggestions (if it's disabled). 1487 @Override 1488 public void setNeutralSuggestionStrip() { 1489 final SettingsValues currentSettings = mSettings.getCurrent(); 1490 final SuggestedWords neutralSuggestions = currentSettings.mBigramPredictionEnabled 1491 ? SuggestedWords.EMPTY : currentSettings.mSpacingAndPunctuations.mSuggestPuncList; 1492 setSuggestedWords(neutralSuggestions); 1493 } 1494 1495 // TODO: Make this private 1496 // Outside LatinIME, only used by the {@link InputTestsBase} test suite. 1497 @UsedForTesting 1498 void loadKeyboard() { 1499 // Since we are switching languages, the most urgent thing is to let the keyboard graphics 1500 // update. LoadKeyboard does that, but we need to wait for buffer flip for it to be on 1501 // the screen. Anything we do right now will delay this, so wait until the next frame 1502 // before we do the rest, like reopening dictionaries and updating suggestions. So we 1503 // post a message. 1504 mHandler.postReopenDictionaries(); 1505 loadSettings(); 1506 if (mKeyboardSwitcher.getMainKeyboardView() != null) { 1507 // Reload keyboard because the current language has been changed. 1508 mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettings.getCurrent(), 1509 getCurrentAutoCapsState(), getCurrentRecapitalizeState()); 1510 } 1511 } 1512 1513 /** 1514 * After an input transaction has been executed, some state must be updated. This includes 1515 * the shift state of the keyboard and suggestions. This method looks at the finished 1516 * inputTransaction to find out what is necessary and updates the state accordingly. 1517 * @param inputTransaction The transaction that has been executed. 1518 */ 1519 private void updateStateAfterInputTransaction(final InputTransaction inputTransaction) { 1520 switch (inputTransaction.getRequiredShiftUpdate()) { 1521 case InputTransaction.SHIFT_UPDATE_LATER: 1522 mHandler.postUpdateShiftState(); 1523 break; 1524 case InputTransaction.SHIFT_UPDATE_NOW: 1525 mKeyboardSwitcher.requestUpdatingShiftState(getCurrentAutoCapsState(), 1526 getCurrentRecapitalizeState()); 1527 break; 1528 default: // SHIFT_NO_UPDATE 1529 } 1530 if (inputTransaction.requiresUpdateSuggestions()) { 1531 mHandler.postUpdateSuggestionStrip(); 1532 } 1533 if (inputTransaction.didAffectContents()) { 1534 mSubtypeState.setCurrentSubtypeHasBeenUsed(); 1535 } 1536 } 1537 1538 private void hapticAndAudioFeedback(final int code, final int repeatCount) { 1539 final MainKeyboardView keyboardView = mKeyboardSwitcher.getMainKeyboardView(); 1540 if (keyboardView != null && keyboardView.isInDraggingFinger()) { 1541 // No need to feedback while finger is dragging. 1542 return; 1543 } 1544 if (repeatCount > 0) { 1545 if (code == Constants.CODE_DELETE && !mInputLogic.mConnection.canDeleteCharacters()) { 1546 // No need to feedback when repeat delete key will have no effect. 1547 return; 1548 } 1549 // TODO: Use event time that the last feedback has been generated instead of relying on 1550 // a repeat count to thin out feedback. 1551 if (repeatCount % PERIOD_FOR_AUDIO_AND_HAPTIC_FEEDBACK_IN_KEY_REPEAT == 0) { 1552 return; 1553 } 1554 } 1555 final AudioAndHapticFeedbackManager feedbackManager = 1556 AudioAndHapticFeedbackManager.getInstance(); 1557 if (repeatCount == 0) { 1558 // TODO: Reconsider how to perform haptic feedback when repeating key. 1559 feedbackManager.performHapticFeedback(keyboardView); 1560 } 1561 feedbackManager.performAudioFeedback(code); 1562 } 1563 1564 // Callback of the {@link KeyboardActionListener}. This is called when a key is depressed; 1565 // release matching call is {@link #onReleaseKey(int,boolean)} below. 1566 @Override 1567 public void onPressKey(final int primaryCode, final int repeatCount, 1568 final boolean isSinglePointer) { 1569 mKeyboardSwitcher.onPressKey(primaryCode, isSinglePointer, getCurrentAutoCapsState(), 1570 getCurrentRecapitalizeState()); 1571 hapticAndAudioFeedback(primaryCode, repeatCount); 1572 } 1573 1574 // Callback of the {@link KeyboardActionListener}. This is called when a key is released; 1575 // press matching call is {@link #onPressKey(int,int,boolean)} above. 1576 @Override 1577 public void onReleaseKey(final int primaryCode, final boolean withSliding) { 1578 mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding, getCurrentAutoCapsState(), 1579 getCurrentRecapitalizeState()); 1580 } 1581 1582 private HardwareEventDecoder getHardwareKeyEventDecoder(final int deviceId) { 1583 final HardwareEventDecoder decoder = mHardwareEventDecoders.get(deviceId); 1584 if (null != decoder) return decoder; 1585 // TODO: create the decoder according to the specification 1586 final HardwareEventDecoder newDecoder = new HardwareKeyboardEventDecoder(deviceId); 1587 mHardwareEventDecoders.put(deviceId, newDecoder); 1588 return newDecoder; 1589 } 1590 1591 // Hooks for hardware keyboard 1592 @Override 1593 public boolean onKeyDown(final int keyCode, final KeyEvent keyEvent) { 1594 mSpecialKeyDetector.onKeyDown(keyEvent); 1595 if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { 1596 return super.onKeyDown(keyCode, keyEvent); 1597 } 1598 final Event event = getHardwareKeyEventDecoder( 1599 keyEvent.getDeviceId()).decodeHardwareKey(keyEvent); 1600 // If the event is not handled by LatinIME, we just pass it to the parent implementation. 1601 // If it's handled, we return true because we did handle it. 1602 if (event.isHandled()) { 1603 mInputLogic.onCodeInput(mSettings.getCurrent(), event, 1604 mKeyboardSwitcher.getKeyboardShiftMode(), 1605 // TODO: this is not necessarily correct for a hardware keyboard right now 1606 mKeyboardSwitcher.getCurrentKeyboardScriptId(), 1607 mHandler); 1608 return true; 1609 } 1610 return super.onKeyDown(keyCode, keyEvent); 1611 } 1612 1613 @Override 1614 public boolean onKeyUp(final int keyCode, final KeyEvent keyEvent) { 1615 mSpecialKeyDetector.onKeyUp(keyEvent); 1616 if (!ProductionFlags.IS_HARDWARE_KEYBOARD_SUPPORTED) { 1617 return super.onKeyUp(keyCode, keyEvent); 1618 } 1619 final long keyIdentifier = keyEvent.getDeviceId() << 32 + keyEvent.getKeyCode(); 1620 if (mInputLogic.mCurrentlyPressedHardwareKeys.remove(keyIdentifier)) { 1621 return true; 1622 } 1623 return super.onKeyUp(keyCode, keyEvent); 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