summaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/eleven/ui/activities/HomeActivity.java
blob: 1462f9a18e9f2220710bdb353b3fe24831935167 (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
/*
 * 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.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.Window;

import com.cyanogenmod.eleven.Config;
import com.cyanogenmod.eleven.R;
import com.cyanogenmod.eleven.cache.ImageFetcher;
import com.cyanogenmod.eleven.ui.fragments.AlbumDetailFragment;
import com.cyanogenmod.eleven.ui.fragments.ArtistDetailFragment;
import com.cyanogenmod.eleven.ui.fragments.AudioPlayerFragment;
import com.cyanogenmod.eleven.ui.fragments.IChildFragment;
import com.cyanogenmod.eleven.ui.fragments.ISetupActionBar;
import com.cyanogenmod.eleven.ui.fragments.PlaylistDetailFragment;
import com.cyanogenmod.eleven.ui.fragments.RecentFragment;
import com.cyanogenmod.eleven.ui.fragments.phone.MusicBrowserPhoneFragment;
import com.cyanogenmod.eleven.ui.fragments.profile.LastAddedFragment;
import com.cyanogenmod.eleven.ui.fragments.profile.TopTracksFragment;
import com.cyanogenmod.eleven.utils.ApolloUtils;
import com.cyanogenmod.eleven.utils.BitmapWithColors;
import com.cyanogenmod.eleven.utils.MusicUtils;
import com.cyanogenmod.eleven.utils.NavUtils;

public class HomeActivity extends SlidingPanelActivity implements
        FragmentManager.OnBackStackChangedListener {
    private static final String TAG = "HomeActivity";
    private static final String ACTION_PREFIX = HomeActivity.class.getName();
    public static final String ACTION_VIEW_ARTIST_DETAILS = ACTION_PREFIX + ".view.ArtistDetails";
    public static final String ACTION_VIEW_ALBUM_DETAILS = ACTION_PREFIX + ".view.AlbumDetails";
    public static final String ACTION_VIEW_PLAYLIST_DETAILS = ACTION_PREFIX + ".view.PlaylistDetails";
    public static final String ACTION_VIEW_SMART_PLAYLIST = ACTION_PREFIX + ".view.SmartPlaylist";
    public static final String EXTRA_BROWSE_PAGE_IDX = "BrowsePageIndex";

    private static final String STATE_KEY_BASE_FRAGMENT = "BaseFragment";

    private static final int NEW_PHOTO = 1;
    public static final int EQUALIZER = 2;

    private String mKey;
    private boolean mLoadedBaseFragment = false;
    private boolean mHasPendingPlaybackRequest = false;
    private Handler mHandler = new Handler();
    private boolean mBrowsePanelActive = true;

    /**
     * Used by the up action to determine how to handle this
     */
    protected boolean mTopLevelActivity = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // if we've been launched by an intent, parse it
        Intent launchIntent = getIntent();
        boolean intentHandled = false;
        if (launchIntent != null) {
            intentHandled = parseIntentForFragment(launchIntent);
        }

        // if the intent didn't cause us to load a fragment, load the music browse one
        if (savedInstanceState == null && !mLoadedBaseFragment) {
            final MusicBrowserPhoneFragment fragment = new MusicBrowserPhoneFragment();
            if (launchIntent != null) {
                fragment.setDefaultPageIdx(launchIntent.getIntExtra(EXTRA_BROWSE_PAGE_IDX,
                        MusicBrowserPhoneFragment.INVALID_PAGE_INDEX));
            }
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.activity_base_content, fragment)
                    .commit();

            mLoadedBaseFragment = true;
            mTopLevelActivity = true;
        }

        getSupportFragmentManager().addOnBackStackChangedListener(this);

        // if we are resuming from a saved instance state
        if (savedInstanceState != null) {
            // track which fragments are loaded and if this is the top level activity
            mTopLevelActivity = savedInstanceState.getBoolean(STATE_KEY_BASE_FRAGMENT);
            mLoadedBaseFragment = mTopLevelActivity;

            // update the action bar based on the top most fragment
            onBackStackChanged();

            // figure which panel we are on and update the status bar
            mBrowsePanelActive = (getCurrentPanel() == Panel.Browse);
            updateStatusBarColor();
        }

        // if intent wasn't UI related, process it as a audio playback request
        if (!intentHandled) {
            handlePlaybackIntent(launchIntent);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_KEY_BASE_FRAGMENT, mTopLevelActivity);
    }

    public Fragment getTopFragment() {
        return getSupportFragmentManager().findFragmentById(R.id.activity_base_content);
    }

    public void postRemoveFragment(final Fragment frag) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // removing the fragment doesn't cause the backstack event to be triggered even if
                // it is the top fragment, so if it is the top fragment, we will just manually
                // call pop back stack
                if (frag == getTopFragment()) {
                    getSupportFragmentManager().popBackStack();
                } else {
                    getSupportFragmentManager().beginTransaction().remove(frag).commit();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // parse intent to ascertain whether the intent is inter UI communication
        boolean intentHandled = parseIntentForFragment(intent);
        // since this activity is marked 'singleTop' (launch mode), an existing activity instance
        // could be sent media play requests
        if ( !intentHandled) {
            handlePlaybackIntent(intent);
        }
    }

    @Override
    public void onMetaChanged() {
        super.onMetaChanged();
        updateStatusBarColor();
    }

    @Override
    protected void onSlide(float slideOffset) {
        boolean isInBrowser = getCurrentPanel() == Panel.Browse && slideOffset < 0.7f;
        if (isInBrowser != mBrowsePanelActive) {
            mBrowsePanelActive = isInBrowser;
            updateStatusBarColor();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        getAudioPlayerFragment().setVisualizerVisible(hasFocus
                && getCurrentPanel() == Panel.MusicPlayer);
    }

    private void updateStatusBarColor() {
        if (mBrowsePanelActive || MusicUtils.getCurrentAlbumId() < 0) {
            updateStatusBarColor(Color.TRANSPARENT);
        } else {
            new AsyncTask<Void, Void, BitmapWithColors>() {
                @Override
                protected BitmapWithColors doInBackground(Void... params) {
                    ImageFetcher imageFetcher = ImageFetcher.getInstance(HomeActivity.this);
                    return imageFetcher.getArtwork(
                            MusicUtils.getAlbumName(), MusicUtils.getCurrentAlbumId(),
                            MusicUtils.getArtistName(), true);
                }
                @Override
                protected void onPostExecute(BitmapWithColors bmc) {
                    updateVisualizerColor(bmc != null
                            ? bmc.getVibrantColor() : Color.TRANSPARENT);
                    updateStatusBarColor(bmc != null
                            ? bmc.getVibrantDarkColor() : Color.TRANSPARENT);
                }
            }.execute();
        }
    }

    private void updateVisualizerColor(int color) {
        if (color == Color.TRANSPARENT) {
            color = getResources().getColor(R.color.visualizer_fill_color);
        }

        // check for null since updatestatusBarColor is a async task
        AudioPlayerFragment fragment = getAudioPlayerFragment();
        if (fragment != null) {
            fragment.setVisualizerColor(color);
        }
    }

    private void updateStatusBarColor(int color) {
        if (color == Color.TRANSPARENT) {
            color = getResources().getColor(R.color.primary_dark);
        }
        final Window window = getWindow();
        ObjectAnimator animator = ObjectAnimator.ofInt(window,
                "statusBarColor", window.getStatusBarColor(), color);
        animator.setEvaluator(new ArgbEvaluator());
        animator.setDuration(300);
        animator.start();
    }

    private boolean parseIntentForFragment(Intent intent) {
        boolean handled = false;
        if (intent.getAction() != null) {
            final String action = intent.getAction();
            Fragment targetFragment = null;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            if (action.equals(ACTION_VIEW_SMART_PLAYLIST)) {
                long playlistId = intent.getExtras().getLong(Config.SMART_PLAYLIST_TYPE);
                switch (Config.SmartPlaylistType.getTypeById(playlistId)) {
                    case LastAdded:
                        targetFragment = new LastAddedFragment();
                        break;
                    case RecentlyPlayed:
                        targetFragment = new RecentFragment();
                        break;
                    case TopTracks:
                        targetFragment = new TopTracksFragment();
                        break;
                }
            } else if (action.equals(ACTION_VIEW_PLAYLIST_DETAILS)) {
                targetFragment = new PlaylistDetailFragment();
            } else if (action.equals(ACTION_VIEW_ALBUM_DETAILS)) {
                targetFragment = new AlbumDetailFragment();
            } else if (action.equals(ACTION_VIEW_ARTIST_DETAILS)) {
                targetFragment = new ArtistDetailFragment();
            }

            if (targetFragment != null) {
                targetFragment.setArguments(intent.getExtras());
                transaction.setCustomAnimations(0, 0, 0, R.anim.fade_out);
                // If we ever come back to this because of memory concerns because
                // none of the fragments are being removed from memory, we can fix this
                // by using "replace" instead of "add".  The caveat is that the performance of
                // returning to previous fragments is a bit more sluggish because the fragment
                // view needs to be recreated. If we do remove that, we can remove the back stack
                // change listener code above
                transaction.add(R.id.activity_base_content, targetFragment);
                if (mLoadedBaseFragment) {
                    transaction.addToBackStack(null);
                    showPanel(Panel.Browse);
                } else {
                    // else mark the fragment as loaded so we don't load the music browse fragment.
                    // this happens when they launch search which is its own activity and then
                    // browse through that back to home activity
                    mLoadedBaseFragment = true;
                    getActionBar().setDisplayHomeAsUpEnabled(true);
                }
                // the current top fragment is about to be hidden by what we are replacing
                // it with -- so tell that fragment not to make its action bar menu items visible
                Fragment oldTop = getTopFragment();
                if (oldTop != null) {
                    oldTop.setMenuVisibility(false);
                }

                transaction.commit();
                handled = true;
            }
        }
        return handled;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == NEW_PHOTO && !TextUtils.isEmpty(mKey)) {
            if (resultCode == RESULT_OK) {
                MusicUtils.removeFromCache(this, mKey);
                final Uri selectedImage = data.getData();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = ImageFetcher.decodeSampledBitmapFromUri(getContentResolver(),
                                selectedImage);

                        ImageFetcher imageFetcher = ApolloUtils.getImageFetcher(HomeActivity.this);
                        imageFetcher.addBitmapToCache(mKey, bitmap);

                        MusicUtils.refresh();
                    }
                }).start();
            }
        }
    }

    /**
     * Starts an activity for result that returns an image from the Gallery.
     */
    public void selectNewPhoto(String key) {
        mKey = key;
        // Now open the gallery
        final Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        startActivityForResult(intent, NEW_PHOTO);
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                navigateToTop();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Navigates to the top Activity and places the view to the correct page
     */
    protected void navigateToTop() {
        final Fragment topFragment = getTopFragment();
        int targetFragmentIndex = MusicBrowserPhoneFragment.INVALID_PAGE_INDEX;
        if (topFragment instanceof IChildFragment) {
            targetFragmentIndex = ((IChildFragment)topFragment).getMusicFragmentParent().ordinal();
        }

        // If we are the top activity in the stack (as determined by the activity that has loaded
        // the MusicBrowserPhoneFragment) then clear the back stack and move the browse fragment
        // to the appropriate page as per Android up standards
        if (mTopLevelActivity) {
            clearBackStack();
            MusicBrowserPhoneFragment musicFragment = (MusicBrowserPhoneFragment) getTopFragment();
            musicFragment.setDefaultPageIdx(targetFragmentIndex);
            showPanel(Panel.Browse);
        } else {
            // I've tried all other combinations with parent activities, support.NavUtils and
            // there is no easy way to achieve what we want that I'm aware of, so clear everything
            // and jump to the right page
            NavUtils.goHome(this, targetFragmentIndex);
        }
    }

    /**
     * Immediately clears the backstack
     */
    protected void clearBackStack() {
        final FragmentManager fragmentManager = getSupportFragmentManager();
        if (fragmentManager.getBackStackEntryCount() > 0) {
            final int id = fragmentManager.getBackStackEntryAt(0).getId();
            fragmentManager.popBackStackImmediate(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    @Override
    public void handlePendingPlaybackRequests() {
        if (mHasPendingPlaybackRequest) {
            Intent unhandledIntent = getIntent();
            handlePlaybackIntent(unhandledIntent);
        }
    }

    /**
     * Checks whether the passed intent contains a playback request,
     * and starts playback if that's the case
     * @return true if the intent was consumed
     */
    private boolean handlePlaybackIntent(Intent intent) {

        if (intent == null) {
            return false;
        } else if ( !MusicUtils.isPlaybackServiceConnected() ) {
            mHasPendingPlaybackRequest = true;
            return false;
        }

        String mimeType = intent.getType();
        boolean handled = false;

        if (MediaStore.Audio.Playlists.CONTENT_TYPE.equals(mimeType)) {
            long id = parseIdFromIntent(intent, "playlistId", "playlist", -1);
            if (id >= 0) {
                MusicUtils.playPlaylist(this, id, false);
                handled = true;
            }
        } else if (MediaStore.Audio.Albums.CONTENT_TYPE.equals(mimeType)) {
            long id = parseIdFromIntent(intent, "albumId", "album", -1);
            if (id >= 0) {
                int position = intent.getIntExtra("position", 0);
                MusicUtils.playAlbum(this, id, position, false);
                handled = true;
            }
        } else if (MediaStore.Audio.Artists.CONTENT_TYPE.equals(mimeType)) {
            long id = parseIdFromIntent(intent, "artistId", "artist", -1);
            if (id >= 0) {
                int position = intent.getIntExtra("position", 0);
                MusicUtils.playArtist(this, id, position, false);
                handled = true;
            }
        }

        // reset intent as it was handled as a playback request
        if (handled) {
            setIntent(new Intent());
        }

        return handled;

    }

    private long parseIdFromIntent(Intent intent, String longKey,
                                   String stringKey, long defaultId) {
        long id = intent.getLongExtra(longKey, -1);
        if (id < 0) {
            String idString = intent.getStringExtra(stringKey);
            if (idString != null) {
                try {
                    id = Long.parseLong(idString);
                } catch (NumberFormatException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        }
        return id;
    }

    @Override
    public void onBackStackChanged() {
        Fragment topFragment = getTopFragment();
        if (topFragment != null) {
            // the fragment that has come back to the top should now have its menu items
            // added to the action bar -- so tell it to make it menu items visible
            topFragment.setMenuVisibility(true);
            ISetupActionBar setupActionBar = (ISetupActionBar) topFragment;
            setupActionBar.setupActionBar();

            getActionBar().setDisplayHomeAsUpEnabled(
                    !(topFragment instanceof MusicBrowserPhoneFragment));
        }
    }
}