OSDN Git Service

Eleven: Cleanup all the whitespace
[android-x86/packages-apps-Eleven.git] / src / com / cyanogenmod / eleven / ui / activities / SearchActivity.java
1 /*
2  * Copyright (C) 2012 Andrew Neal
3  * Copyright (C) 2014 The CyanogenMod Project
4  * Licensed under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with the
6  * License. You may obtain a copy of the License at
7  * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
8  * or agreed to in writing, software distributed under the License is
9  * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10  * KIND, either express or implied. See the License for the specific language
11  * governing permissions and limitations under the License.
12  */
13
14 package com.cyanogenmod.eleven.ui.activities;
15
16 import android.app.ActionBar;
17 import android.app.SearchManager;
18 import android.content.ComponentName;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.content.ServiceConnection;
22 import android.database.Cursor;
23 import android.media.AudioManager;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.os.IBinder;
27 import android.provider.BaseColumns;
28 import android.provider.MediaStore;
29 import android.support.v4.app.FragmentActivity;
30 import android.support.v4.app.LoaderManager.LoaderCallbacks;
31 import android.support.v4.content.Loader;
32 import android.text.TextUtils;
33 import android.view.Menu;
34 import android.view.MenuItem;
35 import android.view.MotionEvent;
36 import android.view.View;
37 import android.view.inputmethod.InputMethodManager;
38 import android.widget.AbsListView;
39 import android.widget.AbsListView.OnScrollListener;
40 import android.widget.AdapterView;
41 import android.widget.AdapterView.OnItemClickListener;
42 import android.widget.ArrayAdapter;
43 import android.widget.ImageView;
44 import android.widget.LinearLayout;
45 import android.widget.ListView;
46 import android.widget.SearchView;
47 import android.widget.SearchView.OnQueryTextListener;
48
49 import com.cyanogenmod.eleven.Config;
50 import com.cyanogenmod.eleven.IElevenService;
51 import com.cyanogenmod.eleven.R;
52 import com.cyanogenmod.eleven.adapters.SummarySearchAdapter;
53 import com.cyanogenmod.eleven.loaders.WrappedAsyncTaskLoader;
54 import com.cyanogenmod.eleven.menu.FragmentMenuItems;
55 import com.cyanogenmod.eleven.model.AlbumArtistDetails;
56 import com.cyanogenmod.eleven.model.SearchResult;
57 import com.cyanogenmod.eleven.model.SearchResult.ResultType;
58 import com.cyanogenmod.eleven.provider.SearchHistory;
59 import com.cyanogenmod.eleven.recycler.RecycleHolder;
60 import com.cyanogenmod.eleven.sectionadapter.SectionAdapter;
61 import com.cyanogenmod.eleven.sectionadapter.SectionCreator;
62 import com.cyanogenmod.eleven.sectionadapter.SectionCreator.SimpleListLoader;
63 import com.cyanogenmod.eleven.sectionadapter.SectionListContainer;
64 import com.cyanogenmod.eleven.utils.ApolloUtils;
65 import com.cyanogenmod.eleven.utils.MusicUtils;
66 import com.cyanogenmod.eleven.utils.MusicUtils.ServiceToken;
67 import com.cyanogenmod.eleven.utils.NavUtils;
68 import com.cyanogenmod.eleven.utils.PopupMenuHelper;
69 import com.cyanogenmod.eleven.utils.SectionCreatorUtils;
70 import com.cyanogenmod.eleven.utils.SectionCreatorUtils.IItemCompare;
71 import com.cyanogenmod.eleven.widgets.IPopupMenuCallback;
72 import com.cyanogenmod.eleven.widgets.LoadingEmptyContainer;
73 import com.cyanogenmod.eleven.widgets.NoResultsContainer;
74
75 import java.util.ArrayList;
76 import java.util.Collections;
77 import java.util.List;
78 import java.util.TreeSet;
79
80 import static android.view.View.OnTouchListener;
81 import static com.cyanogenmod.eleven.utils.MusicUtils.mService;
82
83 /**
84  * Provides the search interface for Apollo.
85  *
86  * @author Andrew Neal (andrewdneal@gmail.com)
87  */
88 public class SearchActivity extends FragmentActivity implements
89         LoaderCallbacks<SectionListContainer<SearchResult>>,
90         OnScrollListener, OnQueryTextListener, OnItemClickListener, ServiceConnection,
91         OnTouchListener {
92     /**
93      * Loading delay of 500ms so we don't flash the screen too much when loading new searches
94      */
95     private static int LOADING_DELAY = 500;
96
97     /**
98      * Identifier for the search loader
99      */
100     private static int SEARCH_LOADER = 0;
101
102     /**
103      * Identifier for the search history loader
104      */
105     private static int HISTORY_LOADER = 1;
106
107     /**
108      * The service token
109      */
110     private ServiceToken mToken;
111
112     /**
113      * The query
114      */
115     private String mFilterString;
116
117     /**
118      * List view
119      */
120     private ListView mListView;
121
122     /**
123      * Used the filter the user's music
124      */
125     private SearchView mSearchView;
126
127     /**
128      * IME manager
129      */
130     private InputMethodManager mImm;
131
132     /**
133      * The view that container the no search results text and the loading progress bar
134      */
135     private LoadingEmptyContainer mLoadingEmptyContainer;
136
137     /**
138      * List view adapter
139      */
140     private SectionAdapter<SearchResult, SummarySearchAdapter> mAdapter;
141
142     /**
143      * boolean tracking whether this is the search level when the user first enters search
144      * or if the user has clicked show all
145      */
146     private boolean mTopLevelSearch;
147
148     /**
149      * If the user has clicked show all, this tells us what type (Artist, Album, etc)
150      */
151     private ResultType mSearchType;
152
153     /**
154      * Search History loader callback
155      */
156     private SearchHistoryCallback mSearchHistoryCallback;
157
158     /**
159      * List view
160      */
161     private ListView mSearchHistoryListView;
162
163     /**
164      * This tracks our current visible state between the different views
165       */
166     enum VisibleState {
167         SearchHistory,
168         Empty,
169         SearchResults,
170         Loading,
171     }
172
173     private VisibleState mCurrentState;
174
175     /**
176      * Handler for posting runnables
177      */
178     private Handler mHandler;
179
180     /**
181      * A runnable to show the loading view that will be posted with a delay to prevent flashing
182      */
183     private Runnable mLoadingRunnable;
184
185     /**
186      * Flag used to track if we are quitting so we don't flash loaders while finishing the activity
187      */
188     private boolean mQuitting = false;
189
190     /**
191      * Pop up menu helper
192      */
193     private PopupMenuHelper mPopupMenuHelper;
194
195     /**
196      * {@inheritDoc}
197      */
198     @Override
199     public void onCreate(final Bundle savedInstanceState) {
200         super.onCreate(savedInstanceState);
201
202         mPopupMenuHelper = new PopupMenuHelper(this, getSupportFragmentManager()) {
203             private SearchResult mSelectedItem;
204
205             @Override
206             public PopupMenuType onPreparePopupMenu(int position) {
207                 mSelectedItem = mAdapter.getTItem(position);
208
209                 return PopupMenuType.SearchResult;
210             }
211
212             @Override
213             protected long[] getIdList() {
214                 switch (mSelectedItem.mType) {
215                     case Artist:
216                         return MusicUtils.getSongListForArtist(SearchActivity.this,
217                                 mSelectedItem.mId);
218                     case Album:
219                         return MusicUtils.getSongListForAlbum(SearchActivity.this,
220                                 mSelectedItem.mId);
221                     case Song:
222                         return new long[] { mSelectedItem.mId };
223                     case Playlist:
224                         return MusicUtils.getSongListForPlaylist(SearchActivity.this,
225                                 mSelectedItem.mId);
226                     default:
227                         return null;
228                 }
229             }
230
231             @Override
232             protected long getSourceId() {
233                 return mSelectedItem.mId;
234             }
235
236             @Override
237             protected Config.IdType getSourceType() {
238                 return mSelectedItem.mType.getSourceType();
239             }
240
241             @Override
242             protected void updateMenuIds(PopupMenuType type, TreeSet<Integer> set) {
243                 super.updateMenuIds(type, set);
244
245                 if (mSelectedItem.mType == ResultType.Album) {
246                     set.add(FragmentMenuItems.MORE_BY_ARTIST);
247                 }
248             }
249
250             @Override
251             protected String getArtistName() {
252                 return mSelectedItem.mArtist;
253             }
254         };
255
256         // Fade it in
257         overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
258
259         // Control the media volume
260         setVolumeControlStream(AudioManager.STREAM_MUSIC);
261
262         // Bind Apollo's service
263         mToken = MusicUtils.bindToService(this, this);
264
265         // Set the layout
266         setContentView(R.layout.activity_search);
267
268         // get the input method manager
269         mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
270
271         // Initialize the adapter
272         SummarySearchAdapter adapter = new SummarySearchAdapter(this);
273         mAdapter = new SectionAdapter<SearchResult, SummarySearchAdapter>(this, adapter);
274         // Set the prefix
275         mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);
276         mAdapter.setupHeaderParameters(R.layout.list_search_header, false);
277         mAdapter.setupFooterParameters(R.layout.list_search_footer, true);
278         mAdapter.setPopupMenuClickedListener(new IPopupMenuCallback.IListener() {
279             @Override
280             public void onPopupMenuClicked(View v, int position) {
281                 mPopupMenuHelper.showPopupMenu(v, position);
282             }
283         });
284
285         mLoadingEmptyContainer = (LoadingEmptyContainer) findViewById(R.id.loading_empty_container);
286         // setup the no results container
287         NoResultsContainer noResults = mLoadingEmptyContainer.getNoResultsContainer();
288         noResults.setMainText(R.string.empty_search);
289         noResults.setSecondaryText(R.string.empty_search_check);
290
291         initListView();
292
293         // setup handler and runnable
294         mHandler = new Handler();
295         mLoadingRunnable = new Runnable() {
296             @Override
297             public void run() {
298                 setState(VisibleState.Loading);
299             }
300         };
301
302         // Theme the action bar
303         final ActionBar actionBar = getActionBar();
304         actionBar.setDisplayHomeAsUpEnabled(true);
305
306         // Get the query String
307         mFilterString = getIntent().getStringExtra(SearchManager.QUERY);
308
309         // if we have a non-empty search string, this is a 2nd lvl search
310         if (!TextUtils.isEmpty(mFilterString)) {
311             mTopLevelSearch = false;
312
313             // get the search type to filter by
314             int type = getIntent().getIntExtra(SearchManager.SEARCH_MODE, -1);
315             if (type >= 0 && type < ResultType.values().length) {
316                 mSearchType = ResultType.values()[type];
317             }
318
319             int resourceId = 0;
320             switch (mSearchType) {
321                 case Artist:
322                     resourceId = R.string.search_title_artists;
323                     break;
324                 case Album:
325                     resourceId = R.string.search_title_albums;
326                     break;
327                 case Playlist:
328                     resourceId = R.string.search_title_playlists;
329                     break;
330                 case Song:
331                     resourceId = R.string.search_title_songs;
332                     break;
333             }
334             actionBar.setTitle(getString(resourceId, mFilterString).toUpperCase());
335             actionBar.setDisplayHomeAsUpEnabled(true);
336
337             // Set the prefix
338             mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);
339
340             // Start the loader for the query
341             getSupportLoaderManager().initLoader(SEARCH_LOADER, null, this);
342         } else {
343             mTopLevelSearch = true;
344             mSearchHistoryCallback = new SearchHistoryCallback();
345
346             // Start the loader for the search history
347             getSupportLoaderManager().initLoader(HISTORY_LOADER, null, mSearchHistoryCallback);
348         }
349     }
350
351     /**
352      * Sets up the list view
353      */
354     private void initListView() {
355         // Initialize the grid
356         mListView = (ListView)findViewById(R.id.list_base);
357         // Set the data behind the list
358         mListView.setAdapter(mAdapter);
359         // Release any references to the recycled Views
360         mListView.setRecyclerListener(new RecycleHolder());
361         // Show the albums and songs from the selected artist
362         mListView.setOnItemClickListener(this);
363         // To help make scrolling smooth
364         mListView.setOnScrollListener(this);
365         // sets the touch listener
366         mListView.setOnTouchListener(this);
367         // If we setEmptyView with mLoadingEmptyContainer it causes a crash in DragSortListView
368         // when updating the search.  For now let's manually toggle visibility and come back
369         // to this later
370         //mListView.setEmptyView(mLoadingEmptyContainer);
371
372         // load the search history list view
373         mSearchHistoryListView = (ListView)findViewById(R.id.list_search_history);
374         mSearchHistoryListView.setOnItemClickListener(new OnItemClickListener() {
375             @Override
376             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
377                 String searchItem = (String)mSearchHistoryListView.getAdapter().getItem(position);
378                 mSearchView.setQuery(searchItem, true);
379             }
380         });
381         mSearchHistoryListView.setOnTouchListener(this);
382     }
383
384     /**
385      * {@inheritDoc}
386      */
387     @Override
388     public Loader<SectionListContainer<SearchResult>> onCreateLoader(final int id,
389                                                                      final Bundle args) {
390         IItemCompare<SearchResult> comparator = null;
391
392         // prep the loader in case the query takes a long time
393         setLoading();
394
395         // if we are at the top level, create a comparator to separate the different types into
396         // their own sections (artists, albums, etc)
397         if (mTopLevelSearch) {
398             comparator = SectionCreatorUtils.createSearchResultComparison(this);
399         }
400
401         return new SectionCreator<SearchResult>(this,
402                 new SummarySearchLoader(this, mFilterString, mSearchType),
403                 comparator);
404     }
405
406     /**
407      * {@inheritDoc}
408      */
409     @Override
410     public boolean onCreateOptionsMenu(final Menu menu) {
411         // if we are not a top level search view, we do not need to create the search fields
412         if (!mTopLevelSearch) {
413             return super.onCreateOptionsMenu(menu);
414         }
415
416         // Search view
417         getMenuInflater().inflate(R.menu.search, menu);
418
419         // Filter the list the user is looking it via SearchView
420         MenuItem searchItem = menu.findItem(R.id.menu_search);
421         mSearchView = (SearchView)searchItem.getActionView();
422         mSearchView.setOnQueryTextListener(this);
423         mSearchView.setQueryHint(getString(R.string.searchHint).toUpperCase());
424
425         // The SearchView has no way for you to customize or get access to the search icon in a
426         // normal fashion, so we need to manually look for the icon and change the
427         // layout params to hide it
428         mSearchView.setIconifiedByDefault(false);
429         mSearchView.setIconified(false);
430         int searchButtonId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
431         ImageView searchIcon = (ImageView)mSearchView.findViewById(searchButtonId);
432         searchIcon.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
433
434         searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
435             @Override
436             public boolean onMenuItemActionExpand(MenuItem item) {
437                 return true;
438             }
439
440             @Override
441             public boolean onMenuItemActionCollapse(MenuItem item) {
442                 quit();
443                 return false;
444             }
445         });
446
447         menu.findItem(R.id.menu_search).expandActionView();
448
449         return super.onCreateOptionsMenu(menu);
450     }
451
452     private void quit() {
453         mQuitting = true;
454         finish();
455     }
456
457     /**
458      * {@inheritDoc}
459      */
460     @Override
461     protected void onDestroy() {
462         super.onDestroy();
463         // Unbind from the service
464         if (mService != null) {
465             MusicUtils.unbindFromService(mToken);
466             mToken = null;
467         }
468     }
469
470     /**
471      * {@inheritDoc}
472      */
473     @Override
474     public boolean onOptionsItemSelected(final MenuItem item) {
475         switch (item.getItemId()) {
476             case android.R.id.home:
477                 quit();
478                 return true;
479             default:
480                 break;
481         }
482         return super.onOptionsItemSelected(item);
483     }
484
485     /**
486      * {@inheritDoc}
487      */
488     @Override
489     public void onLoadFinished(final Loader<SectionListContainer<SearchResult>> loader,
490                                final SectionListContainer<SearchResult> data) {
491         // Check for any errors
492         if (data.mListResults.isEmpty()) {
493             // clear the adapter
494             mAdapter.clear();
495             // show the empty state
496             setState(VisibleState.Empty);
497         } else {
498             // Set the data
499             mAdapter.setData(data);
500             // show the search results
501             setState(VisibleState.SearchResults);
502         }
503     }
504
505     /**
506      * {@inheritDoc}
507      */
508     @Override
509     public void onLoaderReset(final Loader<SectionListContainer<SearchResult>> loader) {
510         mAdapter.unload();
511     }
512
513     /**
514      * {@inheritDoc}
515      */
516     @Override
517     public void onScrollStateChanged(final AbsListView view, final int scrollState) {
518         // Pause disk cache access to ensure smoother scrolling
519         if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
520             mAdapter.getUnderlyingAdapter().setPauseDiskCache(true);
521         } else {
522             mAdapter.getUnderlyingAdapter().setPauseDiskCache(false);
523             mAdapter.notifyDataSetChanged();
524         }
525     }
526
527     /**
528      * {@inheritDoc}
529      */
530     @Override
531     public boolean onQueryTextSubmit(final String query) {
532         // simulate an on query text change
533         onQueryTextChange(query);
534         // hide the input manager
535         hideInputManager();
536
537         return true;
538     }
539
540     public void hideInputManager() {
541         // When the search is "committed" by the user, then hide the keyboard so
542         // the user can more easily browse the list of results.
543         if (mSearchView != null) {
544             if (mImm != null) {
545                 mImm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
546             }
547             mSearchView.clearFocus();
548
549             // add our search string
550             SearchHistory.getInstance(this).addSearchString(mFilterString);
551         }
552     }
553
554     /**
555      * This posts a delayed for showing the loading screen.  The reason for the delayed is we
556      * don't want to flash the loading icon very often since searches usually are pretty fast
557      */
558     public void setLoading() {
559         if (mCurrentState != VisibleState.Loading) {
560             if (!mHandler.hasCallbacks(mLoadingRunnable)) {
561                 mHandler.postDelayed(mLoadingRunnable, LOADING_DELAY);
562             }
563         }
564     }
565
566     /**
567      * Sets the currently visible view
568      * @param state the current visible state
569      */
570     public void setState(VisibleState state) {
571         // remove any delayed runnables.  This has to be before mCurrentState == state
572         // in case the state doesn't change but we've created a loading runnable
573         mHandler.removeCallbacks(mLoadingRunnable);
574
575         // if we are already looking at view already, just quit
576         if (mCurrentState == state) {
577             return;
578         }
579
580         mCurrentState = state;
581
582         mSearchHistoryListView.setVisibility(View.INVISIBLE);
583         mListView.setVisibility(View.INVISIBLE);
584         mLoadingEmptyContainer.setVisibility(View.INVISIBLE);
585
586         switch (mCurrentState) {
587             case SearchHistory:
588                 mSearchHistoryListView.setVisibility(View.VISIBLE);
589                 break;
590             case SearchResults:
591                 mListView.setVisibility(View.VISIBLE);
592                 break;
593             case Empty:
594                 mLoadingEmptyContainer.setVisibility(View.VISIBLE);
595                 mLoadingEmptyContainer.showNoResults();
596                 break;
597             case Loading:
598                 mLoadingEmptyContainer.setVisibility(View.VISIBLE);
599                 mLoadingEmptyContainer.showLoading();
600                 break;
601         }
602     }
603
604     /**
605      * {@inheritDoc}
606      */
607     @Override
608     public boolean onQueryTextChange(final String newText) {
609         if (mQuitting) {
610             return true;
611         }
612
613         if (TextUtils.isEmpty(newText)) {
614             if (!TextUtils.isEmpty(mFilterString)) {
615                 mFilterString = "";
616                 getSupportLoaderManager().restartLoader(HISTORY_LOADER, null,
617                         mSearchHistoryCallback);
618                 getSupportLoaderManager().destroyLoader(SEARCH_LOADER);
619             }
620
621             return true;
622         }
623
624         // if the strings are the same, return
625         if (newText.equals(mFilterString)) {
626             return true;
627         }
628
629         // Called when the action bar search text has changed. Update
630         // the search filter, and restart the loader to do a new query
631         // with this filter.
632         mFilterString = newText;
633         // Set the prefix
634         mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);
635         getSupportLoaderManager().restartLoader(SEARCH_LOADER, null, this);
636         getSupportLoaderManager().destroyLoader(HISTORY_LOADER);
637         return true;
638     }
639
640     /**
641      * {@inheritDoc}
642      */
643     @Override
644     public void onItemClick(final AdapterView<?> parent, final View view, final int position,
645             final long id) {
646         if (mAdapter.isSectionFooter(position)) {
647             // since a footer should be after a list item by definition, let's look up the type
648             // of the previous item
649             SearchResult item = mAdapter.getTItem(position - 1);
650             Intent intent = new Intent(this, SearchActivity.class);
651             intent.putExtra(SearchManager.QUERY, mFilterString);
652             intent.putExtra(SearchManager.SEARCH_MODE, item.mType.ordinal());
653             startActivity(intent);
654         } else {
655             SearchResult item = mAdapter.getTItem(position);
656             switch (item.mType) {
657                 case Artist:
658                     NavUtils.openArtistProfile(this, item.mArtist);
659                     break;
660                 case Album:
661                     NavUtils.openAlbumProfile(this, item.mAlbum, item.mArtist, item.mId);
662                     break;
663                 case Playlist:
664                     NavUtils.openPlaylist(this, item.mId, item.mTitle);
665                     break;
666                 case Song:
667                     // If it's a song, play it and leave
668                     final long[] list = new long[]{
669                             item.mId
670                     };
671                     MusicUtils.playAll(this, list, 0, -1, Config.IdType.NA, false);
672                     break;
673             }
674         }
675     }
676
677     /**
678      * {@inheritDoc}
679      */
680     @Override
681     public void onServiceConnected(final ComponentName name, final IBinder service) {
682         mService = IElevenService.Stub.asInterface(service);
683     }
684
685     /**
686      * {@inheritDoc}
687      */
688     @Override
689     public void onServiceDisconnected(final ComponentName name) {
690         mService = null;
691     }
692
693     /**
694      * This class loads a search result summary of items
695      */
696     private static final class SummarySearchLoader extends SimpleListLoader<SearchResult> {
697         private final String mQuery;
698         private final ResultType mSearchType;
699
700         public SummarySearchLoader(final Context context, final String query,
701                                    final ResultType searchType) {
702             super(context);
703             mQuery = query;
704             mSearchType = searchType;
705         }
706
707         /**
708          * This creates a search result given the data at the cursor position
709          * @param cursor at the position for the item
710          * @param type the type of item to create
711          * @return the search result
712          */
713         protected SearchResult createSearchResult(final Cursor cursor, ResultType type) {
714             SearchResult item = null;
715
716             switch (type) {
717                 case Playlist:
718                     item = SearchResult.createPlaylistResult(cursor);
719                     item.mSongCount = MusicUtils.getSongCountForPlaylist(getContext(), item.mId);
720                     break;
721                 case Song:
722                     item = SearchResult.createSearchResult(cursor);
723                     if (item != null) {
724                         AlbumArtistDetails details = MusicUtils.getAlbumArtDetails(getContext(),
725                                 item.mId);
726                         if (details != null) {
727                             item.mArtist = details.mArtistName;
728                             item.mAlbum = details.mAlbumName;
729                             item.mAlbumId = details.mAlbumId;
730                         }
731                     }
732                     break;
733                 case Album:
734                 case Artist:
735                 default:
736                     item = SearchResult.createSearchResult(cursor);
737                     break;
738             }
739
740             return item;
741         }
742
743         @Override
744         public List<SearchResult> loadInBackground() {
745             // if we are doing a specific type search, run that one
746             if (mSearchType != null && mSearchType != ResultType.Unknown) {
747                 return runSearchForType();
748             }
749
750             return runGenericSearch();
751         }
752
753         /**
754          * This creates a search for a specific type given a filter string.  This will return the
755          * full list of results that matches those two requirements
756          * @return the results for that search
757          */
758         protected List<SearchResult> runSearchForType() {
759             ArrayList<SearchResult> results = new ArrayList<SearchResult>();
760             Cursor cursor = null;
761             try {
762                 if (mSearchType == ResultType.Playlist) {
763                     cursor = makePlaylistSearchCursor(getContext(), mQuery);
764                 } else {
765                     cursor = ApolloUtils.createSearchQueryCursor(getContext(), mQuery);
766                 }
767
768                 // pre-cache this index
769                 final int mimeTypeIndex = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE);
770
771                 if (cursor != null && cursor.moveToFirst()) {
772                     do {
773                         boolean addResult = true;
774
775                         if (mSearchType != ResultType.Playlist) {
776                             // get the result type
777                             ResultType type = ResultType.getResultType(cursor, mimeTypeIndex);
778                             if (type != mSearchType) {
779                                 addResult = false;
780                             }
781                         }
782
783                         if (addResult) {
784                             results.add(createSearchResult(cursor, mSearchType));
785                         }
786                     } while (cursor.moveToNext());
787                 }
788
789             } finally {
790                 if (cursor != null) {
791                     cursor.close();
792                     cursor = null;
793                 }
794             }
795
796             return results;
797         }
798
799         /**
800          * This will run a search given a filter string and return the top NUM_RESULTS_TO_GET per
801          * type
802          * @return the results for that search
803          */
804         public List<SearchResult> runGenericSearch() {
805             ArrayList<SearchResult> results = new ArrayList<SearchResult>();
806             // number of types to query for
807             final int numTypes = ResultType.getNumTypes();
808
809             // number of results we want
810             final int numResultsNeeded = Config.SEARCH_NUM_RESULTS_TO_GET * numTypes;
811
812             // current number of results we have
813             int numResultsAdded = 0;
814
815             // count for each result type
816             int[] numOfEachType = new int[numTypes];
817
818             // search playlists first
819             Cursor playlistCursor = makePlaylistSearchCursor(getContext(), mQuery);
820             if (playlistCursor != null && playlistCursor.moveToFirst()) {
821                 do {
822                     // create the item
823                     SearchResult item = createSearchResult(playlistCursor, ResultType.Playlist);
824                     /// add the results
825                     numResultsAdded++;
826                     results.add(item);
827                 } while (playlistCursor.moveToNext()
828                         && numResultsAdded < Config.SEARCH_NUM_RESULTS_TO_GET);
829
830                 // because we deal with playlists separately,
831                 // just mark that we have the full # of playlists
832                 // so that logic later can quit out early if full
833                 numResultsAdded = Config.SEARCH_NUM_RESULTS_TO_GET;
834
835                 // close the cursor
836                 playlistCursor.close();
837                 playlistCursor = null;
838             }
839
840             // do fancy audio search
841             Cursor cursor = ApolloUtils.createSearchQueryCursor(getContext(), mQuery);
842
843             // pre-cache this index
844             final int mimeTypeIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE);
845
846             // walk through the cursor
847             if (cursor != null && cursor.moveToFirst()) {
848                 do {
849                     // get the result type
850                     ResultType type = ResultType.getResultType(cursor, mimeTypeIndex);
851
852                     // if we still need this type
853                     if (numOfEachType[type.ordinal()] < Config.SEARCH_NUM_RESULTS_TO_GET) {
854                         // get the search result
855                         SearchResult item = createSearchResult(cursor, type);
856
857                         if (item != null) {
858                             // add it
859                             results.add(item);
860                             numOfEachType[type.ordinal()]++;
861                             numResultsAdded++;
862
863                             // if we have enough then quit
864                             if (numResultsAdded >= numResultsNeeded) {
865                                 break;
866                             }
867                         }
868                     }
869                 } while (cursor.moveToNext());
870
871                 cursor.close();
872                 cursor = null;
873             }
874
875             // sort our results
876             Collections.sort(results, SearchResult.COMPARATOR);
877
878             return results;
879         }
880
881         public static Cursor makePlaylistSearchCursor(final Context context,
882                                                       final String searchTerms) {
883             if (TextUtils.isEmpty(searchTerms)) {
884                 return null;
885             }
886
887             // trim out special characters like % or \ as well as things like "a" "and" etc
888             String trimmedSearchTerms = MusicUtils.getTrimmedName(searchTerms);
889
890             if (TextUtils.isEmpty(trimmedSearchTerms)) {
891                 return null;
892             }
893
894             String[] keywords = trimmedSearchTerms.split(" ");
895
896             // prep the keyword for like search
897             for (int i = 0; i < keywords.length; i++) {
898                 keywords[i] = "%" + keywords[i] + "%";
899             }
900
901             String where = "";
902
903             // make the where clause
904             for (int i = 0; i < keywords.length; i++) {
905                 if (i == 0) {
906                     where = "name LIKE ?";
907                 } else {
908                     where += " AND name LIKE ?";
909                 }
910             }
911
912             return context.getContentResolver().query(
913                     MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
914                     new String[]{
915                         /* 0 */
916                             BaseColumns._ID,
917                         /* 1 */
918                             MediaStore.Audio.PlaylistsColumns.NAME
919                     }, where, keywords, MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER);
920         }
921     }
922
923     /**
924      * Loads the search history in the background and creates an array adapter
925      */
926     public static class SearchHistoryLoader extends WrappedAsyncTaskLoader<ArrayAdapter<String>> {
927         public SearchHistoryLoader(Context context) {
928             super(context);
929         }
930
931         @Override
932         public ArrayAdapter<String> loadInBackground() {
933             ArrayList<String> strings = SearchHistory.getInstance(getContext()).getRecentSearches();
934             ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
935                     R.layout.list_item_search_history, R.id.line_one);
936             adapter.addAll(strings);
937             return adapter;
938         }
939     }
940
941     /**
942      * This handles the Loader callbacks for the search history
943      */
944     public class SearchHistoryCallback implements LoaderCallbacks<ArrayAdapter<String>> {
945         @Override
946         public Loader<ArrayAdapter<String>> onCreateLoader(int i, Bundle bundle) {
947             // prep the loader in case the query takes a long time
948             setLoading();
949
950             return new SearchHistoryLoader(SearchActivity.this);
951         }
952
953         @Override
954         public void onLoadFinished(Loader<ArrayAdapter<String>> searchHistoryAdapterLoader,
955                                    ArrayAdapter<String> searchHistoryAdapter) {
956             // show the search history
957             setState(VisibleState.SearchHistory);
958
959             mSearchHistoryListView.setAdapter(searchHistoryAdapter);
960         }
961
962         @Override
963         public void onLoaderReset(Loader<ArrayAdapter<String>> cursorAdapterLoader) {
964             ((ArrayAdapter)mSearchHistoryListView.getAdapter()).clear();
965         }
966     }
967
968     /**
969      * {@inheritDoc}
970      */
971     @Override
972     public void onScroll(final AbsListView view, final int firstVisibleItem,
973             final int visibleItemCount, final int totalItemCount) {
974         // Nothing to do
975     }
976
977     @Override
978     public boolean onTouch(View v, MotionEvent event) {
979         hideInputManager();
980         return false;
981     }
982 }