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