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