SearchActivityView.java revision e833f84eee7ab575c8d53dec9b133fa5de9c7e6d
1/* 2 * Copyright (C) 2010 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.quicksearchbox.ui; 18 19import com.android.quicksearchbox.Corpora; 20import com.android.quicksearchbox.Corpus; 21import com.android.quicksearchbox.CorpusResult; 22import com.android.quicksearchbox.Logger; 23import com.android.quicksearchbox.Promoter; 24import com.android.quicksearchbox.QsbApplication; 25import com.android.quicksearchbox.R; 26import com.android.quicksearchbox.SearchActivity; 27import com.android.quicksearchbox.SuggestionCursor; 28import com.android.quicksearchbox.Suggestions; 29import com.android.quicksearchbox.VoiceSearch; 30import com.android.quicksearchbox.ui.SuggestionsAdapter.SuggestionsAdapterChangeListener; 31 32import android.app.Activity; 33import android.content.Context; 34import android.database.DataSetObserver; 35import android.graphics.drawable.Drawable; 36import android.text.Editable; 37import android.text.TextUtils; 38import android.text.TextWatcher; 39import android.util.AttributeSet; 40import android.util.Log; 41import android.view.KeyEvent; 42import android.view.View; 43import android.view.inputmethod.CompletionInfo; 44import android.view.inputmethod.InputMethodManager; 45import android.widget.AbsListView; 46import android.widget.ImageButton; 47import android.widget.RelativeLayout; 48 49import java.util.ArrayList; 50import java.util.Arrays; 51 52/** 53 * 54 */ 55public abstract class SearchActivityView extends RelativeLayout 56 implements SuggestionsAdapterChangeListener { 57 protected static final boolean DBG = false; 58 protected static final String TAG = "QSB.SearchActivityView"; 59 60 // The string used for privateImeOptions to identify to the IME that it should not show 61 // a microphone button since one already exists in the search dialog. 62 // TODO: This should move to android-common or something. 63 private static final String IME_OPTION_NO_MICROPHONE = "nm"; 64 65 private Corpus mCorpus; 66 67 protected QueryTextView mQueryTextView; 68 // True if the query was empty on the previous call to updateQuery() 69 protected boolean mQueryWasEmpty = true; 70 protected Drawable mQueryTextEmptyBg; 71 protected Drawable mQueryTextNotEmptyBg; 72 73 protected SuggestionsView mSuggestionsView; 74 75 protected SuggestionsAdapter mSuggestionsAdapter; 76 77 protected ImageButton mSearchCloseButton; 78 protected ImageButton mSearchGoButton; 79 protected ImageButton mVoiceSearchButton; 80 81 protected ButtonsKeyListener mButtonsKeyListener; 82 83 private boolean mUpdateSuggestions; 84 85 private QueryListener mQueryListener; 86 private SearchClickListener mSearchClickListener; 87 private View.OnClickListener mExitClickListener; 88 89 public SearchActivityView(Context context) { 90 super(context); 91 } 92 93 public SearchActivityView(Context context, AttributeSet attrs) { 94 super(context, attrs); 95 } 96 97 public SearchActivityView(Context context, AttributeSet attrs, int defStyle) { 98 super(context, attrs, defStyle); 99 } 100 101 @Override 102 protected void onFinishInflate() { 103 mQueryTextView = (QueryTextView) findViewById(R.id.search_src_text); 104 105 mSuggestionsView = (SuggestionsView) findViewById(R.id.suggestions); 106 mSuggestionsView.setOnScrollListener(new InputMethodCloser()); 107 mSuggestionsView.setOnKeyListener(new SuggestionsViewKeyListener()); 108 mSuggestionsView.setOnFocusChangeListener(new SuggestListFocusListener()); 109 110 mSuggestionsAdapter = createSuggestionsAdapter(); 111 mSuggestionsAdapter.setSuggestionAdapterChangeListener(this); 112 // TODO: why do we need focus listeners both on the SuggestionsView and the individual 113 // suggestions? 114 mSuggestionsAdapter.setOnFocusChangeListener(new SuggestListFocusListener()); 115 116 mSearchCloseButton = (ImageButton) findViewById(R.id.search_close_btn); 117 mSearchGoButton = (ImageButton) findViewById(R.id.search_go_btn); 118 mVoiceSearchButton = (ImageButton) findViewById(R.id.search_voice_btn); 119 120 mQueryTextView.addTextChangedListener(new SearchTextWatcher()); 121 mQueryTextView.setOnKeyListener(new QueryTextViewKeyListener()); 122 mQueryTextView.setOnFocusChangeListener(new QueryTextViewFocusListener()); 123 mQueryTextEmptyBg = mQueryTextView.getBackground(); 124 125 mSearchGoButton.setOnClickListener(new SearchGoButtonClickListener()); 126 127 mButtonsKeyListener = new ButtonsKeyListener(); 128 mSearchGoButton.setOnKeyListener(mButtonsKeyListener); 129 mVoiceSearchButton.setOnKeyListener(mButtonsKeyListener); 130 if (mSearchCloseButton != null) { 131 mSearchCloseButton.setOnKeyListener(mButtonsKeyListener); 132 mSearchCloseButton.setOnClickListener(new CloseClickListener()); 133 } 134 135 mUpdateSuggestions = true; 136 } 137 138 public void onSuggestionAdapterChanged() { 139 mSuggestionsView.setAdapter(mSuggestionsAdapter); 140 } 141 142 public abstract void onResume(); 143 144 public abstract void onStop(); 145 146 public void start() { 147 mSuggestionsAdapter.registerDataSetObserver(new SuggestionsObserver()); 148 mSuggestionsView.setAdapter(mSuggestionsAdapter); 149 } 150 151 public void destroy() { 152 mSuggestionsAdapter.setSuggestionAdapterChangeListener(null); 153 mSuggestionsView.setAdapter(null); // closes mSuggestionsAdapter 154 } 155 156 // TODO: Get rid of this. To make it more easily testable, 157 // the SearchActivityView should not depend on QsbApplication. 158 protected QsbApplication getQsbApplication() { 159 return QsbApplication.get(getContext()); 160 } 161 162 private VoiceSearch getVoiceSearch() { 163 return getQsbApplication().getVoiceSearch(); 164 } 165 166 protected SuggestionsAdapter createSuggestionsAdapter() { 167 return new DelayingSuggestionsAdapter(getQsbApplication().getDefaultSuggestionViewFactory(), 168 getQsbApplication().getCorpora()); 169 } 170 171 172 protected Corpora getCorpora() { 173 return getQsbApplication().getCorpora(); 174 } 175 176 public Corpus getCorpus() { 177 return mCorpus; 178 } 179 180 protected abstract Promoter createSuggestionsPromoter(); 181 182 protected Corpus getCorpus(String sourceName) { 183 if (sourceName == null) return null; 184 Corpus corpus = getCorpora().getCorpus(sourceName); 185 if (corpus == null) { 186 Log.w(TAG, "Unknown corpus " + sourceName); 187 return null; 188 } 189 return corpus; 190 } 191 192 public void onCorpusSelected(String corpusName) { 193 setCorpus(corpusName); 194 focusQueryTextView(); 195 showInputMethodForQuery(); 196 } 197 198 public void setCorpus(String corpusName) { 199 if (DBG) Log.d(TAG, "setCorpus(" + corpusName + ")"); 200 Corpus corpus = getCorpus(corpusName); 201 setCorpus(corpus); 202 updateUi(); 203 } 204 205 protected void setCorpus(Corpus corpus) { 206 mCorpus = corpus; 207 mSuggestionsAdapter.setPromoter(createSuggestionsPromoter()); 208 Suggestions suggestions = getSuggestions(); 209 if (corpus == null || suggestions == null || !suggestions.expectsCorpus(corpus)) { 210 getActivity().updateSuggestions(); 211 } 212 } 213 214 public String getCorpusName() { 215 Corpus corpus = getCorpus(); 216 return corpus == null ? null : corpus.getName(); 217 } 218 219 public abstract Corpus getSearchCorpus(); 220 221 public Corpus getWebCorpus() { 222 Corpus webCorpus = getCorpora().getWebCorpus(); 223 if (webCorpus == null) { 224 Log.e(TAG, "No web corpus"); 225 } 226 return webCorpus; 227 } 228 229 public void setMaxPromotedSuggestions(int maxPromoted) { 230 mSuggestionsView.setLimitSuggestionsToViewHeight(false); 231 mSuggestionsAdapter.setMaxPromoted(maxPromoted); 232 } 233 234 public void limitSuggestionsToViewHeight() { 235 mSuggestionsView.setLimitSuggestionsToViewHeight(true); 236 } 237 238 public void setMaxPromotedResults(int maxPromoted) { 239 } 240 241 public void limitResultsToViewHeight() { 242 } 243 244 public void setQueryListener(QueryListener listener) { 245 mQueryListener = listener; 246 } 247 248 public void setSearchClickListener(SearchClickListener listener) { 249 mSearchClickListener = listener; 250 } 251 252 public abstract void showCorpusSelectionDialog(); 253 254 public abstract void setSettingsButtonClickListener(View.OnClickListener listener); 255 256 public void setVoiceSearchButtonClickListener(View.OnClickListener listener) { 257 if (mVoiceSearchButton != null) { 258 mVoiceSearchButton.setOnClickListener(listener); 259 } 260 } 261 262 public void setSuggestionClickListener(final SuggestionClickListener listener) { 263 mSuggestionsAdapter.setSuggestionClickListener(listener); 264 mQueryTextView.setCommitCompletionListener(new QueryTextView.CommitCompletionListener() { 265 @Override 266 public void onCommitCompletion(int position) { 267 mSuggestionsAdapter.onSuggestionClicked(position); 268 } 269 }); 270 } 271 272 public void setExitClickListener(final View.OnClickListener listener) { 273 mExitClickListener = listener; 274 } 275 276 public void setEmptySpaceClickListener(final View.OnClickListener listener) { 277 } 278 279 protected SuggestionsAdapter getSuggestionsAdapter() { 280 return mSuggestionsAdapter; 281 } 282 283 public Suggestions getSuggestions() { 284 return mSuggestionsAdapter.getSuggestions(); 285 } 286 287 public SuggestionCursor getCurrentSuggestions() { 288 return mSuggestionsAdapter.getCurrentSuggestions(); 289 } 290 291 public void setSuggestions(Suggestions suggestions) { 292 suggestions.acquire(); 293 mSuggestionsAdapter.setSuggestions(suggestions); 294 } 295 296 public void clearSuggestions() { 297 mSuggestionsAdapter.setSuggestions(null); 298 } 299 300 public String getQuery() { 301 CharSequence q = mQueryTextView.getText(); 302 return q == null ? "" : q.toString(); 303 } 304 305 /** 306 * Sets the text in the query box. Does not update the suggestions. 307 */ 308 public void setQuery(String query, boolean selectAll) { 309 mUpdateSuggestions = false; 310 mQueryTextView.setText(query); 311 mQueryTextView.setTextSelection(selectAll); 312 mUpdateSuggestions = true; 313 } 314 315 protected SearchActivity getActivity() { 316 Context context = getContext(); 317 if (context instanceof SearchActivity) { 318 return (SearchActivity) context; 319 } else { 320 return null; 321 } 322 } 323 324 public void hideSuggestions() { 325 mSuggestionsView.setVisibility(GONE); 326 } 327 328 public void showSuggestions() { 329 mSuggestionsView.setVisibility(VISIBLE); 330 } 331 332 public void focusQueryTextView() { 333 mQueryTextView.requestFocus(); 334 } 335 336 protected void updateUi() { 337 updateUi(getQuery().length() == 0); 338 } 339 340 protected void updateUi(boolean queryEmpty) { 341 updateQueryTextView(queryEmpty); 342 updateSearchGoButton(queryEmpty); 343 updateVoiceSearchButton(queryEmpty); 344 } 345 346 private void updateQueryTextView(boolean queryEmpty) { 347 if (queryEmpty) { 348 if (isSearchCorpusWeb()) { 349 mQueryTextView.setBackgroundDrawable(mQueryTextEmptyBg); 350 mQueryTextView.setHint(null); 351 } else { 352 if (mQueryTextNotEmptyBg == null) { 353 mQueryTextNotEmptyBg = 354 getResources().getDrawable(R.drawable.textfield_search_empty); 355 } 356 mQueryTextView.setBackgroundDrawable(mQueryTextNotEmptyBg); 357 Corpus corpus = getCorpus(); 358 mQueryTextView.setHint(corpus == null ? "" : corpus.getHint()); 359 } 360 } else { 361 mQueryTextView.setBackgroundResource(R.drawable.textfield_search); 362 } 363 } 364 365 private void updateSearchGoButton(boolean queryEmpty) { 366 if (queryEmpty) { 367 mSearchGoButton.setVisibility(View.GONE); 368 } else { 369 mSearchGoButton.setVisibility(View.VISIBLE); 370 } 371 } 372 373 protected void updateVoiceSearchButton(boolean queryEmpty) { 374 if (shouldShowVoiceSearch(queryEmpty) 375 && getVoiceSearch().shouldShowVoiceSearch(getCorpus())) { 376 mVoiceSearchButton.setVisibility(View.VISIBLE); 377 mQueryTextView.setPrivateImeOptions(IME_OPTION_NO_MICROPHONE); 378 } else { 379 mVoiceSearchButton.setVisibility(View.GONE); 380 mQueryTextView.setPrivateImeOptions(null); 381 } 382 } 383 384 protected boolean shouldShowVoiceSearch(boolean queryEmpty) { 385 return queryEmpty; 386 } 387 388 /** 389 * Hides the input method. 390 */ 391 protected void hideInputMethod() { 392 InputMethodManager imm = (InputMethodManager) 393 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 394 if (imm != null) { 395 imm.hideSoftInputFromWindow(getWindowToken(), 0); 396 } 397 } 398 399 public abstract void considerHidingInputMethod(); 400 401 public void showInputMethodForQuery() { 402 mQueryTextView.showInputMethod(); 403 } 404 405 /** 406 * Overrides the handling of the back key to dismiss the activity. 407 */ 408 @Override 409 public boolean dispatchKeyEventPreIme(KeyEvent event) { 410 Activity activity = getActivity(); 411 if (activity != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK) { 412 KeyEvent.DispatcherState state = getKeyDispatcherState(); 413 if (state != null) { 414 if (event.getAction() == KeyEvent.ACTION_DOWN 415 && event.getRepeatCount() == 0) { 416 state.startTracking(event, this); 417 return true; 418 } else if (event.getAction() == KeyEvent.ACTION_UP 419 && !event.isCanceled() && state.isTracking(event)) { 420 hideInputMethod(); 421 activity.onBackPressed(); 422 return true; 423 } 424 } 425 } 426 return super.dispatchKeyEventPreIme(event); 427 } 428 429 /** 430 * If the input method is in fullscreen mode, and the selector corpus 431 * is All or Web, use the web search suggestions as completions. 432 */ 433 protected void updateInputMethodSuggestions() { 434 InputMethodManager imm = (InputMethodManager) 435 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 436 if (imm == null || !imm.isFullscreenMode()) return; 437 Suggestions suggestions = mSuggestionsAdapter.getSuggestions(); 438 if (suggestions == null) return; 439 CompletionInfo[] completions = webSuggestionsToCompletions(suggestions); 440 if (DBG) Log.d(TAG, "displayCompletions(" + Arrays.toString(completions) + ")"); 441 imm.displayCompletions(mQueryTextView, completions); 442 } 443 444 private CompletionInfo[] webSuggestionsToCompletions(Suggestions suggestions) { 445 // TODO: This should also include include web search shortcuts 446 CorpusResult cursor = suggestions.getWebResult(); 447 if (cursor == null) return null; 448 int count = cursor.getCount(); 449 ArrayList<CompletionInfo> completions = new ArrayList<CompletionInfo>(count); 450 boolean usingWebCorpus = isSearchCorpusWeb(); 451 for (int i = 0; i < count; i++) { 452 cursor.moveTo(i); 453 if (!usingWebCorpus || cursor.isWebSearchSuggestion()) { 454 String text1 = cursor.getSuggestionText1(); 455 completions.add(new CompletionInfo(i, i, text1)); 456 } 457 } 458 return completions.toArray(new CompletionInfo[completions.size()]); 459 } 460 461 protected void onSuggestionsChanged() { 462 updateInputMethodSuggestions(); 463 } 464 465 /** 466 * Checks if the corpus used for typed searches is the web corpus. 467 */ 468 protected boolean isSearchCorpusWeb() { 469 Corpus corpus = getSearchCorpus(); 470 return corpus != null && corpus.isWebCorpus(); 471 } 472 473 protected boolean onSuggestionKeyDown(SuggestionsAdapter adapter, 474 int position, int keyCode, KeyEvent event) { 475 // Treat enter or search as a click 476 if ( keyCode == KeyEvent.KEYCODE_ENTER 477 || keyCode == KeyEvent.KEYCODE_SEARCH 478 || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 479 if (adapter != null) { 480 SuggestionsAdapter suggestionsAdapter = adapter; 481 suggestionsAdapter.onSuggestionClicked(position); 482 return true; 483 } else { 484 return false; 485 } 486 } 487 488 return false; 489 } 490 491 protected boolean onSearchClicked(int method) { 492 if (mSearchClickListener != null) { 493 return mSearchClickListener.onSearchClicked(method); 494 } 495 return false; 496 } 497 498 /** 499 * Filters the suggestions list when the search text changes. 500 */ 501 private class SearchTextWatcher implements TextWatcher { 502 public void afterTextChanged(Editable s) { 503 boolean empty = s.length() == 0; 504 if (empty != mQueryWasEmpty) { 505 mQueryWasEmpty = empty; 506 updateUi(empty); 507 } 508 if (mUpdateSuggestions) { 509 if (mQueryListener != null) { 510 mQueryListener.onQueryChanged(); 511 } 512 } 513 } 514 515 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 516 } 517 518 public void onTextChanged(CharSequence s, int start, int before, int count) { 519 } 520 } 521 522 /** 523 * Handles key events on the suggestions list view. 524 */ 525 protected class SuggestionsViewKeyListener implements View.OnKeyListener { 526 public boolean onKey(View v, int keyCode, KeyEvent event) { 527 if (event.getAction() == KeyEvent.ACTION_DOWN 528 && v instanceof SuggestionsView) { 529 SuggestionsView view = ((SuggestionsView) v); 530 int position = view.getSelectedPosition(); 531 if (onSuggestionKeyDown(view.getAdapter(), position, keyCode, event)) { 532 return true; 533 } 534 } 535 return forwardKeyToQueryTextView(keyCode, event); 536 } 537 } 538 539 private class InputMethodCloser implements SuggestionsView.OnScrollListener { 540 541 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, 542 int totalItemCount) { 543 } 544 545 public void onScrollStateChanged(AbsListView view, int scrollState) { 546 considerHidingInputMethod(); 547 } 548 } 549 550 /** 551 * Listens for clicks on the source selector. 552 */ 553 private class SearchGoButtonClickListener implements View.OnClickListener { 554 public void onClick(View view) { 555 onSearchClicked(Logger.SEARCH_METHOD_BUTTON); 556 } 557 } 558 559 /** 560 * Handles non-text keys in the query text view. 561 */ 562 private class QueryTextViewKeyListener implements View.OnKeyListener { 563 public boolean onKey(View view, int keyCode, KeyEvent event) { 564 // Handle IME search action key 565 if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) { 566 // if no action was taken, consume the key event so that the keyboard 567 // remains on screen. 568 return !onSearchClicked(Logger.SEARCH_METHOD_KEYBOARD); 569 } 570 return false; 571 } 572 } 573 574 /** 575 * Handles key events on the search and voice search buttons, 576 * by refocusing to EditText. 577 */ 578 private class ButtonsKeyListener implements View.OnKeyListener { 579 public boolean onKey(View v, int keyCode, KeyEvent event) { 580 return forwardKeyToQueryTextView(keyCode, event); 581 } 582 } 583 584 private boolean forwardKeyToQueryTextView(int keyCode, KeyEvent event) { 585 if (!event.isSystem() && !isDpadKey(keyCode)) { 586 if (DBG) Log.d(TAG, "Forwarding key to query box: " + event); 587 if (mQueryTextView.requestFocus()) { 588 return mQueryTextView.dispatchKeyEvent(event); 589 } 590 } 591 return false; 592 } 593 594 private boolean isDpadKey(int keyCode) { 595 switch (keyCode) { 596 case KeyEvent.KEYCODE_DPAD_UP: 597 case KeyEvent.KEYCODE_DPAD_DOWN: 598 case KeyEvent.KEYCODE_DPAD_LEFT: 599 case KeyEvent.KEYCODE_DPAD_RIGHT: 600 case KeyEvent.KEYCODE_DPAD_CENTER: 601 return true; 602 default: 603 return false; 604 } 605 } 606 607 /** 608 * Hides the input method when the suggestions get focus. 609 */ 610 private class SuggestListFocusListener implements OnFocusChangeListener { 611 public void onFocusChange(View v, boolean focused) { 612 if (DBG) Log.d(TAG, "Suggestions focus change, now: " + focused); 613 if (focused) { 614 considerHidingInputMethod(); 615 } 616 } 617 } 618 619 private class QueryTextViewFocusListener implements OnFocusChangeListener { 620 public void onFocusChange(View v, boolean focused) { 621 if (DBG) Log.d(TAG, "Query focus change, now: " + focused); 622 if (focused) { 623 // The query box got focus, show the input method 624 showInputMethodForQuery(); 625 } 626 } 627 } 628 629 private class SuggestionsObserver extends DataSetObserver { 630 @Override 631 public void onChanged() { 632 onSuggestionsChanged(); 633 } 634 } 635 636 public interface QueryListener { 637 void onQueryChanged(); 638 } 639 640 public interface SearchClickListener { 641 boolean onSearchClicked(int method); 642 } 643 644 private class CloseClickListener implements OnClickListener { 645 646 public void onClick(View v) { 647 if (!TextUtils.isEmpty(mQueryTextView.getText())) { 648 mQueryTextView.setText(""); 649 } else { 650 mExitClickListener.onClick(v); 651 } 652 } 653 } 654} 655