OSDN Git Service

Add Landscape support to Eleven
[android-x86/packages-apps-Eleven.git] / src / com / cyanogenmod / eleven / ui / activities / HomeActivity.java
1 /*
2  * Copyright (C) 2014 The CyanogenMod Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.cyanogenmod.eleven.ui.activities;
17
18 import android.animation.ArgbEvaluator;
19 import android.animation.ObjectAnimator;
20 import android.content.Intent;
21 import android.graphics.Bitmap;
22 import android.graphics.Color;
23 import android.net.Uri;
24 import android.os.AsyncTask;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.provider.MediaStore;
28 import android.support.v4.app.Fragment;
29 import android.support.v4.app.FragmentManager;
30 import android.support.v4.app.FragmentTransaction;
31 import android.text.TextUtils;
32 import android.util.Log;
33 import android.view.MenuItem;
34 import android.view.Window;
35
36 import com.cyanogenmod.eleven.Config;
37 import com.cyanogenmod.eleven.R;
38 import com.cyanogenmod.eleven.cache.ImageFetcher;
39 import com.cyanogenmod.eleven.ui.fragments.AlbumDetailFragment;
40 import com.cyanogenmod.eleven.ui.fragments.ArtistDetailFragment;
41 import com.cyanogenmod.eleven.ui.fragments.IChildFragment;
42 import com.cyanogenmod.eleven.ui.fragments.ISetupActionBar;
43 import com.cyanogenmod.eleven.ui.fragments.PlaylistDetailFragment;
44 import com.cyanogenmod.eleven.ui.fragments.RecentFragment;
45 import com.cyanogenmod.eleven.ui.fragments.phone.MusicBrowserPhoneFragment;
46 import com.cyanogenmod.eleven.ui.fragments.profile.LastAddedFragment;
47 import com.cyanogenmod.eleven.ui.fragments.profile.TopTracksFragment;
48 import com.cyanogenmod.eleven.utils.ApolloUtils;
49 import com.cyanogenmod.eleven.utils.BitmapWithColors;
50 import com.cyanogenmod.eleven.utils.MusicUtils;
51 import com.cyanogenmod.eleven.utils.NavUtils;
52
53 public class HomeActivity extends SlidingPanelActivity implements
54         FragmentManager.OnBackStackChangedListener {
55     private static final String TAG = "HomeActivity";
56     private static final String ACTION_PREFIX = HomeActivity.class.getName();
57     public static final String ACTION_VIEW_ARTIST_DETAILS = ACTION_PREFIX + ".view.ArtistDetails";
58     public static final String ACTION_VIEW_ALBUM_DETAILS = ACTION_PREFIX + ".view.AlbumDetails";
59     public static final String ACTION_VIEW_PLAYLIST_DETAILS = ACTION_PREFIX + ".view.PlaylistDetails";
60     public static final String ACTION_VIEW_SMART_PLAYLIST = ACTION_PREFIX + ".view.SmartPlaylist";
61     public static final String EXTRA_BROWSE_PAGE_IDX = "BrowsePageIndex";
62
63     private static final String STATE_KEY_BASE_FRAGMENT = "BaseFragment";
64
65     private static final int NEW_PHOTO = 1;
66     public static final int EQUALIZER = 2;
67
68     private String mKey;
69     private boolean mLoadedBaseFragment = false;
70     private boolean mHasPendingPlaybackRequest = false;
71     private Handler mHandler = new Handler();
72     private boolean mBrowsePanelActive = true;
73
74     /**
75      * Used by the up action to determine how to handle this
76      */
77     protected boolean mTopLevelActivity = false;
78
79     @Override
80     protected void onCreate(Bundle savedInstanceState) {
81         super.onCreate(savedInstanceState);
82
83         // if we've been launched by an intent, parse it
84         Intent launchIntent = getIntent();
85         boolean intentHandled = false;
86         if (launchIntent != null) {
87             intentHandled = parseIntentForFragment(launchIntent);
88         }
89
90         // if the intent didn't cause us to load a fragment, load the music browse one
91         if (savedInstanceState == null && !mLoadedBaseFragment) {
92             final MusicBrowserPhoneFragment fragment = new MusicBrowserPhoneFragment();
93             if (launchIntent != null) {
94                 fragment.setDefaultPageIdx(launchIntent.getIntExtra(EXTRA_BROWSE_PAGE_IDX,
95                         MusicBrowserPhoneFragment.INVALID_PAGE_INDEX));
96             }
97             getSupportFragmentManager().beginTransaction()
98                     .replace(R.id.activity_base_content, fragment)
99                     .commit();
100
101             mLoadedBaseFragment = true;
102             mTopLevelActivity = true;
103         }
104
105         getSupportFragmentManager().addOnBackStackChangedListener(this);
106
107         // if we are resuming from a saved instance state
108         if (savedInstanceState != null) {
109             // track which fragments are loaded and if this is the top level activity
110             mTopLevelActivity = savedInstanceState.getBoolean(STATE_KEY_BASE_FRAGMENT);
111             mLoadedBaseFragment = mTopLevelActivity;
112
113             // update the action bar based on the top most fragment
114             onBackStackChanged();
115
116             // figure which panel we are on and update the status bar
117             mBrowsePanelActive = (getCurrentPanel() == Panel.Browse);
118             updateStatusBarColor();
119         }
120
121         // if intent wasn't UI related, process it as a audio playback request
122         if (!intentHandled) {
123             handlePlaybackIntent(launchIntent);
124         }
125     }
126
127     @Override
128     protected void onSaveInstanceState(Bundle outState) {
129         super.onSaveInstanceState(outState);
130         outState.putBoolean(STATE_KEY_BASE_FRAGMENT, mTopLevelActivity);
131     }
132
133     public Fragment getTopFragment() {
134         return getSupportFragmentManager().findFragmentById(R.id.activity_base_content);
135     }
136
137     public void postRemoveFragment(final Fragment frag) {
138         mHandler.post(new Runnable() {
139             @Override
140             public void run() {
141                 // removing the fragment doesn't cause the backstack event to be triggered even if
142                 // it is the top fragment, so if it is the top fragment, we will just manually
143                 // call pop back stack
144                 if (frag == getTopFragment()) {
145                     getSupportFragmentManager().popBackStack();
146                 } else {
147                     getSupportFragmentManager().beginTransaction().remove(frag).commit();
148                 }
149             }
150         });
151     }
152
153     @Override
154     protected void onNewIntent(Intent intent) {
155         super.onNewIntent(intent);
156
157         // parse intent to ascertain whether the intent is inter UI communication
158         boolean intentHandled = parseIntentForFragment(intent);
159         // since this activity is marked 'singleTop' (launch mode), an existing activity instance
160         // could be sent media play requests
161         if ( !intentHandled) {
162             handlePlaybackIntent(intent);
163         }
164     }
165
166     @Override
167     public void onMetaChanged() {
168         super.onMetaChanged();
169         updateStatusBarColor();
170     }
171
172     @Override
173     protected void onSlide(float slideOffset) {
174         super.onSlide(slideOffset);
175
176         boolean isInBrowser = getCurrentPanel() == Panel.Browse && slideOffset < 0.7f;
177         if (isInBrowser != mBrowsePanelActive) {
178             mBrowsePanelActive = isInBrowser;
179             updateStatusBarColor();
180         }
181     }
182
183     private void updateStatusBarColor() {
184         if (mBrowsePanelActive || MusicUtils.getCurrentAlbumId() < 0) {
185             updateStatusBarColor(getResources().getColor(R.color.primary_dark));
186         } else {
187             new AsyncTask<Void, Void, Integer>() {
188                 @Override
189                 protected Integer doInBackground(Void... params) {
190                     ImageFetcher imageFetcher = ImageFetcher.getInstance(HomeActivity.this);
191                     final BitmapWithColors bitmap = imageFetcher.getArtwork(
192                             MusicUtils.getAlbumName(), MusicUtils.getCurrentAlbumId(),
193                             MusicUtils.getArtistName(), true);
194                     return bitmap != null ? bitmap.getVibrantDarkColor() : Color.TRANSPARENT;
195                 }
196                 @Override
197                 protected void onPostExecute(Integer color) {
198                     if (color == Color.TRANSPARENT) {
199                         color = getResources().getColor(R.color.primary_dark);
200                     }
201                     updateStatusBarColor(color);
202                 }
203             }.execute();
204         }
205     }
206
207     private void updateStatusBarColor(int color) {
208         final Window window = getWindow();
209         ObjectAnimator animator = ObjectAnimator.ofInt(window,
210                 "statusBarColor", window.getStatusBarColor(), color);
211         animator.setEvaluator(new ArgbEvaluator());
212         animator.setDuration(300);
213         animator.start();
214     }
215
216     private boolean parseIntentForFragment(Intent intent) {
217         boolean handled = false;
218         if (intent.getAction() != null) {
219             final String action = intent.getAction();
220             Fragment targetFragment = null;
221             FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
222
223             if (action.equals(ACTION_VIEW_SMART_PLAYLIST)) {
224                 long playlistId = intent.getExtras().getLong(Config.SMART_PLAYLIST_TYPE);
225                 switch (Config.SmartPlaylistType.getTypeById(playlistId)) {
226                     case LastAdded:
227                         targetFragment = new LastAddedFragment();
228                         break;
229                     case RecentlyPlayed:
230                         targetFragment = new RecentFragment();
231                         break;
232                     case TopTracks:
233                         targetFragment = new TopTracksFragment();
234                         break;
235                 }
236             } else if (action.equals(ACTION_VIEW_PLAYLIST_DETAILS)) {
237                 targetFragment = new PlaylistDetailFragment();
238             } else if (action.equals(ACTION_VIEW_ALBUM_DETAILS)) {
239                 targetFragment = new AlbumDetailFragment();
240             } else if (action.equals(ACTION_VIEW_ARTIST_DETAILS)) {
241                 targetFragment = new ArtistDetailFragment();
242             }
243
244             if (targetFragment != null) {
245                 targetFragment.setArguments(intent.getExtras());
246                 transaction.setCustomAnimations(0, 0, 0, R.anim.fade_out);
247                 // If we ever come back to this because of memory concerns because
248                 // none of the fragments are being removed from memory, we can fix this
249                 // by using "replace" instead of "add".  The caveat is that the performance of
250                 // returning to previous fragments is a bit more sluggish because the fragment
251                 // view needs to be recreated. If we do remove that, we can remove the back stack
252                 // change listener code above
253                 transaction.add(R.id.activity_base_content, targetFragment);
254                 if (mLoadedBaseFragment) {
255                     transaction.addToBackStack(null);
256                     showPanel(Panel.Browse);
257                 } else {
258                     // else mark the fragment as loaded so we don't load the music browse fragment.
259                     // this happens when they launch search which is its own activity and then
260                     // browse through that back to home activity
261                     mLoadedBaseFragment = true;
262                     getActionBar().setDisplayHomeAsUpEnabled(true);
263                 }
264                 // the current top fragment is about to be hidden by what we are replacing
265                 // it with -- so tell that fragment not to make its action bar menu items visible
266                 Fragment oldTop = getTopFragment();
267                 if (oldTop != null) {
268                     oldTop.setMenuVisibility(false);
269                 }
270
271                 transaction.commit();
272                 handled = true;
273             }
274         }
275         return handled;
276     }
277
278     @Override
279     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
280         super.onActivityResult(requestCode, resultCode, data);
281         if (requestCode == NEW_PHOTO && !TextUtils.isEmpty(mKey)) {
282             if (resultCode == RESULT_OK) {
283                 MusicUtils.removeFromCache(this, mKey);
284                 final Uri selectedImage = data.getData();
285
286                 new Thread(new Runnable() {
287                     @Override
288                     public void run() {
289                         Bitmap bitmap = ImageFetcher.decodeSampledBitmapFromUri(getContentResolver(),
290                                 selectedImage);
291
292                         ImageFetcher imageFetcher = ApolloUtils.getImageFetcher(HomeActivity.this);
293                         imageFetcher.addBitmapToCache(mKey, bitmap);
294
295                         MusicUtils.refresh();
296                     }
297                 }).start();
298             }
299         }
300     }
301
302     /**
303      * Starts an activity for result that returns an image from the Gallery.
304      */
305     public void selectNewPhoto(String key) {
306         mKey = key;
307         // Now open the gallery
308         final Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
309         intent.setType("image/*");
310         startActivityForResult(intent, NEW_PHOTO);
311     }
312
313     @Override
314     public boolean onOptionsItemSelected(final MenuItem item) {
315         switch (item.getItemId()) {
316             case android.R.id.home:
317                 navigateToTop();
318                 return true;
319         }
320
321         return super.onOptionsItemSelected(item);
322     }
323
324     /**
325      * Navigates to the top Activity and places the view to the correct page
326      */
327     protected void navigateToTop() {
328         final Fragment topFragment = getTopFragment();
329         int targetFragmentIndex = MusicBrowserPhoneFragment.INVALID_PAGE_INDEX;
330         if (topFragment instanceof IChildFragment) {
331             targetFragmentIndex = ((IChildFragment)topFragment).getMusicFragmentParent().ordinal();
332         }
333
334         // If we are the top activity in the stack (as determined by the activity that has loaded
335         // the MusicBrowserPhoneFragment) then clear the back stack and move the browse fragment
336         // to the appropriate page as per Android up standards
337         if (mTopLevelActivity) {
338             clearBackStack();
339             MusicBrowserPhoneFragment musicFragment = (MusicBrowserPhoneFragment) getTopFragment();
340             musicFragment.setDefaultPageIdx(targetFragmentIndex);
341             showPanel(Panel.Browse);
342         } else {
343             // I've tried all other combinations with parent activities, support.NavUtils and
344             // there is no easy way to achieve what we want that I'm aware of, so clear everything
345             // and jump to the right page
346             NavUtils.goHome(this, targetFragmentIndex);
347         }
348     }
349
350     /**
351      * Immediately clears the backstack
352      */
353     protected void clearBackStack() {
354         final FragmentManager fragmentManager = getSupportFragmentManager();
355         if (fragmentManager.getBackStackEntryCount() > 0) {
356             final int id = fragmentManager.getBackStackEntryAt(0).getId();
357             fragmentManager.popBackStackImmediate(id, FragmentManager.POP_BACK_STACK_INCLUSIVE);
358         }
359     }
360
361     @Override
362     public void handlePendingPlaybackRequests() {
363         if (mHasPendingPlaybackRequest) {
364             Intent unhandledIntent = getIntent();
365             handlePlaybackIntent(unhandledIntent);
366         }
367     }
368
369     /**
370      * Checks whether the passed intent contains a playback request,
371      * and starts playback if that's the case
372      * @return true if the intent was consumed
373      */
374     private boolean handlePlaybackIntent(Intent intent) {
375
376         if (intent == null) {
377             return false;
378         } else if ( !MusicUtils.isPlaybackServiceConnected() ) {
379             mHasPendingPlaybackRequest = true;
380             return false;
381         }
382
383         Uri uri = intent.getData();
384         String mimeType = intent.getType();
385         boolean handled = false;
386
387         if (uri != null && uri.toString().length() > 0) {
388             MusicUtils.playFile(this, uri);
389             handled = true;
390         } else if (MediaStore.Audio.Playlists.CONTENT_TYPE.equals(mimeType)) {
391             long id = parseIdFromIntent(intent, "playlistId", "playlist", -1);
392             if (id >= 0) {
393                 MusicUtils.playPlaylist(this, id, false);
394                 handled = true;
395             }
396         } else if (MediaStore.Audio.Albums.CONTENT_TYPE.equals(mimeType)) {
397             long id = parseIdFromIntent(intent, "albumId", "album", -1);
398             if (id >= 0) {
399                 int position = intent.getIntExtra("position", 0);
400                 MusicUtils.playAlbum(this, id, position, false);
401                 handled = true;
402             }
403         } else if (MediaStore.Audio.Artists.CONTENT_TYPE.equals(mimeType)) {
404             long id = parseIdFromIntent(intent, "artistId", "artist", -1);
405             if (id >= 0) {
406                 int position = intent.getIntExtra("position", 0);
407                 MusicUtils.playArtist(this, id, position, false);
408                 handled = true;
409             }
410         }
411
412         // reset intent as it was handled as a playback request
413         if (handled) {
414             setIntent(new Intent());
415         }
416
417         return handled;
418
419     }
420
421     private long parseIdFromIntent(Intent intent, String longKey,
422                                    String stringKey, long defaultId) {
423         long id = intent.getLongExtra(longKey, -1);
424         if (id < 0) {
425             String idString = intent.getStringExtra(stringKey);
426             if (idString != null) {
427                 try {
428                     id = Long.parseLong(idString);
429                 } catch (NumberFormatException e) {
430                     Log.e(TAG, e.getMessage());
431                 }
432             }
433         }
434         return id;
435     }
436
437     @Override
438     public void onBackStackChanged() {
439         Fragment topFragment = getTopFragment();
440         if (topFragment != null) {
441             // the fragment that has come back to the top should now have its menu items
442             // added to the action bar -- so tell it to make it menu items visible
443             topFragment.setMenuVisibility(true);
444             ISetupActionBar setupActionBar = (ISetupActionBar) topFragment;
445             setupActionBar.setupActionBar();
446
447             getActionBar().setDisplayHomeAsUpEnabled(
448                     !(topFragment instanceof MusicBrowserPhoneFragment));
449         }
450     }
451 }