summaryrefslogtreecommitdiffstats
path: root/src/org/lineageos/eleven/ui/activities/SearchActivity.java
blob: 3bfbb6f96ce315acad0143663417efcc3a9d9257 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
/*
 * Copyright (C) 2012 Andrew Neal
 * Copyright (C) 2014 The CyanogenMod Project
 * Licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

package com.cyanogenmod.eleven.ui.activities;

import android.app.ActionBar;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

import com.cyanogenmod.eleven.Config;
import com.cyanogenmod.eleven.IElevenService;
import com.cyanogenmod.eleven.R;
import com.cyanogenmod.eleven.adapters.SummarySearchAdapter;
import com.cyanogenmod.eleven.loaders.WrappedAsyncTaskLoader;
import com.cyanogenmod.eleven.menu.FragmentMenuItems;
import com.cyanogenmod.eleven.model.AlbumArtistDetails;
import com.cyanogenmod.eleven.model.SearchResult;
import com.cyanogenmod.eleven.model.SearchResult.ResultType;
import com.cyanogenmod.eleven.provider.SearchHistory;
import com.cyanogenmod.eleven.recycler.RecycleHolder;
import com.cyanogenmod.eleven.sectionadapter.SectionAdapter;
import com.cyanogenmod.eleven.sectionadapter.SectionCreator;
import com.cyanogenmod.eleven.sectionadapter.SectionCreator.SimpleListLoader;
import com.cyanogenmod.eleven.sectionadapter.SectionListContainer;
import com.cyanogenmod.eleven.utils.ApolloUtils;
import com.cyanogenmod.eleven.utils.MusicUtils;
import com.cyanogenmod.eleven.utils.MusicUtils.ServiceToken;
import com.cyanogenmod.eleven.utils.NavUtils;
import com.cyanogenmod.eleven.utils.PopupMenuHelper;
import com.cyanogenmod.eleven.utils.SectionCreatorUtils;
import com.cyanogenmod.eleven.utils.SectionCreatorUtils.IItemCompare;
import com.cyanogenmod.eleven.widgets.IPopupMenuCallback;
import com.cyanogenmod.eleven.widgets.LoadingEmptyContainer;
import com.cyanogenmod.eleven.widgets.NoResultsContainer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;

import static android.view.View.OnTouchListener;
import static com.cyanogenmod.eleven.utils.MusicUtils.mService;

/**
 * Provides the search interface for Apollo.
 *
 * @author Andrew Neal (andrewdneal@gmail.com)
 */
public class SearchActivity extends FragmentActivity implements
        LoaderCallbacks<SectionListContainer<SearchResult>>,
        OnScrollListener, OnQueryTextListener, OnItemClickListener, ServiceConnection,
        OnTouchListener {
    /**
     * Loading delay of 500ms so we don't flash the screen too much when loading new searches
     */
    private static int LOADING_DELAY = 500;

    /**
     * Identifier for the search loader
     */
    private static int SEARCH_LOADER = 0;

    /**
     * Identifier for the search history loader
     */
    private static int HISTORY_LOADER = 1;

    /**
     * The service token
     */
    private ServiceToken mToken;

    /**
     * The query
     */
    private String mFilterString;

    /**
     * List view
     */
    private ListView mListView;

    /**
     * Used the filter the user's music
     */
    private SearchView mSearchView;

    /**
     * IME manager
     */
    private InputMethodManager mImm;

    /**
     * The view that container the no search results text and the loading progress bar
     */
    private LoadingEmptyContainer mLoadingEmptyContainer;

    /**
     * List view adapter
     */
    private SectionAdapter<SearchResult, SummarySearchAdapter> mAdapter;

    /**
     * boolean tracking whether this is the search level when the user first enters search
     * or if the user has clicked show all
     */
    private boolean mTopLevelSearch;

    /**
     * If the user has clicked show all, this tells us what type (Artist, Album, etc)
     */
    private ResultType mSearchType;

    /**
     * Search History loader callback
     */
    private SearchHistoryCallback mSearchHistoryCallback;

    /**
     * List view
     */
    private ListView mSearchHistoryListView;

    /**
     * This tracks our current visible state between the different views
      */
    enum VisibleState {
        SearchHistory,
        Empty,
        SearchResults,
        Loading,
    }

    private VisibleState mCurrentState;

    /**
     * Handler for posting runnables
     */
    private Handler mHandler;

    /**
     * A runnable to show the loading view that will be posted with a delay to prevent flashing
     */
    private Runnable mLoadingRunnable;

    /**
     * Flag used to track if we are quitting so we don't flash loaders while finishing the activity
     */
    private boolean mQuitting = false;

    /**
     * Pop up menu helper
     */
    private PopupMenuHelper mPopupMenuHelper;

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mPopupMenuHelper = new PopupMenuHelper(this, getSupportFragmentManager()) {
            private SearchResult mSelectedItem;

            @Override
            public PopupMenuType onPreparePopupMenu(int position) {
                mSelectedItem = mAdapter.getTItem(position);

                return PopupMenuType.SearchResult;
            }

            @Override
            protected long[] getIdList() {
                switch (mSelectedItem.mType) {
                    case Artist:
                        return MusicUtils.getSongListForArtist(SearchActivity.this,
                                mSelectedItem.mId);
                    case Album:
                        return MusicUtils.getSongListForAlbum(SearchActivity.this,
                                mSelectedItem.mId);
                    case Song:
                        return new long[] { mSelectedItem.mId };
                    case Playlist:
                        return MusicUtils.getSongListForPlaylist(SearchActivity.this,
                                mSelectedItem.mId);
                    default:
                        return null;
                }
            }

            @Override
            protected long getSourceId() {
                return mSelectedItem.mId;
            }

            @Override
            protected Config.IdType getSourceType() {
                return mSelectedItem.mType.getSourceType();
            }

            @Override
            protected void updateMenuIds(PopupMenuType type, TreeSet<Integer> set) {
                super.updateMenuIds(type, set);

                if (mSelectedItem.mType == ResultType.Album) {
                    set.add(FragmentMenuItems.MORE_BY_ARTIST);
                }
            }

            @Override
            protected String getArtistName() {
                return mSelectedItem.mArtist;
            }
        };

        // Fade it in
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        // Control the media volume
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        // Bind Apollo's service
        mToken = MusicUtils.bindToService(this, this);

        // Set the layout
        setContentView(R.layout.activity_search);

        // get the input method manager
        mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        // Initialize the adapter
        SummarySearchAdapter adapter = new SummarySearchAdapter(this);
        mAdapter = new SectionAdapter<SearchResult, SummarySearchAdapter>(this, adapter);
        // Set the prefix
        mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);
        mAdapter.setupHeaderParameters(R.layout.list_search_header, false);
        mAdapter.setupFooterParameters(R.layout.list_search_footer, true);
        mAdapter.setPopupMenuClickedListener(new IPopupMenuCallback.IListener() {
            @Override
            public void onPopupMenuClicked(View v, int position) {
                mPopupMenuHelper.showPopupMenu(v, position);
            }
        });

        mLoadingEmptyContainer = (LoadingEmptyContainer) findViewById(R.id.loading_empty_container);
        // setup the no results container
        NoResultsContainer noResults = mLoadingEmptyContainer.getNoResultsContainer();
        noResults.setMainText(R.string.empty_search);
        noResults.setSecondaryText(R.string.empty_search_check);

        initListView();

        // setup handler and runnable
        mHandler = new Handler();
        mLoadingRunnable = new Runnable() {
            @Override
            public void run() {
                setState(VisibleState.Loading);
            }
        };

        // Theme the action bar
        final ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        // Get the query String
        mFilterString = getIntent().getStringExtra(SearchManager.QUERY);

        // if we have a non-empty search string, this is a 2nd lvl search
        if (!TextUtils.isEmpty(mFilterString)) {
            mTopLevelSearch = false;

            // get the search type to filter by
            int type = getIntent().getIntExtra(SearchManager.SEARCH_MODE, -1);
            if (type >= 0 && type < ResultType.values().length) {
                mSearchType = ResultType.values()[type];
            }

            int resourceId = 0;
            switch (mSearchType) {
                case Artist:
                    resourceId = R.string.search_title_artists;
                    break;
                case Album:
                    resourceId = R.string.search_title_albums;
                    break;
                case Playlist:
                    resourceId = R.string.search_title_playlists;
                    break;
                case Song:
                    resourceId = R.string.search_title_songs;
                    break;
            }
            actionBar.setTitle(getString(resourceId, mFilterString));
            actionBar.setDisplayHomeAsUpEnabled(true);

            // Set the prefix
            mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);

            // Start the loader for the query
            getSupportLoaderManager().initLoader(SEARCH_LOADER, null, this);
        } else {
            mTopLevelSearch = true;
            mSearchHistoryCallback = new SearchHistoryCallback();

            // Start the loader for the search history
            getSupportLoaderManager().initLoader(HISTORY_LOADER, null, mSearchHistoryCallback);
        }
    }

    /**
     * Sets up the list view
     */
    private void initListView() {
        // Initialize the grid
        mListView = (ListView)findViewById(R.id.list_base);
        // Set the data behind the list
        mListView.setAdapter(mAdapter);
        // Release any references to the recycled Views
        mListView.setRecyclerListener(new RecycleHolder());
        // Show the albums and songs from the selected artist
        mListView.setOnItemClickListener(this);
        // To help make scrolling smooth
        mListView.setOnScrollListener(this);
        // sets the touch listener
        mListView.setOnTouchListener(this);
        // If we setEmptyView with mLoadingEmptyContainer it causes a crash in DragSortListView
        // when updating the search.  For now let's manually toggle visibility and come back
        // to this later
        //mListView.setEmptyView(mLoadingEmptyContainer);

        // load the search history list view
        mSearchHistoryListView = (ListView)findViewById(R.id.list_search_history);
        mSearchHistoryListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String searchItem = (String)mSearchHistoryListView.getAdapter().getItem(position);
                mSearchView.setQuery(searchItem, true);
            }
        });
        mSearchHistoryListView.setOnTouchListener(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Loader<SectionListContainer<SearchResult>> onCreateLoader(final int id,
                                                                     final Bundle args) {
        IItemCompare<SearchResult> comparator = null;

        // prep the loader in case the query takes a long time
        setLoading();

        // if we are at the top level, create a comparator to separate the different types into
        // their own sections (artists, albums, etc)
        if (mTopLevelSearch) {
            comparator = SectionCreatorUtils.createSearchResultComparison(this);
        }

        return new SectionCreator<SearchResult>(this,
                new SummarySearchLoader(this, mFilterString, mSearchType),
                comparator);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        // if we are not a top level search view, we do not need to create the search fields
        if (!mTopLevelSearch) {
            return super.onCreateOptionsMenu(menu);
        }

        // Search view
        getMenuInflater().inflate(R.menu.search, menu);

        // Filter the list the user is looking it via SearchView
        MenuItem searchItem = menu.findItem(R.id.menu_search);
        mSearchView = (SearchView)searchItem.getActionView();
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setQueryHint(getString(R.string.searchHint));

        // The SearchView has no way for you to customize or get access to the search icon in a
        // normal fashion, so we need to manually look for the icon and change the
        // layout params to hide it
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setIconified(false);
        int searchButtonId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
        ImageView searchIcon = (ImageView)mSearchView.findViewById(searchButtonId);
        searchIcon.setLayoutParams(new LinearLayout.LayoutParams(0, 0));

        searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                quit();
                return false;
            }
        });

        menu.findItem(R.id.menu_search).expandActionView();

        return super.onCreateOptionsMenu(menu);
    }

    private void quit() {
        mQuitting = true;
        finish();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Unbind from the service
        if (mService != null) {
            MusicUtils.unbindFromService(mToken);
            mToken = null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                quit();
                return true;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onLoadFinished(final Loader<SectionListContainer<SearchResult>> loader,
                               final SectionListContainer<SearchResult> data) {
        // Check for any errors
        if (data.mListResults.isEmpty()) {
            // clear the adapter
            mAdapter.clear();
            // show the empty state
            setState(VisibleState.Empty);
        } else {
            // Set the data
            mAdapter.setData(data);
            // show the search results
            setState(VisibleState.SearchResults);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onLoaderReset(final Loader<SectionListContainer<SearchResult>> loader) {
        mAdapter.unload();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onScrollStateChanged(final AbsListView view, final int scrollState) {
        // Pause disk cache access to ensure smoother scrolling
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
            mAdapter.getUnderlyingAdapter().setPauseDiskCache(true);
        } else {
            mAdapter.getUnderlyingAdapter().setPauseDiskCache(false);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onQueryTextSubmit(final String query) {
        // simulate an on query text change
        onQueryTextChange(query);
        // hide the input manager
        hideInputManager();

        return true;
    }

    public void hideInputManager() {
        // When the search is "committed" by the user, then hide the keyboard so
        // the user can more easily browse the list of results.
        if (mSearchView != null) {
            if (mImm != null) {
                mImm.hideSoftInputFromWindow(mSearchView.getWindowToken(), 0);
            }
            mSearchView.clearFocus();

            // add our search string
            SearchHistory.getInstance(this).addSearchString(mFilterString);
        }
    }

    /**
     * This posts a delayed for showing the loading screen.  The reason for the delayed is we
     * don't want to flash the loading icon very often since searches usually are pretty fast
     */
    public void setLoading() {
        if (mCurrentState != VisibleState.Loading) {
            if (!mHandler.hasCallbacks(mLoadingRunnable)) {
                mHandler.postDelayed(mLoadingRunnable, LOADING_DELAY);
            }
        }
    }

    /**
     * Sets the currently visible view
     * @param state the current visible state
     */
    public void setState(VisibleState state) {
        // remove any delayed runnables.  This has to be before mCurrentState == state
        // in case the state doesn't change but we've created a loading runnable
        mHandler.removeCallbacks(mLoadingRunnable);

        // if we are already looking at view already, just quit
        if (mCurrentState == state) {
            return;
        }

        mCurrentState = state;

        mSearchHistoryListView.setVisibility(View.INVISIBLE);
        mListView.setVisibility(View.INVISIBLE);
        mLoadingEmptyContainer.setVisibility(View.INVISIBLE);

        switch (mCurrentState) {
            case SearchHistory:
                mSearchHistoryListView.setVisibility(View.VISIBLE);
                break;
            case SearchResults:
                mListView.setVisibility(View.VISIBLE);
                break;
            case Empty:
                mLoadingEmptyContainer.setVisibility(View.VISIBLE);
                mLoadingEmptyContainer.showNoResults();
                break;
            case Loading:
                mLoadingEmptyContainer.setVisibility(View.VISIBLE);
                mLoadingEmptyContainer.showLoading();
                break;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onQueryTextChange(final String newText) {
        if (mQuitting) {
            return true;
        }

        if (TextUtils.isEmpty(newText)) {
            if (!TextUtils.isEmpty(mFilterString)) {
                mFilterString = "";
                getSupportLoaderManager().restartLoader(HISTORY_LOADER, null,
                        mSearchHistoryCallback);
                getSupportLoaderManager().destroyLoader(SEARCH_LOADER);
            }

            return true;
        }

        // if the strings are the same, return
        if (newText.equals(mFilterString)) {
            return true;
        }

        // Called when the action bar search text has changed. Update
        // the search filter, and restart the loader to do a new query
        // with this filter.
        mFilterString = newText;
        // Set the prefix
        mAdapter.getUnderlyingAdapter().setPrefix(mFilterString);
        getSupportLoaderManager().restartLoader(SEARCH_LOADER, null, this);
        getSupportLoaderManager().destroyLoader(HISTORY_LOADER);
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onItemClick(final AdapterView<?> parent, final View view, final int position,
            final long id) {
        if (mAdapter.isSectionFooter(position)) {
            // since a footer should be after a list item by definition, let's look up the type
            // of the previous item
            SearchResult item = mAdapter.getTItem(position - 1);
            Intent intent = new Intent(this, SearchActivity.class);
            intent.putExtra(SearchManager.QUERY, mFilterString);
            intent.putExtra(SearchManager.SEARCH_MODE, item.mType.ordinal());
            startActivity(intent);
        } else {
            SearchResult item = mAdapter.getTItem(position);
            switch (item.mType) {
                case Artist:
                    NavUtils.openArtistProfile(this, item.mArtist);
                    break;
                case Album:
                    NavUtils.openAlbumProfile(this, item.mAlbum, item.mArtist, item.mId);
                    break;
                case Playlist:
                    NavUtils.openPlaylist(this, item.mId, item.mTitle);
                    break;
                case Song:
                    // If it's a song, play it and leave
                    final long[] list = new long[]{
                            item.mId
                    };
                    MusicUtils.playAll(this, list, 0, -1, Config.IdType.NA, false);
                    break;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onServiceConnected(final ComponentName name, final IBinder service) {
        mService = IElevenService.Stub.asInterface(service);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onServiceDisconnected(final ComponentName name) {
        mService = null;
    }

    /**
     * This class loads a search result summary of items
     */
    private static final class SummarySearchLoader extends SimpleListLoader<SearchResult> {
        private final String mQuery;
        private final ResultType mSearchType;

        public SummarySearchLoader(final Context context, final String query,
                                   final ResultType searchType) {
            super(context);
            mQuery = query;
            mSearchType = searchType;
        }

        /**
         * This creates a search result given the data at the cursor position
         * @param cursor at the position for the item
         * @param type the type of item to create
         * @return the search result
         */
        protected SearchResult createSearchResult(final Cursor cursor, ResultType type) {
            SearchResult item = null;

            switch (type) {
                case Playlist:
                    item = SearchResult.createPlaylistResult(cursor);
                    item.mSongCount = MusicUtils.getSongCountForPlaylist(getContext(), item.mId);
                    break;
                case Song:
                    item = SearchResult.createSearchResult(cursor);
                    if (item != null) {
                        AlbumArtistDetails details = MusicUtils.getAlbumArtDetails(getContext(),
                                item.mId);
                        if (details != null) {
                            item.mArtist = details.mArtistName;
                            item.mAlbum = details.mAlbumName;
                            item.mAlbumId = details.mAlbumId;
                        }
                    }
                    break;
                case Album:
                case Artist:
                default:
                    item = SearchResult.createSearchResult(cursor);
                    break;
            }

            return item;
        }

        @Override
        public List<SearchResult> loadInBackground() {
            // if we are doing a specific type search, run that one
            if (mSearchType != null && mSearchType != ResultType.Unknown) {
                return runSearchForType();
            }

            return runGenericSearch();
        }

        /**
         * This creates a search for a specific type given a filter string.  This will return the
         * full list of results that matches those two requirements
         * @return the results for that search
         */
        protected List<SearchResult> runSearchForType() {
            ArrayList<SearchResult> results = new ArrayList<SearchResult>();
            Cursor cursor = null;
            try {
                if (mSearchType == ResultType.Playlist) {
                    cursor = makePlaylistSearchCursor(getContext(), mQuery);
                } else {
                    cursor = ApolloUtils.createSearchQueryCursor(getContext(), mQuery);
                }

                // pre-cache this index
                final int mimeTypeIndex = cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE);

                if (cursor != null && cursor.moveToFirst()) {
                    do {
                        boolean addResult = true;

                        if (mSearchType != ResultType.Playlist) {
                            // get the result type
                            ResultType type = ResultType.getResultType(cursor, mimeTypeIndex);
                            if (type != mSearchType) {
                                addResult = false;
                            }
                        }

                        if (addResult) {
                            results.add(createSearchResult(cursor, mSearchType));
                        }
                    } while (cursor.moveToNext());
                }

            } finally {
                if (cursor != null) {
                    cursor.close();
                    cursor = null;
                }
            }

            return results;
        }

        /**
         * This will run a search given a filter string and return the top NUM_RESULTS_TO_GET per
         * type
         * @return the results for that search
         */
        public List<SearchResult> runGenericSearch() {
            ArrayList<SearchResult> results = new ArrayList<SearchResult>();
            // number of types to query for
            final int numTypes = ResultType.getNumTypes();

            // number of results we want
            final int numResultsNeeded = Config.SEARCH_NUM_RESULTS_TO_GET * numTypes;

            // current number of results we have
            int numResultsAdded = 0;

            // count for each result type
            int[] numOfEachType = new int[numTypes];

            // search playlists first
            Cursor playlistCursor = makePlaylistSearchCursor(getContext(), mQuery);
            if (playlistCursor != null && playlistCursor.moveToFirst()) {
                do {
                    // create the item
                    SearchResult item = createSearchResult(playlistCursor, ResultType.Playlist);
                    /// add the results
                    numResultsAdded++;
                    results.add(item);
                } while (playlistCursor.moveToNext()
                        && numResultsAdded < Config.SEARCH_NUM_RESULTS_TO_GET);

                // because we deal with playlists separately,
                // just mark that we have the full # of playlists
                // so that logic later can quit out early if full
                numResultsAdded = Config.SEARCH_NUM_RESULTS_TO_GET;

                // close the cursor
                playlistCursor.close();
                playlistCursor = null;
            }

            // do fancy audio search
            Cursor cursor = ApolloUtils.createSearchQueryCursor(getContext(), mQuery);

            // pre-cache this index
            final int mimeTypeIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE);

            // walk through the cursor
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    // get the result type
                    ResultType type = ResultType.getResultType(cursor, mimeTypeIndex);

                    // if we still need this type
                    if (numOfEachType[type.ordinal()] < Config.SEARCH_NUM_RESULTS_TO_GET) {
                        // get the search result
                        SearchResult item = createSearchResult(cursor, type);

                        if (item != null) {
                            // add it
                            results.add(item);
                            numOfEachType[type.ordinal()]++;
                            numResultsAdded++;

                            // if we have enough then quit
                            if (numResultsAdded >= numResultsNeeded) {
                                break;
                            }
                        }
                    }
                } while (cursor.moveToNext());

                cursor.close();
                cursor = null;
            }

            // sort our results
            Collections.sort(results, SearchResult.COMPARATOR);

            return results;
        }

        public static Cursor makePlaylistSearchCursor(final Context context,
                                                      final String searchTerms) {
            if (TextUtils.isEmpty(searchTerms)) {
                return null;
            }

            // trim out special characters like % or \ as well as things like "a" "and" etc
            String trimmedSearchTerms = MusicUtils.getTrimmedName(searchTerms);

            if (TextUtils.isEmpty(trimmedSearchTerms)) {
                return null;
            }

            String[] keywords = trimmedSearchTerms.split(" ");

            // prep the keyword for like search
            for (int i = 0; i < keywords.length; i++) {
                keywords[i] = "%" + keywords[i] + "%";
            }

            String where = "";

            // make the where clause
            for (int i = 0; i < keywords.length; i++) {
                if (i == 0) {
                    where = "name LIKE ?";
                } else {
                    where += " AND name LIKE ?";
                }
            }

            return context.getContentResolver().query(
                    MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
                    new String[]{
                        /* 0 */
                            BaseColumns._ID,
                        /* 1 */
                            MediaStore.Audio.PlaylistsColumns.NAME
                    }, where, keywords, MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER);
        }
    }

    /**
     * Loads the search history in the background and creates an array adapter
     */
    public static class SearchHistoryLoader extends WrappedAsyncTaskLoader<ArrayAdapter<String>> {
        public SearchHistoryLoader(Context context) {
            super(context);
        }

        @Override
        public ArrayAdapter<String> loadInBackground() {
            ArrayList<String> strings = SearchHistory.getInstance(getContext()).getRecentSearches();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
                    R.layout.list_item_search_history, R.id.line_one);
            adapter.addAll(strings);
            return adapter;
        }
    }

    /**
     * This handles the Loader callbacks for the search history
     */
    public class SearchHistoryCallback implements LoaderCallbacks<ArrayAdapter<String>> {
        @Override
        public Loader<ArrayAdapter<String>> onCreateLoader(int i, Bundle bundle) {
            // prep the loader in case the query takes a long time
            setLoading();

            return new SearchHistoryLoader(SearchActivity.this);
        }

        @Override
        public void onLoadFinished(Loader<ArrayAdapter<String>> searchHistoryAdapterLoader,
                                   ArrayAdapter<String> searchHistoryAdapter) {
            // show the search history
            setState(VisibleState.SearchHistory);

            mSearchHistoryListView.setAdapter(searchHistoryAdapter);
        }

        @Override
        public void onLoaderReset(Loader<ArrayAdapter<String>> cursorAdapterLoader) {
            ((ArrayAdapter)mSearchHistoryListView.getAdapter()).clear();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onScroll(final AbsListView view, final int firstVisibleItem,
            final int visibleItemCount, final int totalItemCount) {
        // Nothing to do
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        hideInputManager();
        return false;
    }
}