diff --git a/app/app.iml b/app/app.iml index 2566dab7..c37e4467 100644 --- a/app/app.iml +++ b/app/app.iml @@ -35,10 +35,16 @@ @@ -50,7 +56,6 @@ - @@ -64,7 +69,6 @@ - @@ -148,10 +152,13 @@ + + + @@ -166,7 +173,6 @@ - @@ -189,87 +195,87 @@ - + - - + + + + + + + + - - - - - - - - - - + + + + + + + + + + + - - - - - - - - - + + + + - - - + + - - - - - + + + + + + + + - - - - + + + + - - - - - + + - + + - - - + + - - + + + + + - - - - - - - - + + + - + + - - - - - + + + + + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 6141b996..32115020 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,5 +1,6 @@ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 28 @@ -122,7 +123,7 @@ dependencies { implementation "com.squareup.retrofit2:adapter-rxjava2:2.4.0" implementation "com.jakewharton:butterknife:$butterKnife" - annotationProcessor "com.jakewharton:butterknife-compiler:$butterKnife" + kapt "com.jakewharton:butterknife-compiler:$butterKnife" implementation "com.afollestad.material-dialogs:core:$materialDialog" implementation "com.afollestad.material-dialogs:commons:$materialDialog" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e9ade2f9..ca258b34 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -103,27 +103,19 @@ - - + - - + + --> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/assets/retro-changelog.html b/app/src/main/assets/retro-changelog.html index 5bae13be..281b5626 100644 --- a/app/src/main/assets/retro-changelog.html +++ b/app/src/main/assets/retro-changelog.html @@ -1 +1 @@ -

Are you subscribed to PewDiePie

You can view the changelog dialog again at any time from the about section.

Version 2.2.100

  • Click new music mix to play songs
  • Gradient image option for gird list
  • Clear button for playing queue
  • Click toolbar (Library) to open options
  • Folder list back button
  • New theme Fit
  • On library click on toolbar for accessing main menu
  • On home click on toolbar for accessing search
  • BottomSheetDialogue is now adaptable to screens, background colour and text size consistency.
  • Removed coloured navigation bar option to making app adapt the primary colour
  • Swipe up gesture for now playing removed, replaced with "tap to open", To achieve transparent navigation bar for desired themes.
  • Improved tablet UI and home screen by adding suggestions toggle banner issues.
  • Improving lyrics page

FAQ's

*If you face any UI related issues you clear app data and cache, if its not working try to uninstall and install again.

\ No newline at end of file +

Version 2.2.100

  • Click new music mix to play songs
  • Gradient image option for gird list
  • Clear button for playing queue
  • Click toolbar (Library) to open options
  • Folder list back button
  • New theme Fit
  • On library click on toolbar for accessing main menu
  • On home click on toolbar for accessing search
  • BottomSheetDialogue is now adaptable to screens, background colour and text size consistency.
  • Removed coloured navigation bar option to making app adapt the primary colour
  • Swipe up gesture for now playing removed, replaced with "tap to open", To achieve transparent navigation bar for desired themes.
  • Improved tablet UI and home screen by adding suggestions toggle banner issues.
  • Improving lyrics page

FAQ's

*If you face any UI related issues you clear app data and cache, if its not working try to uninstall and install again.

\ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/Constants.java b/app/src/main/java/code/name/monkey/retromusic/Constants.java deleted file mode 100644 index 529e3d80..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/Constants.java +++ /dev/null @@ -1,42 +0,0 @@ -package code.name.monkey.retromusic; - -public class Constants { - - public static final String DISCORD_LINK = "https://discord.gg/qTecXXn"; - - public static final String RETRO_MUSIC_PACKAGE_NAME = "code.name.monkey.retromusic"; - public static final String MUSIC_PACKAGE_NAME = "com.android.music"; - public static final String ACTION_TOGGLE_PAUSE = RETRO_MUSIC_PACKAGE_NAME + ".togglepause"; - public static final String ACTION_PLAY = RETRO_MUSIC_PACKAGE_NAME + ".play"; - public static final String ACTION_PLAY_PLAYLIST = RETRO_MUSIC_PACKAGE_NAME + ".play.playlist"; - public static final String ACTION_PAUSE = RETRO_MUSIC_PACKAGE_NAME + ".pause"; - public static final String ACTION_STOP = RETRO_MUSIC_PACKAGE_NAME + ".stop"; - public static final String ACTION_SKIP = RETRO_MUSIC_PACKAGE_NAME + ".skip"; - public static final String ACTION_REWIND = RETRO_MUSIC_PACKAGE_NAME + ".rewind"; - public static final String ACTION_QUIT = RETRO_MUSIC_PACKAGE_NAME + ".quitservice"; - public static final String INTENT_EXTRA_PLAYLIST = RETRO_MUSIC_PACKAGE_NAME + "intentextra.playlist"; - public static final String INTENT_EXTRA_SHUFFLE_MODE = RETRO_MUSIC_PACKAGE_NAME + ".intentextra.shufflemode"; - public static final String APP_WIDGET_UPDATE = RETRO_MUSIC_PACKAGE_NAME + ".appwidgetupdate"; - public static final String EXTRA_APP_WIDGET_NAME = RETRO_MUSIC_PACKAGE_NAME + "app_widget_name"; - // do not change these three strings as it will break support with other apps (e.g. last.fm scrobbling) - public static final String META_CHANGED = RETRO_MUSIC_PACKAGE_NAME + ".metachanged"; - public static final String QUEUE_CHANGED = RETRO_MUSIC_PACKAGE_NAME + ".queuechanged"; - public static final String PLAY_STATE_CHANGED = RETRO_MUSIC_PACKAGE_NAME + ".playstatechanged"; - public static final String REPEAT_MODE_CHANGED = RETRO_MUSIC_PACKAGE_NAME + ".repeatmodechanged"; - public static final String SHUFFLE_MODE_CHANGED = RETRO_MUSIC_PACKAGE_NAME + ".shufflemodechanged"; - public static final String MEDIA_STORE_CHANGED = RETRO_MUSIC_PACKAGE_NAME + ".mediastorechanged"; - public static final String RATE_ON_GOOGLE_PLAY = "https://play.google.com/store/apps/details?id=code.name.monkey.retromusic"; - public static final String PAYPAL_ME_URL = "https://www.paypal.me/h4h14"; - public static final String GOOGLE_PLUS_COMMUNITY = "https://plus.google.com/communities/110811566242871492162"; - public static final String TRANSLATE = "http://monkeycodeapp.oneskyapp.com/collaboration/project?id=238534"; - public static final String GITHUB_PROJECT = "https://github.com/h4h13/RetroMusicPlayer"; - public static final String BASE_API_URL_KUGOU = "http://lyrics.kugou.com/"; - public static final String TELEGRAM_CHANGE_LOG = "https://t.me/retromusiclog"; - public static final String USER_PROFILE = "profile.jpg"; - public static final String USER_BANNER = "banner.jpg"; - public static final String APP_INSTAGRAM_LINK = "https://www.instagram.com/retromusicapp/"; - public static final String APP_TELEGRAM_LINK = "https://t.me/retromusicapp/"; - public static final String APP_TWITTER_LINK = "https://twitter.com/retromusicapp"; - public static final String FAQ_LINK = "https://github.com/h4h13/RetroMusicPlayer/blob/master/FAQ.md"; - public static final int CAST_SERVER_PORT = 8080; -} diff --git a/app/src/main/java/code/name/monkey/retromusic/Constants.kt b/app/src/main/java/code/name/monkey/retromusic/Constants.kt new file mode 100644 index 00000000..38f3bfb8 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/Constants.kt @@ -0,0 +1,97 @@ +package code.name.monkey.retromusic + +import android.provider.BaseColumns +import android.provider.MediaStore + +object Constants { + + @JvmField + val DISCORD_LINK = "https://discord.gg/qTecXXn" + + @JvmField + val RETRO_MUSIC_PACKAGE_NAME = "code.name.monkey.retromusic" + @JvmField + val MUSIC_PACKAGE_NAME = "com.android.music" + @JvmField + val ACTION_TOGGLE_PAUSE = "$RETRO_MUSIC_PACKAGE_NAME.togglepause" + @JvmField + val ACTION_PLAY = "$RETRO_MUSIC_PACKAGE_NAME.play" + @JvmField + val ACTION_PLAY_PLAYLIST = "$RETRO_MUSIC_PACKAGE_NAME.play.playlist" + @JvmField + val ACTION_PAUSE = "$RETRO_MUSIC_PACKAGE_NAME.pause" + @JvmField + val ACTION_STOP = "$RETRO_MUSIC_PACKAGE_NAME.stop" + @JvmField + val ACTION_SKIP = "$RETRO_MUSIC_PACKAGE_NAME.skip" + @JvmField + val ACTION_REWIND = "$RETRO_MUSIC_PACKAGE_NAME.rewind" + @JvmField + val ACTION_QUIT = "$RETRO_MUSIC_PACKAGE_NAME.quitservice" + @JvmField + val INTENT_EXTRA_PLAYLIST = RETRO_MUSIC_PACKAGE_NAME + "intentextra.playlist" + @JvmField + val INTENT_EXTRA_SHUFFLE_MODE = "$RETRO_MUSIC_PACKAGE_NAME.intentextra.shufflemode" + @JvmField + val APP_WIDGET_UPDATE = "$RETRO_MUSIC_PACKAGE_NAME.appwidgetupdate" + @JvmField + val EXTRA_APP_WIDGET_NAME = RETRO_MUSIC_PACKAGE_NAME + "app_widget_name" + + @JvmField + val META_CHANGED = "$RETRO_MUSIC_PACKAGE_NAME.metachanged" + @JvmField + val QUEUE_CHANGED = "$RETRO_MUSIC_PACKAGE_NAME.queuechanged" + @JvmField + val PLAY_STATE_CHANGED = "$RETRO_MUSIC_PACKAGE_NAME.playstatechanged" + @JvmField + val REPEAT_MODE_CHANGED = "$RETRO_MUSIC_PACKAGE_NAME.repeatmodechanged" + @JvmField + val SHUFFLE_MODE_CHANGED = "$RETRO_MUSIC_PACKAGE_NAME.shufflemodechanged" + @JvmField + val MEDIA_STORE_CHANGED = "$RETRO_MUSIC_PACKAGE_NAME.mediastorechanged" + @JvmField + val RATE_ON_GOOGLE_PLAY = "https://play.google.com/store/apps/details?id=code.name.monkey.retromusic" + @JvmField + val PAYPAL_ME_URL = "https://www.paypal.me/h4h14" + @JvmField + val GOOGLE_PLUS_COMMUNITY = "https://plus.google.com/communities/110811566242871492162" + @JvmField + val TRANSLATE = "http://monkeycodeapp.oneskyapp.com/collaboration/project?id=238534" + @JvmField + val GITHUB_PROJECT = "https://github.com/h4h13/RetroMusicPlayer" + @JvmField + val BASE_API_URL_KUGOU = "http://lyrics.kugou.com/" + @JvmField + val TELEGRAM_CHANGE_LOG = "https://t.me/retromusiclog" + @JvmField + val USER_PROFILE = "profile.jpg" + @JvmField + val USER_BANNER = "banner.jpg" + @JvmField + val APP_INSTAGRAM_LINK = "https://www.instagram.com/retromusicapp/" + @JvmField + val APP_TELEGRAM_LINK = "https://t.me/retromusicapp/" + @JvmField + val APP_TWITTER_LINK = "https://twitter.com/retromusicapp" + @JvmField + val FAQ_LINK = "https://github.com/h4h13/RetroMusicPlayer/blob/master/FAQ.md" + @JvmField + val CAST_SERVER_PORT = 8080 + + const val BASE_SELECTION = MediaStore.Audio.AudioColumns.IS_MUSIC + "=1" + " AND " + MediaStore.Audio.AudioColumns.TITLE + " != ''" + @JvmField + val BASE_PROJECTION = arrayOf(BaseColumns._ID, // 0 + MediaStore.Audio.AudioColumns.TITLE, // 1 + MediaStore.Audio.AudioColumns.TRACK, // 2 + MediaStore.Audio.AudioColumns.YEAR, // 3 + MediaStore.Audio.AudioColumns.DURATION, // 4 + MediaStore.Audio.AudioColumns.DATA, // 5 + MediaStore.Audio.AudioColumns.DATE_MODIFIED, // 6 + MediaStore.Audio.AudioColumns.ALBUM_ID, // 7 + MediaStore.Audio.AudioColumns.ALBUM, // 8 + MediaStore.Audio.AudioColumns.ARTIST_ID, // 9 + MediaStore.Audio.AudioColumns.ARTIST)// 10 + const val NUMBER_OF_TOP_TRACKS = 99 + + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/Injection.java b/app/src/main/java/code/name/monkey/retromusic/Injection.java deleted file mode 100644 index 4fe94a74..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/Injection.java +++ /dev/null @@ -1,23 +0,0 @@ -package code.name.monkey.retromusic; - -import code.name.monkey.retromusic.providers.RepositoryImpl; -import code.name.monkey.retromusic.providers.interfaces.Repository; -import code.name.monkey.retromusic.rest.KogouClient; -import code.name.monkey.retromusic.rest.service.KuGouApiService; -import code.name.monkey.retromusic.util.schedulers.BaseSchedulerProvider; -import code.name.monkey.retromusic.util.schedulers.SchedulerProvider; - -public class Injection { - - public static Repository provideRepository() { - return RepositoryImpl.getInstance(); - } - - public static BaseSchedulerProvider provideSchedulerProvider() { - return SchedulerProvider.getInstance(); - } - - public static KuGouApiService provideKuGouApiService() { - return new KogouClient().getApiService(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/Injection.kt b/app/src/main/java/code/name/monkey/retromusic/Injection.kt new file mode 100644 index 00000000..349d029f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/Injection.kt @@ -0,0 +1,23 @@ +package code.name.monkey.retromusic + +import code.name.monkey.retromusic.providers.RepositoryImpl +import code.name.monkey.retromusic.providers.interfaces.Repository +import code.name.monkey.retromusic.rest.KogouClient +import code.name.monkey.retromusic.rest.service.KuGouApiService +import code.name.monkey.retromusic.util.schedulers.BaseSchedulerProvider +import code.name.monkey.retromusic.util.schedulers.SchedulerProvider + +object Injection { + + fun provideRepository(): Repository { + return RepositoryImpl.getInstance() + } + + fun provideSchedulerProvider(): BaseSchedulerProvider { + return SchedulerProvider.getInstance() + } + + fun provideKuGouApiService(): KuGouApiService { + return KogouClient().apiService + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/RetroApplication.java b/app/src/main/java/code/name/monkey/retromusic/RetroApplication.java deleted file mode 100644 index 8e75f135..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/RetroApplication.java +++ /dev/null @@ -1,125 +0,0 @@ -package code.name.monkey.retromusic; - -import android.content.Context; -import android.os.Build; - -import com.anjlab.android.iab.v3.BillingProcessor; -import com.anjlab.android.iab.v3.TransactionDetails; -import com.bumptech.glide.Glide; - -import androidx.annotation.NonNull; -import androidx.multidex.MultiDexApplication; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.appshortcuts.DynamicShortcutManager; -import uk.co.chrisjenx.calligraphy.CalligraphyConfig; - -public class RetroApplication extends MultiDexApplication { - - public static final String PRO_VERSION_PRODUCT_ID = "pro_version"; - - private static RetroApplication app; - - private BillingProcessor billingProcessor; - - public static RetroApplication getInstance() { - return app; - } - - public static Context getContext() { - return app.getApplicationContext(); - } - - public static boolean isProVersion() { - return BuildConfig.DEBUG || app.billingProcessor.isPurchased(PRO_VERSION_PRODUCT_ID); - } - - public static void deleteAppData() { - try { - // clearing app data - String packageName = app.getPackageName(); - Runtime runtime = Runtime.getRuntime(); - runtime.exec("pm clear " + packageName); - - System.exit(0); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void onCreate() { - super.onCreate(); - app = this; - - setupErrorHandler(); - - // default theme - if (!ThemeStore.isConfigured(this, 3)) { - ThemeStore.editTheme(this) - .accentColorRes(R.color.md_green_A200) - .coloredNavigationBar(true) - .commit(); - } - - CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() - .setDefaultFontPath("fonts/circular_std_book.otf") - .setFontAttrId(R.attr.fontPath) - .build() - ); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { - new DynamicShortcutManager(this).initDynamicShortcuts(); - } - - // automatically restores purchases - billingProcessor = new BillingProcessor(this, BuildConfig.GOOGLE_PLAY_LICENSE_KEY, - new BillingProcessor.IBillingHandler() { - @Override - public void onProductPurchased(@NonNull String productId, TransactionDetails details) { - } - - @Override - public void onPurchaseHistoryRestored() { - //Toast.makeText(App.this, R.string.restored_previous_purchase_please_restart, Toast.LENGTH_LONG).show(); - } - - @Override - public void onBillingError(int errorCode, Throwable error) { - } - - @Override - public void onBillingInitialized() { - } - }); - } - - private void setupErrorHandler() { - Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { - @Override - public void uncaughtException(Thread thread, Throwable throwable) { - handleUncaughtException(thread, throwable); - } - }); - } - - private void handleUncaughtException(Thread thread, Throwable throwable) { - throwable.printStackTrace(); - deleteAppData(); - //Intent intent = new Intent(this, ErrorHandlerActivity.class); - //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - //startActivity(intent); - } - - @Override - public void onLowMemory() { - super.onLowMemory(); - Glide.with(this).onLowMemory(); - } - - @Override - public void onTerminate() { - super.onTerminate(); - billingProcessor.release(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/RetroApplication.kt b/app/src/main/java/code/name/monkey/retromusic/RetroApplication.kt new file mode 100644 index 00000000..176e6a03 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/RetroApplication.kt @@ -0,0 +1,94 @@ +package code.name.monkey.retromusic + +import android.content.Context +import androidx.multidex.MultiDexApplication +import code.name.monkey.appthemehelper.ThemeStore +import com.anjlab.android.iab.v3.BillingProcessor +import com.anjlab.android.iab.v3.TransactionDetails +import com.bumptech.glide.Glide +import uk.co.chrisjenx.calligraphy.CalligraphyConfig + +class RetroApplication : MultiDexApplication() { + + lateinit var billingProcessor: BillingProcessor + + override fun onCreate() { + super.onCreate() + instance = this + + setupErrorHandler() + + // default theme + if (!ThemeStore.isConfigured(this, 3)) { + ThemeStore.editTheme(this) + .accentColorRes(R.color.md_green_A200) + .coloredNavigationBar(true) + .commit() + } + + // automatically restores purchases + billingProcessor = BillingProcessor(this, BuildConfig.GOOGLE_PLAY_LICENSE_KEY, + object : BillingProcessor.IBillingHandler { + override fun onProductPurchased(productId: String, details: TransactionDetails?) {} + + override fun onPurchaseHistoryRestored() { + //Toast.makeText(App.this, R.string.restored_previous_purchase_please_restart, Toast.LENGTH_LONG).show(); + } + + override fun onBillingError(errorCode: Int, error: Throwable?) {} + + override fun onBillingInitialized() {} + }) + } + + private fun setupErrorHandler() { + Thread.setDefaultUncaughtExceptionHandler { _, throwable -> handleUncaughtException(throwable) } + } + + private fun handleUncaughtException(throwable: Throwable) { + throwable.printStackTrace() + deleteAppData() + //Intent intent = new Intent(this, ErrorHandlerActivity.class); + //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + //startActivity(intent); + } + + override fun onLowMemory() { + super.onLowMemory() + Glide.with(this).onLowMemory() + } + + override fun onTerminate() { + super.onTerminate() + billingProcessor.release() + } + + companion object { + + const val PRO_VERSION_PRODUCT_ID = "pro_version" + + lateinit var instance: RetroApplication + private set + + val context: Context + get() = instance.applicationContext + + val isProVersion: Boolean + get() = BuildConfig.DEBUG || instance.billingProcessor.isPurchased(PRO_VERSION_PRODUCT_ID) + + fun deleteAppData() { + try { + // clearing app data + val packageName = instance.packageName + val runtime = Runtime.getRuntime() + runtime.exec("pm clear $packageName") + + System.exit(0) + + } catch (e: Exception) { + e.printStackTrace() + } + + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/AppShortcutIconGenerator.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/AppShortcutIconGenerator.java deleted file mode 100644 index 40db1bfc..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/AppShortcutIconGenerator.java +++ /dev/null @@ -1,71 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.drawable.Drawable; -import android.graphics.drawable.Icon; -import android.graphics.drawable.LayerDrawable; -import android.os.Build; -import androidx.annotation.RequiresApi; -import android.util.TypedValue; - -import code.name.monkey.appthemehelper.ThemeStore; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; - -/** - * @author Adrian Campos - */ -@RequiresApi(Build.VERSION_CODES.N_MR1) -public final class AppShortcutIconGenerator { - public static Icon generateThemedIcon(Context context, int iconId) { - if (PreferenceUtil.getInstance().coloredAppShortcuts()){ - return generateUserThemedIcon(context, iconId); - } else { - return generateDefaultThemedIcon(context, iconId); - } - } - - private static Icon generateDefaultThemedIcon(Context context, int iconId) { - // Return an Icon of iconId with default colors - return generateThemedIcon(context, iconId, - context.getColor(R.color.app_shortcut_default_foreground), - context.getColor(R.color.app_shortcut_default_background) - ); - } - - private static Icon generateUserThemedIcon(Context context, int iconId) { - // Get background color from context's theme - final TypedValue typedColorBackground = new TypedValue(); - context.getTheme().resolveAttribute(android.R.attr.colorBackground, typedColorBackground, true); - - // Return an Icon of iconId with those colors - return generateThemedIcon(context, iconId, - ThemeStore.accentColor(context), - typedColorBackground.data - ); - } - - private static Icon generateThemedIcon(Context context, int iconId, int foregroundColor, int backgroundColor) { - // Get and tint foreground and background drawables - Drawable vectorDrawable = RetroUtil.getTintedVectorDrawable(context, iconId, foregroundColor); - Drawable backgroundDrawable = RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_app_shortcut_background, backgroundColor); - - // Squash the two drawables together - LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{backgroundDrawable, vectorDrawable}); - - // Return as an Icon - return Icon.createWithBitmap(drawableToBitmap(layerDrawable)); - } - - private static Bitmap drawableToBitmap(Drawable drawable) { - Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(bitmap); - drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); - drawable.draw(canvas); - return bitmap; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/AppShortcutLauncherActivity.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/AppShortcutLauncherActivity.java deleted file mode 100644 index 85e9c402..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/AppShortcutLauncherActivity.java +++ /dev/null @@ -1,77 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; - -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.MyTopTracksPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.ShuffleAllPlaylist; - -import code.name.monkey.retromusic.appshortcuts.shortcuttype.LastAddedShortcutType; -import code.name.monkey.retromusic.appshortcuts.shortcuttype.ShuffleAllShortcutType; -import code.name.monkey.retromusic.appshortcuts.shortcuttype.TopTracksShortcutType; -import code.name.monkey.retromusic.service.MusicService; - -import static code.name.monkey.retromusic.Constants.*; - -/** - * @author Adrian Campos - */ - -public class AppShortcutLauncherActivity extends Activity { - public static final String KEY_SHORTCUT_TYPE = "code.name.monkey.retromusic.appshortcuts.ShortcutType"; - - public static final int SHORTCUT_TYPE_SHUFFLE_ALL = 0; - public static final int SHORTCUT_TYPE_TOP_TRACKS = 1; - public static final int SHORTCUT_TYPE_LAST_ADDED = 2; - public static final int SHORTCUT_TYPE_NONE = 3; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - int shortcutType = SHORTCUT_TYPE_NONE; - - // Set shortcutType from the intent extras - Bundle extras = getIntent().getExtras(); - if (extras != null) { - //noinspection WrongConstant - shortcutType = extras.getInt(KEY_SHORTCUT_TYPE, SHORTCUT_TYPE_NONE); - } - - switch (shortcutType) { - case SHORTCUT_TYPE_SHUFFLE_ALL: - startServiceWithPlaylist(MusicService.SHUFFLE_MODE_SHUFFLE, - new ShuffleAllPlaylist(getApplicationContext())); - DynamicShortcutManager.reportShortcutUsed(this, ShuffleAllShortcutType.getId()); - break; - case SHORTCUT_TYPE_TOP_TRACKS: - startServiceWithPlaylist(MusicService.SHUFFLE_MODE_NONE, - new MyTopTracksPlaylist(getApplicationContext())); - DynamicShortcutManager.reportShortcutUsed(this, TopTracksShortcutType.getId()); - break; - case SHORTCUT_TYPE_LAST_ADDED: - startServiceWithPlaylist(MusicService.SHUFFLE_MODE_NONE, - new LastAddedPlaylist(getApplicationContext())); - DynamicShortcutManager.reportShortcutUsed(this, LastAddedShortcutType.getId()); - break; - } - - finish(); - } - - private void startServiceWithPlaylist(int shuffleMode, Playlist playlist) { - Intent intent = new Intent(this, MusicService.class); - intent.setAction(ACTION_PLAY_PLAYLIST); - - Bundle bundle = new Bundle(); - bundle.putParcelable(INTENT_EXTRA_PLAYLIST, playlist); - bundle.putInt(INTENT_EXTRA_SHUFFLE_MODE, shuffleMode); - - intent.putExtras(bundle); - - startService(intent); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/DynamicShortcutManager.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/DynamicShortcutManager.java deleted file mode 100644 index 5fb28054..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/DynamicShortcutManager.java +++ /dev/null @@ -1,63 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ShortcutInfo; -import android.content.pm.ShortcutManager; -import android.graphics.drawable.Icon; -import android.os.Build; - -import code.name.monkey.retromusic.appshortcuts.shortcuttype.LastAddedShortcutType; -import code.name.monkey.retromusic.appshortcuts.shortcuttype.ShuffleAllShortcutType; -import code.name.monkey.retromusic.appshortcuts.shortcuttype.TopTracksShortcutType; - -import java.util.Arrays; -import java.util.List; - -/** - * @author Adrian Campos - */ - -@TargetApi(Build.VERSION_CODES.N_MR1) -public class DynamicShortcutManager { - - private Context context; - private ShortcutManager shortcutManager; - - public DynamicShortcutManager(Context context) { - this.context = context; - shortcutManager = this.context.getSystemService(ShortcutManager.class); - } - - public static ShortcutInfo createShortcut(Context context, String id, String shortLabel, String longLabel, Icon icon, Intent intent) { - return new ShortcutInfo.Builder(context, id) - .setShortLabel(shortLabel) - .setLongLabel(longLabel) - .setIcon(icon) - .setIntent(intent) - .build(); - } - - public void initDynamicShortcuts() { - if (shortcutManager.getDynamicShortcuts().size() == 0) { - shortcutManager.setDynamicShortcuts(getDefaultShortcuts()); - } - } - - public void updateDynamicShortcuts() { - shortcutManager.updateShortcuts(getDefaultShortcuts()); - } - - public List getDefaultShortcuts() { - return (Arrays.asList( - new ShuffleAllShortcutType(context).getShortcutInfo(), - new TopTracksShortcutType(context).getShortcutInfo(), - new LastAddedShortcutType(context).getShortcutInfo() - )); - } - - public static void reportShortcutUsed(Context context, String shortcutId){ - context.getSystemService(ShortcutManager.class).reportShortcutUsed(shortcutId); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/BaseShortcutType.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/BaseShortcutType.java deleted file mode 100644 index 28f16a7e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/BaseShortcutType.java +++ /dev/null @@ -1,50 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts.shortcuttype; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.Intent; -import android.content.pm.ShortcutInfo; -import android.os.Build; -import android.os.Bundle; - -import code.name.monkey.retromusic.appshortcuts.AppShortcutLauncherActivity; - - -/** - * @author Adrian Campos - */ -@TargetApi(Build.VERSION_CODES.N_MR1) -public abstract class BaseShortcutType { - - static final String ID_PREFIX = "code.name.monkey.retromusic.appshortcuts.id."; - - Context context; - - public BaseShortcutType(Context context) { - this.context = context; - } - - static public String getId() { - return ID_PREFIX + "invalid"; - } - - abstract ShortcutInfo getShortcutInfo(); - - /** - * Creates an Intent that will launch MainActivtiy and immediately play {@param songs} in either shuffle or normal mode - * - * @param shortcutType Describes the type of shortcut to create (ShuffleAll, TopTracks, custom playlist, etc.) - * @return - */ - Intent getPlaySongsIntent(int shortcutType) { - Intent intent = new Intent(context, AppShortcutLauncherActivity.class); - intent.setAction(Intent.ACTION_VIEW); - - Bundle b = new Bundle(); - b.putInt(AppShortcutLauncherActivity.KEY_SHORTCUT_TYPE, shortcutType); - - intent.putExtras(b); - - return intent; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/LastAddedShortcutType.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/LastAddedShortcutType.java deleted file mode 100644 index 72db3eeb..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/LastAddedShortcutType.java +++ /dev/null @@ -1,34 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts.shortcuttype; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.pm.ShortcutInfo; -import android.os.Build; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appshortcuts.AppShortcutIconGenerator; -import code.name.monkey.retromusic.appshortcuts.AppShortcutLauncherActivity; - - -/** - * @author Adrian Campos - */ -@TargetApi(Build.VERSION_CODES.N_MR1) -public final class LastAddedShortcutType extends BaseShortcutType { - public LastAddedShortcutType(Context context) { - super(context); - } - - public static String getId() { - return ID_PREFIX + "last_added"; - } - - public ShortcutInfo getShortcutInfo() { - return new ShortcutInfo.Builder(context, getId()) - .setShortLabel(context.getString(R.string.app_shortcut_last_added_short)) - .setLongLabel(context.getString(R.string.app_shortcut_last_added_long)) - .setIcon(AppShortcutIconGenerator.generateThemedIcon(context, R.drawable.ic_app_shortcut_last_added)) - .setIntent(getPlaySongsIntent(AppShortcutLauncherActivity.SHORTCUT_TYPE_LAST_ADDED)) - .build(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/ShuffleAllShortcutType.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/ShuffleAllShortcutType.java deleted file mode 100644 index be3ba008..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/ShuffleAllShortcutType.java +++ /dev/null @@ -1,35 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts.shortcuttype; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.pm.ShortcutInfo; -import android.os.Build; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appshortcuts.AppShortcutIconGenerator; -import code.name.monkey.retromusic.appshortcuts.AppShortcutLauncherActivity; - - - -/** - * @author Adrian Campos - */ -@TargetApi(Build.VERSION_CODES.N_MR1) -public final class ShuffleAllShortcutType extends BaseShortcutType { - public ShuffleAllShortcutType(Context context) { - super(context); - } - - public static String getId() { - return ID_PREFIX + "shuffle_all"; - } - - public ShortcutInfo getShortcutInfo() { - return new ShortcutInfo.Builder(context, getId()) - .setShortLabel(context.getString(R.string.app_shortcut_shuffle_all_short)) - .setLongLabel(context.getString(R.string.app_shortcut_shuffle_all_long)) - .setIcon(AppShortcutIconGenerator.generateThemedIcon(context, R.drawable.ic_app_shortcut_shuffle_all)) - .setIntent(getPlaySongsIntent(AppShortcutLauncherActivity.SHORTCUT_TYPE_SHUFFLE_ALL)) - .build(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/TopTracksShortcutType.java b/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/TopTracksShortcutType.java deleted file mode 100644 index 3e78db33..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appshortcuts/shortcuttype/TopTracksShortcutType.java +++ /dev/null @@ -1,35 +0,0 @@ -package code.name.monkey.retromusic.appshortcuts.shortcuttype; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.pm.ShortcutInfo; -import android.os.Build; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appshortcuts.AppShortcutIconGenerator; -import code.name.monkey.retromusic.appshortcuts.AppShortcutLauncherActivity; - - - -/** - * @author Adrian Campos - */ -@TargetApi(Build.VERSION_CODES.N_MR1) -public final class TopTracksShortcutType extends BaseShortcutType { - public TopTracksShortcutType(Context context) { - super(context); - } - - public static String getId() { - return ID_PREFIX + "top_tracks"; - } - - public ShortcutInfo getShortcutInfo() { - return new ShortcutInfo.Builder(context, getId()) - .setShortLabel(context.getString(R.string.app_shortcut_top_tracks_short)) - .setLongLabel(context.getString(R.string.app_shortcut_top_tracks_long)) - .setIcon(AppShortcutIconGenerator.generateThemedIcon(context, R.drawable.ic_app_shortcut_top_tracks)) - .setIntent(getPlaySongsIntent(AppShortcutLauncherActivity.SHORTCUT_TYPE_TOP_TRACKS)) - .build(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetBig.java b/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetBig.java deleted file mode 100644 index 11145dbd..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetBig.java +++ /dev/null @@ -1,174 +0,0 @@ -package code.name.monkey.retromusic.appwidgets; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.Point; -import android.graphics.drawable.Drawable; -import android.text.TextUtils; -import android.view.View; -import android.widget.RemoteViews; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; -import com.bumptech.glide.request.target.Target; - -import androidx.annotation.Nullable; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.Constants; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appwidgets.base.BaseAppWidget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.MainActivity; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; -import code.name.monkey.retromusic.util.RetroUtil; - -public class AppWidgetBig extends BaseAppWidget { - - public static final String NAME = "app_widget_big"; - - private static AppWidgetBig mInstance; - private Target target; // for cancellation - - public static synchronized AppWidgetBig getInstance() { - if (mInstance == null) { - mInstance = new AppWidgetBig(); - } - return mInstance; - } - - /** - * Initialize given widgets to default state, where we launch Music on default click and hide - * actions if service not running. - */ - protected void defaultAppWidget(final Context context, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(context.getPackageName(), - R.layout.app_widget_big); - - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - appWidgetView.setImageViewResource(R.id.image, R.drawable.default_album_art); - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_next_white_24dp, - MaterialValueHelper.getPrimaryTextColor(context, false)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_previous_white_24dp, - MaterialValueHelper.getPrimaryTextColor(context, false)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_play_arrow_white_24dp, - MaterialValueHelper.getPrimaryTextColor(context, false)), 1f)); - - linkButtons(context, appWidgetView); - pushUpdate(context, appWidgetIds, appWidgetView); - } - - /** - * Update all active widget instances by pushing changes - */ - public void performUpdate(final MusicService service, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(service.getPackageName(), - R.layout.app_widget_big); - - final boolean isPlaying = service.isPlaying(); - final Song song = service.getCurrentSong(); - - // Set the titles and artwork - if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName)) { - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - } else { - appWidgetView.setViewVisibility(R.id.media_titles, View.VISIBLE); - appWidgetView.setTextViewText(R.id.title, song.title); - appWidgetView.setTextViewText(R.id.text, getSongArtistAndAlbum(song)); - } - - // Set correct drawable for pause state - int playPauseRes = - isPlaying ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp; - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, createBitmap( - RetroUtil.getTintedVectorDrawable(service, playPauseRes, - MaterialValueHelper.getPrimaryTextColor(service, false)), 1f)); - - // Set prev/next button drawables - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - MaterialValueHelper.getPrimaryTextColor(service, false)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - MaterialValueHelper.getPrimaryTextColor(service, false)), 1f)); - - // Link actions buttons to intents - linkButtons(service, appWidgetView); - - // Load the album cover async and push the update on completion - Point p = RetroUtil.getScreenSize(service); - final int widgetImageSize = Math.min(p.x, p.y); - final Context appContext = service.getApplicationContext(); - service.runOnUiThread(new Runnable() { - @Override - public void run() { - if (target != null) { - Glide.clear(target); - } - target = SongGlideRequest.Builder.from(Glide.with(appContext), song) - .checkIgnoreMediaStore(appContext) - .asBitmap().build() - .into(new SimpleTarget(widgetImageSize, widgetImageSize) { - @Override - public void onResourceReady(Bitmap resource, - GlideAnimation glideAnimation) { - update(resource); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - update(null); - } - - private void update(@Nullable Bitmap bitmap) { - if (bitmap == null) { - appWidgetView.setImageViewResource(R.id.image, R.drawable.default_album_art); - } else { - appWidgetView.setImageViewBitmap(R.id.image, bitmap); - } - pushUpdate(appContext, appWidgetIds, appWidgetView); - } - }); - } - }); - } - - /** - * Link up various button actions using {@link PendingIntent}. - */ - private void linkButtons(final Context context, final RemoteViews views) { - Intent action; - PendingIntent pendingIntent; - - final ComponentName serviceName = new ComponentName(context, MusicService.class); - - // Home - action = new Intent(context, NowPayingActivity.class); - action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - pendingIntent = PendingIntent.getActivity(context, 0, action, 0); - views.setOnClickPendingIntent(R.id.clickable_area, pendingIntent); - - // Previous track - pendingIntent = buildPendingIntent(context, Constants.ACTION_REWIND, serviceName); - views.setOnClickPendingIntent(R.id.button_prev, pendingIntent); - - // Play and pause - pendingIntent = buildPendingIntent(context, Constants.ACTION_TOGGLE_PAUSE, serviceName); - views.setOnClickPendingIntent(R.id.button_toggle_play_pause, pendingIntent); - - // Next track - pendingIntent = buildPendingIntent(context, Constants.ACTION_SKIP, serviceName); - views.setOnClickPendingIntent(R.id.button_next, pendingIntent); - - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetCard.java b/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetCard.java deleted file mode 100644 index f995c47f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetCard.java +++ /dev/null @@ -1,197 +0,0 @@ -package code.name.monkey.retromusic.appwidgets; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import android.text.TextUtils; -import android.view.View; -import android.widget.RemoteViews; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; -import com.bumptech.glide.request.target.Target; - -import androidx.annotation.Nullable; -import androidx.palette.graphics.Palette; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.Constants; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appwidgets.base.BaseAppWidget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.MainActivity; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; -import code.name.monkey.retromusic.util.RetroUtil; - -public class AppWidgetCard extends BaseAppWidget { - - public static final String NAME = "app_widget_card"; - - private static AppWidgetCard mInstance; - private static int imageSize = 0; - private static float cardRadius = 0f; - private Target target; // for cancellation - - public static synchronized AppWidgetCard getInstance() { - if (mInstance == null) { - mInstance = new AppWidgetCard(); - } - return mInstance; - } - - /** - * Initialize given widgets to default state, where we launch Music on default click and hide - * actions if service not running. - */ - protected void defaultAppWidget(final Context context, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(context.getPackageName(), - R.layout.app_widget_card); - - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - appWidgetView.setImageViewResource(R.id.image, R.drawable.default_album_art); - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_next_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_previous_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_play_arrow_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - - linkButtons(context, appWidgetView); - pushUpdate(context, appWidgetIds, appWidgetView); - } - - /** - * Update all active widget instances by pushing changes - */ - public void performUpdate(final MusicService service, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(service.getPackageName(), - R.layout.app_widget_card); - - final boolean isPlaying = service.isPlaying(); - final Song song = service.getCurrentSong(); - - // Set the titles and artwork - if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName)) { - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - } else { - appWidgetView.setViewVisibility(R.id.media_titles, View.VISIBLE); - appWidgetView.setTextViewText(R.id.title, song.title); - appWidgetView.setTextViewText(R.id.text, getSongArtistAndAlbum(song)); - } - - // Set correct drawable for pause state - int playPauseRes = - isPlaying ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp; - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, createBitmap( - RetroUtil.getTintedVectorDrawable(service, playPauseRes, - MaterialValueHelper.getSecondaryTextColor(service, true)), 1f)); - - // Set prev/next button drawables - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - MaterialValueHelper.getSecondaryTextColor(service, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - MaterialValueHelper.getSecondaryTextColor(service, true)), 1f)); - - // Link actions buttons to intents - linkButtons(service, appWidgetView); - - if (imageSize == 0) { - imageSize = service.getResources().getDimensionPixelSize(R.dimen.app_widget_card_image_size); - } - if (cardRadius == 0f) { - cardRadius = service.getResources().getDimension(R.dimen.app_widget_card_radius); - } - - // Load the album cover async and push the update on completion - service.runOnUiThread(new Runnable() { - @Override - public void run() { - if (target != null) { - Glide.clear(target); - } - target = SongGlideRequest.Builder.from(Glide.with(service), song) - .checkIgnoreMediaStore(service) - .generatePalette(service).build() - .centerCrop() - .into(new SimpleTarget(imageSize, imageSize) { - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - Palette palette = resource.getPalette(); - update(resource.getBitmap(), palette.getVibrantColor(palette - .getMutedColor(MaterialValueHelper.getSecondaryTextColor(service, true)))); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - update(null, MaterialValueHelper.getSecondaryTextColor(service, true)); - } - - private void update(@Nullable Bitmap bitmap, int color) { - // Set correct drawable for pause state - int playPauseRes = isPlaying ? R.drawable.ic_pause_white_24dp - : R.drawable.ic_play_arrow_white_24dp; - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, - createBitmap(RetroUtil.getTintedVectorDrawable(service, playPauseRes, color), 1f)); - - // Set prev/next button drawables - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - color), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - color), 1f)); - - final Drawable image = getAlbumArtDrawable(service.getResources(), bitmap); - final Bitmap roundedBitmap = createRoundedBitmap(image, imageSize, imageSize, - cardRadius, 0, cardRadius, 0); - appWidgetView.setImageViewBitmap(R.id.image, roundedBitmap); - - pushUpdate(service, appWidgetIds, appWidgetView); - } - }); - } - }); - } - - /** - * Link up various button actions using {@link PendingIntent}. - */ - private void linkButtons(final Context context, final RemoteViews views) { - Intent action; - PendingIntent pendingIntent; - - final ComponentName serviceName = new ComponentName(context, MusicService.class); - - // Home - action = new Intent(context, NowPayingActivity.class); - action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - pendingIntent = PendingIntent.getActivity(context, 0, action, 0); - views.setOnClickPendingIntent(R.id.image, pendingIntent); - views.setOnClickPendingIntent(R.id.media_titles, pendingIntent); - - // Previous track - pendingIntent = buildPendingIntent(context, Constants.ACTION_REWIND, serviceName); - views.setOnClickPendingIntent(R.id.button_prev, pendingIntent); - - // Play and pause - pendingIntent = buildPendingIntent(context, Constants.ACTION_TOGGLE_PAUSE, serviceName); - views.setOnClickPendingIntent(R.id.button_toggle_play_pause, pendingIntent); - - // Next track - pendingIntent = buildPendingIntent(context, Constants.ACTION_SKIP, serviceName); - views.setOnClickPendingIntent(R.id.button_next, pendingIntent); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetClassic.java b/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetClassic.java deleted file mode 100644 index 9d8afa32..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetClassic.java +++ /dev/null @@ -1,182 +0,0 @@ -package code.name.monkey.retromusic.appwidgets; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import androidx.annotation.Nullable; -import androidx.palette.graphics.Palette; -import android.text.TextUtils; -import android.view.View; -import android.widget.RemoteViews; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.Constants; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appwidgets.base.BaseAppWidget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.MainActivity; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; -import code.name.monkey.retromusic.util.RetroUtil; -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; -import com.bumptech.glide.request.target.Target; - -public class AppWidgetClassic extends BaseAppWidget { - - public static final String NAME = "app_widget_classic"; - - private static AppWidgetClassic mInstance; - private static int imageSize = 0; - private static float cardRadius = 0f; - private Target target; // for cancellation - - public static synchronized AppWidgetClassic getInstance() { - if (mInstance == null) { - mInstance = new AppWidgetClassic(); - } - return mInstance; - } - - /** - * Initialize given widgets to default state, where we launch Music on default click and hide - * actions if service not running. - */ - protected void defaultAppWidget(final Context context, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(context.getPackageName(), - R.layout.app_widget_classic); - - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - appWidgetView.setImageViewResource(R.id.image, R.drawable.default_album_art); - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_next_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_previous_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_play_arrow_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - - linkButtons(context, appWidgetView); - pushUpdate(context, appWidgetIds, appWidgetView); - } - - /** - * Update all active widget instances by pushing changes - */ - public void performUpdate(final MusicService service, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(service.getPackageName(), - R.layout.app_widget_classic); - - final boolean isPlaying = service.isPlaying(); - final Song song = service.getCurrentSong(); - - // Set the titles and artwork - if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName)) { - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - } else { - appWidgetView.setViewVisibility(R.id.media_titles, View.VISIBLE); - appWidgetView.setTextViewText(R.id.title, song.title); - appWidgetView.setTextViewText(R.id.text, getSongArtistAndAlbum(song)); - } - - // Link actions buttons to intents - linkButtons(service, appWidgetView); - - if (imageSize == 0) { - imageSize = service.getResources() - .getDimensionPixelSize(R.dimen.app_widget_classic_image_size); - } - if (cardRadius == 0f) { - cardRadius = service.getResources().getDimension(R.dimen.app_widget_card_radius); - } - - // Load the album cover async and push the update on completion - final Context appContext = service.getApplicationContext(); - service.runOnUiThread(new Runnable() { - @Override - public void run() { - if (target != null) { - Glide.clear(target); - } - target = SongGlideRequest.Builder.from(Glide.with(appContext), song) - .checkIgnoreMediaStore(appContext) - .generatePalette(service).build() - .centerCrop() - .into(new SimpleTarget(imageSize, imageSize) { - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - Palette palette = resource.getPalette(); - update(resource.getBitmap(), palette.getVibrantColor(palette - .getMutedColor(MaterialValueHelper.getSecondaryTextColor(appContext, true)))); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - update(null, MaterialValueHelper.getSecondaryTextColor(appContext, true)); - } - - private void update(@Nullable Bitmap bitmap, int color) { - // Set correct drawable for pause state - int playPauseRes = isPlaying ? R.drawable.ic_pause_white_24dp - : R.drawable.ic_play_arrow_white_24dp; - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, - createBitmap(RetroUtil.getTintedVectorDrawable(service, playPauseRes, color), 1f)); - - // Set prev/next button drawables - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - color), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - color), 1f)); - - final Drawable image = getAlbumArtDrawable(service.getResources(), bitmap); - final Bitmap roundedBitmap = createRoundedBitmap(image, imageSize, imageSize, - cardRadius, 0, cardRadius, 0); - appWidgetView.setImageViewBitmap(R.id.image, roundedBitmap); - - pushUpdate(appContext, appWidgetIds, appWidgetView); - } - }); - } - }); - } - - /** - * Link up various button actions using {@link PendingIntent}. - */ - private void linkButtons(final Context context, final RemoteViews views) { - Intent action; - PendingIntent pendingIntent; - - final ComponentName serviceName = new ComponentName(context, MusicService.class); - - // Home - action = new Intent(context, NowPayingActivity.class); - action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - pendingIntent = PendingIntent.getActivity(context, 0, action, 0); - views.setOnClickPendingIntent(R.id.image, pendingIntent); - views.setOnClickPendingIntent(R.id.media_titles, pendingIntent); - - // Previous track - pendingIntent = buildPendingIntent(context, Constants.ACTION_REWIND, serviceName); - views.setOnClickPendingIntent(R.id.button_prev, pendingIntent); - - // Play and pause - pendingIntent = buildPendingIntent(context, Constants.ACTION_TOGGLE_PAUSE, serviceName); - views.setOnClickPendingIntent(R.id.button_toggle_play_pause, pendingIntent); - - // Next track - pendingIntent = buildPendingIntent(context, Constants.ACTION_SKIP, serviceName); - views.setOnClickPendingIntent(R.id.button_next, pendingIntent); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetSmall.java b/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetSmall.java deleted file mode 100644 index 376254f8..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appwidgets/AppWidgetSmall.java +++ /dev/null @@ -1,187 +0,0 @@ -package code.name.monkey.retromusic.appwidgets; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.drawable.Drawable; -import androidx.annotation.Nullable; -import androidx.palette.graphics.Palette; -import android.text.TextUtils; -import android.view.View; -import android.widget.RemoteViews; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.Constants; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appwidgets.base.BaseAppWidget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.MainActivity; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; -import code.name.monkey.retromusic.util.RetroUtil; -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; -import com.bumptech.glide.request.target.Target; - -public class AppWidgetSmall extends BaseAppWidget { - - public static final String NAME = "app_widget_small"; - - private static AppWidgetSmall mInstance; - private static int imageSize = 0; - private static float cardRadius = 0f; - private Target target; // for cancellation - - public static synchronized AppWidgetSmall getInstance() { - if (mInstance == null) { - mInstance = new AppWidgetSmall(); - } - return mInstance; - } - - /** - * Initialize given widgets to default state, where we launch Music on default click and hide - * actions if service not running. - */ - protected void defaultAppWidget(final Context context, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(context.getPackageName(), - R.layout.app_widget_small); - - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - appWidgetView.setImageViewResource(R.id.image, R.drawable.default_album_art); - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_next_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_previous_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, createBitmap( - RetroUtil.getTintedVectorDrawable(context, R.drawable.ic_play_arrow_white_24dp, - MaterialValueHelper.getSecondaryTextColor(context, true)), 1f)); - - linkButtons(context, appWidgetView); - pushUpdate(context, appWidgetIds, appWidgetView); - } - - /** - * Update all active widget instances by pushing changes - */ - public void performUpdate(final MusicService service, final int[] appWidgetIds) { - final RemoteViews appWidgetView = new RemoteViews(service.getPackageName(), - R.layout.app_widget_small); - - final boolean isPlaying = service.isPlaying(); - final Song song = service.getCurrentSong(); - - // Set the titles and artwork - if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName)) { - appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE); - } else { - if (TextUtils.isEmpty(song.title) || TextUtils.isEmpty(song.artistName)) { - appWidgetView.setTextViewText(R.id.text_separator, ""); - } else { - appWidgetView.setTextViewText(R.id.text_separator, "•"); - } - - appWidgetView.setViewVisibility(R.id.media_titles, View.VISIBLE); - appWidgetView.setTextViewText(R.id.title, song.title); - appWidgetView.setTextViewText(R.id.text, song.artistName); - } - - // Link actions buttons to intents - linkButtons(service, appWidgetView); - - if (imageSize == 0) { - imageSize = service.getResources().getDimensionPixelSize(R.dimen.app_widget_small_image_size); - } - if (cardRadius == 0f) { - cardRadius = service.getResources().getDimension(R.dimen.app_widget_card_radius); - } - - // Load the album cover async and push the update on completion - final Context appContext = service.getApplicationContext(); - service.runOnUiThread(new Runnable() { - @Override - public void run() { - if (target != null) { - Glide.clear(target); - } - target = SongGlideRequest.Builder.from(Glide.with(appContext), song) - .checkIgnoreMediaStore(appContext) - .generatePalette(service).build() - .centerCrop() - .into(new SimpleTarget(imageSize, imageSize) { - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - Palette palette = resource.getPalette(); - update(resource.getBitmap(), palette.getVibrantColor(palette - .getMutedColor(MaterialValueHelper.getSecondaryTextColor(appContext, true)))); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - update(null, MaterialValueHelper.getSecondaryTextColor(appContext, true)); - } - - private void update(@Nullable Bitmap bitmap, int color) { - // Set correct drawable for pause state - int playPauseRes = isPlaying ? R.drawable.ic_pause_white_24dp - : R.drawable.ic_play_arrow_white_24dp; - appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, - createBitmap(RetroUtil.getTintedVectorDrawable(service, playPauseRes, color), 1f)); - - // Set prev/next button drawables - appWidgetView.setImageViewBitmap(R.id.button_next, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - color), 1f)); - appWidgetView.setImageViewBitmap(R.id.button_prev, createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - color), 1f)); - - final Drawable image = getAlbumArtDrawable(service.getResources(), bitmap); - final Bitmap roundedBitmap = createRoundedBitmap(image, imageSize, imageSize, - cardRadius, 0, 0, 0); - appWidgetView.setImageViewBitmap(R.id.image, roundedBitmap); - - pushUpdate(appContext, appWidgetIds, appWidgetView); - } - }); - } - }); - } - - /** - * Link up various button actions using {@link PendingIntent}. - */ - private void linkButtons(final Context context, final RemoteViews views) { - Intent action; - PendingIntent pendingIntent; - - final ComponentName serviceName = new ComponentName(context, MusicService.class); - - // Home - action = new Intent(context, NowPayingActivity.class); - action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - pendingIntent = PendingIntent.getActivity(context, 0, action, 0); - views.setOnClickPendingIntent(R.id.image, pendingIntent); - views.setOnClickPendingIntent(R.id.media_titles, pendingIntent); - - // Previous track - pendingIntent = buildPendingIntent(context, Constants.ACTION_REWIND, serviceName); - views.setOnClickPendingIntent(R.id.button_prev, pendingIntent); - - // Play and pause - pendingIntent = buildPendingIntent(context, Constants.ACTION_TOGGLE_PAUSE, serviceName); - views.setOnClickPendingIntent(R.id.button_toggle_play_pause, pendingIntent); - - // Next track - pendingIntent = buildPendingIntent(context, Constants.ACTION_SKIP, serviceName); - views.setOnClickPendingIntent(R.id.button_next, pendingIntent); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appwidgets/BootReceiver.java b/app/src/main/java/code/name/monkey/retromusic/appwidgets/BootReceiver.java deleted file mode 100644 index 38fb2989..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appwidgets/BootReceiver.java +++ /dev/null @@ -1,32 +0,0 @@ -package code.name.monkey.retromusic.appwidgets; - -import android.appwidget.AppWidgetManager; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.os.Build; - -import code.name.monkey.retromusic.service.MusicService; - - -/** - * @author Eugene Cheung (arkon) - */ -public class BootReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - final AppWidgetManager widgetManager = AppWidgetManager.getInstance(context); - - // Start music service if there are any existing widgets - if (widgetManager.getAppWidgetIds(new ComponentName(context, AppWidgetBig.class)).length > 0 || - widgetManager.getAppWidgetIds(new ComponentName(context, AppWidgetClassic.class)).length > 0 || - widgetManager.getAppWidgetIds(new ComponentName(context, AppWidgetSmall.class)).length > 0 || - widgetManager.getAppWidgetIds(new ComponentName(context, AppWidgetCard.class)).length > 0) { - final Intent serviceIntent = new Intent(context, MusicService.class); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // not allowed on Oreo - context.startService(serviceIntent); - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/appwidgets/base/BaseAppWidget.java b/app/src/main/java/code/name/monkey/retromusic/appwidgets/base/BaseAppWidget.java deleted file mode 100644 index acb9476d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/appwidgets/base/BaseAppWidget.java +++ /dev/null @@ -1,163 +0,0 @@ -package code.name.monkey.retromusic.appwidgets.base; - -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.res.Resources; -import android.graphics.Bitmap; -import android.graphics.BitmapShader; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Path; -import android.graphics.RectF; -import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.text.TextUtils; -import android.widget.RemoteViews; - -import code.name.monkey.retromusic.Constants; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; - -public abstract class BaseAppWidget extends AppWidgetProvider { - - public static final String NAME = "app_widget"; - - protected static Bitmap createBitmap(Drawable drawable, float sizeMultiplier) { - Bitmap bitmap = Bitmap.createBitmap((int) (drawable.getIntrinsicWidth() * sizeMultiplier), - (int) (drawable.getIntrinsicHeight() * sizeMultiplier), Bitmap.Config.ARGB_8888); - Canvas c = new Canvas(bitmap); - drawable.setBounds(0, 0, c.getWidth(), c.getHeight()); - drawable.draw(c); - return bitmap; - } - - protected static Bitmap createRoundedBitmap(Drawable drawable, int width, int height, float tl, - float tr, float bl, float br) { - if (drawable == null) { - return null; - } - - Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - Canvas c = new Canvas(bitmap); - drawable.setBounds(0, 0, width, height); - drawable.draw(c); - - Bitmap rounded = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - - Canvas canvas = new Canvas(rounded); - Paint paint = new Paint(); - paint.setShader( - new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); - paint.setAntiAlias(true); - canvas.drawPath(composeRoundedRectPath(new RectF(0, 0, width, height), tl, tr, bl, br), paint); - - return rounded; - } - - protected static Path composeRoundedRectPath(RectF rect, float tl, float tr, float bl, float br) { - Path path = new Path(); - tl = tl < 0 ? 0 : tl; - tr = tr < 0 ? 0 : tr; - bl = bl < 0 ? 0 : bl; - br = br < 0 ? 0 : br; - - path.moveTo(rect.left + tl, rect.top); - path.lineTo(rect.right - tr, rect.top); - path.quadTo(rect.right, rect.top, rect.right, rect.top + tr); - path.lineTo(rect.right, rect.bottom - br); - path.quadTo(rect.right, rect.bottom, rect.right - br, rect.bottom); - path.lineTo(rect.left + bl, rect.bottom); - path.quadTo(rect.left, rect.bottom, rect.left, rect.bottom - bl); - path.lineTo(rect.left, rect.top + tl); - path.quadTo(rect.left, rect.top, rect.left + tl, rect.top); - path.close(); - - return path; - } - - /** - * {@inheritDoc} - */ - @Override - public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, - final int[] appWidgetIds) { - defaultAppWidget(context, appWidgetIds); - final Intent updateIntent = new Intent(Constants.APP_WIDGET_UPDATE); - updateIntent.putExtra(Constants.EXTRA_APP_WIDGET_NAME, NAME); - updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); - updateIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); - context.sendBroadcast(updateIntent); - } - - /** - * Handle a change notification coming over from {@link MusicService} - */ - public void notifyChange(final MusicService service, final String what) { - if (hasInstances(service)) { - if (Constants.META_CHANGED.equals(what) || Constants.PLAY_STATE_CHANGED.equals(what)) { - performUpdate(service, null); - } - } - } - - protected void pushUpdate(final Context context, final int[] appWidgetIds, - final RemoteViews views) { - final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); - if (appWidgetIds != null) { - appWidgetManager.updateAppWidget(appWidgetIds, views); - } else { - appWidgetManager.updateAppWidget(new ComponentName(context, getClass()), views); - } - } - - /** - * Check against {@link AppWidgetManager} if there are any instances of this widget. - */ - protected boolean hasInstances(final Context context) { - final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); - final int[] mAppWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, - getClass())); - return mAppWidgetIds.length > 0; - } - - protected PendingIntent buildPendingIntent(Context context, final String action, - final ComponentName serviceName) { - Intent intent = new Intent(action); - intent.setComponent(serviceName); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - return PendingIntent.getForegroundService(context, 0, intent, 0); - } else { - return PendingIntent.getService(context, 0, intent, 0); - } - } - - abstract protected void defaultAppWidget(final Context context, final int[] appWidgetIds); - - abstract public void performUpdate(final MusicService service, final int[] appWidgetIds); - - protected Drawable getAlbumArtDrawable(final Resources resources, final Bitmap bitmap) { - Drawable image; - if (bitmap == null) { - image = resources.getDrawable(R.drawable.default_album_art); - } else { - image = new BitmapDrawable(resources, bitmap); - } - return image; - } - - protected String getSongArtistAndAlbum(final Song song) { - final StringBuilder builder = new StringBuilder(); - builder.append(song.artistName); - if (!TextUtils.isEmpty(song.artistName) && !TextUtils.isEmpty(song.albumName)) { - builder.append(" • "); - } - builder.append(song.albumName); - return builder.toString(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/cast/CastHelper.java b/app/src/main/java/code/name/monkey/retromusic/cast/CastHelper.java index 89bfa519..a8951ee0 100644 --- a/app/src/main/java/code/name/monkey/retromusic/cast/CastHelper.java +++ b/app/src/main/java/code/name/monkey/retromusic/cast/CastHelper.java @@ -16,6 +16,8 @@ import code.name.monkey.retromusic.Constants; import code.name.monkey.retromusic.model.Song; import code.name.monkey.retromusic.util.RetroUtil; +import static code.name.monkey.retromusic.Constants.CAST_SERVER_PORT; + public class CastHelper { public static void startCasting(CastSession castSession, Song song) { @@ -23,22 +25,22 @@ public class CastHelper { String ipAddress = RetroUtil.getIPAddress(true); URL baseUrl; try { - baseUrl = new URL("https", ipAddress, Constants.CAST_SERVER_PORT, ""); + baseUrl = new URL("https", ipAddress,CAST_SERVER_PORT, ""); } catch (MalformedURLException e) { e.printStackTrace(); return; } - String songUrl = baseUrl.toString() + "/song?id=" + song.id; - String albumArtUrl = baseUrl.toString() + "/albumart?id=" + song.albumId; + String songUrl = baseUrl.toString() + "/song?id=" + song.getId(); + String albumArtUrl = baseUrl.toString() + "/albumart?id=" + song.getAlbumId(); MediaMetadata musicMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK); - musicMetadata.putString(MediaMetadata.KEY_TITLE, song.title); - musicMetadata.putString(MediaMetadata.KEY_ARTIST, song.artistName); - musicMetadata.putString(MediaMetadata.KEY_ALBUM_TITLE, song.albumName); - musicMetadata.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.trackNumber); + musicMetadata.putString(MediaMetadata.KEY_TITLE, song.getTitle()); + musicMetadata.putString(MediaMetadata.KEY_ARTIST, song.getArtistName()); + musicMetadata.putString(MediaMetadata.KEY_ALBUM_TITLE, song.getAlbumName()); + musicMetadata.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.getTrackNumber()); musicMetadata.addImage(new WebImage(Uri.parse(albumArtUrl))); try { @@ -46,7 +48,7 @@ public class CastHelper { .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED) .setContentType("audio/mpeg") .setMetadata(musicMetadata) - .setStreamDuration(song.duration) + .setStreamDuration(song.getDuration()) .build(); RemoteMediaClient remoteMediaClient = castSession.getRemoteMediaClient(); remoteMediaClient.load(mediaInfo, new MediaLoadOptions.Builder() diff --git a/app/src/main/java/code/name/monkey/retromusic/cast/WebServer.java b/app/src/main/java/code/name/monkey/retromusic/cast/WebServer.java index fd96ae8c..172514de 100644 --- a/app/src/main/java/code/name/monkey/retromusic/cast/WebServer.java +++ b/app/src/main/java/code/name/monkey/retromusic/cast/WebServer.java @@ -13,13 +13,15 @@ import code.name.monkey.retromusic.Constants; import code.name.monkey.retromusic.util.RetroUtil; import fi.iki.elonen.NanoHTTPD; +import static code.name.monkey.retromusic.Constants.CAST_SERVER_PORT; + public class WebServer extends NanoHTTPD { private Context context; private Uri songUri, albumArtUri; public WebServer(Context context) { - super(Constants.CAST_SERVER_PORT); + super(CAST_SERVER_PORT); this.context = context; } diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.java index 4741ef29..2a8cfa7c 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.java +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.java @@ -75,7 +75,7 @@ public class AddToPlaylistDialog extends RoundedBottomSheetDialogFragment { super.onViewCreated(view, savedInstanceState); title.setTextColor(ThemeStore.textColorPrimary(getContext())); final ArrayList songs = getArguments().getParcelableArrayList("songs"); - final ArrayList playlists = PlaylistLoader.getAllPlaylists(getActivity()).blockingFirst(); + final ArrayList playlists = PlaylistLoader.INSTANCE.getAllPlaylists(getActivity()).blockingFirst(); final AddToPlaylist playlistAdapter = new AddToPlaylist(getActivity(), playlists, R.layout.item_playlist, songs, getDialog()); playlist.setLayoutManager(new LinearLayoutManager(getContext())); playlist.setItemAnimator(new DefaultItemAnimator()); diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.java index ca670503..0f725635 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.java +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.java @@ -82,7 +82,7 @@ public class DeleteSongsDialog extends RoundedBottomSheetDialogFragment { if (songs.size() > 1) { content = Html.fromHtml(getString(R.string.delete_x_songs, songs.size())); } else { - content = Html.fromHtml(getString(R.string.delete_song_x, songs.get(0).title)); + content = Html.fromHtml(getString(R.string.delete_song_x, songs.get(0).getTitle())); } this.title.setText(content); } diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/MainOptionsBottomSheetDialogFragment.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/MainOptionsBottomSheetDialogFragment.java index 6c08adaa..0374f023 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/MainOptionsBottomSheetDialogFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/MainOptionsBottomSheetDialogFragment.java @@ -81,8 +81,8 @@ public class MainOptionsBottomSheetDialogFragment extends RoundedBottomSheetDial public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_main_options, container, false); ButterKnife.bind(this, layout); - layout.findViewById(R.id.action_buy_pro).setVisibility(RetroApplication.isProVersion() ? View.GONE : View.VISIBLE); - ButterKnife.apply(materialButtons, textColor, ThemeStore.textColorPrimary(getContext())); + layout.findViewById(R.id.action_buy_pro).setVisibility(RetroApplication.Companion.isProVersion() ? View.GONE : View.VISIBLE); + //ButterKnife.apply(materialButtons, textColor, ThemeStore.textColorPrimary(getContext())); return layout; } @@ -157,7 +157,7 @@ public class MainOptionsBottomSheetDialogFragment extends RoundedBottomSheetDial .setQuality(75) .setCompressFormat(Bitmap.CompressFormat.WEBP) .compressToBitmapAsFlowable( - new File(PreferenceUtil.getInstance().getProfileImage(), USER_PROFILE)) + new File(PreferenceUtil.getInstance().getProfileImage(),USER_PROFILE)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(userImageBottom::setImageBitmap, diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.java deleted file mode 100644 index 6f144747..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.java +++ /dev/null @@ -1,93 +0,0 @@ -package code.name.monkey.retromusic.dialogs; - -import android.os.Bundle; -import android.text.Html; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.PlaylistSong; -import code.name.monkey.retromusic.util.PlaylistsUtil; -import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment; - - -public class RemoveFromPlaylistDialog extends RoundedBottomSheetDialogFragment { - @BindView(R.id.action_remove) - TextView remove; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.action_cancel) - TextView cancel; - - @NonNull - public static RemoveFromPlaylistDialog create(PlaylistSong song) { - ArrayList list = new ArrayList<>(); - list.add(song); - return create(list); - } - - @NonNull - public static RemoveFromPlaylistDialog create(ArrayList songs) { - RemoveFromPlaylistDialog dialog = new RemoveFromPlaylistDialog(); - Bundle args = new Bundle(); - args.putParcelableArrayList("songs", songs); - dialog.setArguments(args); - return dialog; - } - - @OnClick({R.id.action_cancel, R.id.action_remove}) - void actions(View view) { - final ArrayList songs = getArguments().getParcelableArrayList("songs"); - switch (view.getId()) { - case R.id.action_remove: - if (getActivity() == null) - return; - PlaylistsUtil.removeFromPlaylist(getActivity(), songs); - break; - default: - } - dismiss(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View layout = inflater.inflate(R.layout.dialog_remove_from_playlist, container, false); - ButterKnife.bind(this, layout); - return layout; - } - - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - //noinspection unchecked - final ArrayList songs = getArguments().getParcelableArrayList("songs"); - int title; - CharSequence content; - if (songs != null && songs.size() > 1) { - title = R.string.remove_songs_from_playlist_title; - content = Html.fromHtml(getString(R.string.remove_x_songs_from_playlist, songs.size())); - } else { - title = R.string.remove_song_from_playlist_title; - content = Html.fromHtml(getString(R.string.remove_song_x_from_playlist, songs.get(0).title)); - } - this.remove.setText(content); - this.title.setText(title); - - this.title.setTextColor(ThemeStore.textColorPrimary(getContext())); - this.remove.setTextColor(ThemeStore.textColorSecondary(getContext())); - this.cancel.setTextColor(ThemeStore.textColorSecondary(getContext())); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.kt new file mode 100644 index 00000000..38726666 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.kt @@ -0,0 +1,91 @@ +package code.name.monkey.retromusic.dialogs + +import android.os.Build +import android.os.Bundle +import android.text.Html +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.OnClick +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.PlaylistSong +import code.name.monkey.retromusic.util.PlaylistsUtil +import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment +import java.util.* + + +class RemoveFromPlaylistDialog : RoundedBottomSheetDialogFragment() { + @BindView(R.id.action_remove) + internal var remove: TextView? = null + + @BindView(R.id.title) + internal var title: TextView? = null + + @BindView(R.id.action_cancel) + internal var cancel: TextView? = null + + @OnClick(R.id.action_cancel, R.id.action_remove) + internal fun actions(view: View) { + val songs = arguments!!.getParcelableArrayList("songs") + when (view.id) { + R.id.action_remove -> { + if (activity == null) + return + PlaylistsUtil.removeFromPlaylist(activity!!, songs!!) + } + } + dismiss() + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val layout = inflater.inflate(R.layout.dialog_remove_from_playlist, container, false) + ButterKnife.bind(this, layout) + return layout + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val songs = arguments!!.getParcelableArrayList("songs") + val title: Int + val content: CharSequence + if (songs != null && songs.size > 1) { + title = R.string.remove_songs_from_playlist_title + content = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + Html.fromHtml(getString(R.string.remove_x_songs_from_playlist, songs.size), Html.FROM_HTML_MODE_LEGACY) + } else { + Html.fromHtml(getString(R.string.remove_x_songs_from_playlist, songs.size)) + } + } else { + title = R.string.remove_song_from_playlist_title + content = Html.fromHtml(getString(R.string.remove_song_x_from_playlist, songs!![0].title)) + } + this.remove!!.text = content + this.title!!.setText(title) + + this.title!!.setTextColor(ThemeStore.textColorPrimary(context!!)) + this.remove!!.setTextColor(ThemeStore.textColorSecondary(context!!)) + this.cancel!!.setTextColor(ThemeStore.textColorSecondary(context!!)) + } + + companion object { + + fun create(song: PlaylistSong): RemoveFromPlaylistDialog { + val list = ArrayList() + list.add(song) + return create(list) + } + + fun create(songs: ArrayList): RemoveFromPlaylistDialog { + val dialog = RemoveFromPlaylistDialog() + val args = Bundle() + args.putParcelableArrayList("songs", songs) + dialog.arguments = args + return dialog + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.java index abfad350..3e661319 100755 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.java +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.java @@ -168,7 +168,7 @@ public class SleepTimerDialog extends RoundedBottomSheetDialogFragment { private Intent makeTimerIntent() { return new Intent(getActivity(), MusicService.class) - .setAction(ACTION_QUIT); + .setAction( ACTION_QUIT); } private class TimerUpdater extends CountDownTimer { diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.java index 6d3a6930..e67a4a68 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.java +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.java @@ -94,7 +94,7 @@ public class SongDetailDialog extends RoundedBottomSheetDialogFragment { final Song song = getArguments().getParcelable("song"); if (song != null) { - final File songFile = new File(song.data); + final File songFile = new File(song.getData()); if (songFile.exists()) { textViews.get(1).setText(makeTextWithTitle(context, R.string.label_file_name, songFile.getName())); textViews.get(2).setText(makeTextWithTitle(context, R.string.label_file_path, songFile.getAbsolutePath())); @@ -110,12 +110,12 @@ public class SongDetailDialog extends RoundedBottomSheetDialogFragment { } catch (@NonNull CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException e) { Log.e(TAG, "error while reading the song file", e); // fallback - textViews.get(5).setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration))); + textViews.get(5).setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.getDuration()))); } } else { // fallback - textViews.get(1).setText(makeTextWithTitle(context, R.string.label_file_name, song.title)); - textViews.get(5).setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration))); + textViews.get(1).setText(makeTextWithTitle(context, R.string.label_file_name, song.getTitle())); + textViews.get(5).setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.getDuration()))); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.java b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.java index 96b70347..7b804a7e 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.java +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.java @@ -51,7 +51,7 @@ public class SongShareDialog extends RoundedBottomSheetDialogFragment { super.onViewCreated(view, savedInstanceState); final Song song = getArguments().getParcelable("song"); - audioFile.setText(getString(R.string.currently_listening_to_x_by_x, song.title, song.artistName)); + audioFile.setText(getString(R.string.currently_listening_to_x_by_x, song.getTitle(), song.getArtistName())); audioFile.setTextColor(ThemeStore.textColorSecondary(getContext())); audioText.setTextColor(ThemeStore.textColorSecondary(getContext())); title.setTextColor(ThemeStore.textColorPrimary(getContext())); @@ -60,7 +60,7 @@ public class SongShareDialog extends RoundedBottomSheetDialogFragment { @OnClick({R.id.option_2, R.id.option_1}) void onClick(View view) { final Song song = getArguments().getParcelable("song"); - final String currentlyListening = getString(R.string.currently_listening_to_x_by_x, song.title, song.artistName); + final String currentlyListening = getString(R.string.currently_listening_to_x_by_x, song.getTitle(), song.getArtistName()); switch (view.getId()) { case R.id.option_1: startActivity(Intent.createChooser( diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.java b/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.java index 968fdd17..7bf2c1e9 100644 --- a/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.java +++ b/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.java @@ -31,7 +31,7 @@ public class ArtistGlideRequest { private static DrawableTypeRequest createBaseRequest(RequestManager requestManager, Artist artist, boolean noCustomImage, boolean forceDownload) { - boolean hasCustomImage = CustomArtistImageUtil.getInstance(RetroApplication.getInstance()) + boolean hasCustomImage = CustomArtistImageUtil.getInstance(RetroApplication.Companion.getInstance()) .hasCustomArtistImage(artist); if (noCustomImage || !hasCustomImage) { return requestManager.load(new ArtistImage(artist.getName(), forceDownload)); @@ -41,7 +41,7 @@ public class ArtistGlideRequest { } private static Key createSignature(Artist artist) { - return ArtistSignatureUtil.getInstance(RetroApplication.getInstance()) + return ArtistSignatureUtil.getInstance(RetroApplication.Companion.getInstance()) .getArtistSignature(artist.getName()); } diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicColoredTarget.java b/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicColoredTarget.java deleted file mode 100644 index c20dd0a1..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicColoredTarget.java +++ /dev/null @@ -1,53 +0,0 @@ -package code.name.monkey.retromusic.glide; - -import android.graphics.drawable.Drawable; -import android.widget.ImageView; - -import com.bumptech.glide.request.animation.GlideAnimation; - -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.RetroApplication; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteTarget; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.util.PreferenceUtil; - -import static code.name.monkey.retromusic.util.RetroColorUtil.getColor; -import static code.name.monkey.retromusic.util.RetroColorUtil.getDominantColor; - - -public abstract class RetroMusicColoredTarget extends BitmapPaletteTarget { - - public RetroMusicColoredTarget(ImageView view) { - super(view); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - onColorReady(getDefaultFooterColor()); - } - - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - super.onResourceReady(resource, glideAnimation); - int defaultColor = getDefaultFooterColor(); - - int primaryColor = getColor(resource.getPalette(), defaultColor); - int dominantColor = getDominantColor(resource.getBitmap(), defaultColor); - - onColorReady(PreferenceUtil.getInstance().isDominantColor() ? - dominantColor : primaryColor); - } - - protected int getDefaultFooterColor() { - return ATHUtil.resolveColor(getView().getContext(), R.attr.defaultFooterColor); - } - - protected int getAlbumArtistFooterColor() { - return ATHUtil.resolveColor(getView().getContext(), R.attr.cardBackgroundColor); - } - - public abstract void onColorReady(int color); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicColoredTarget.kt b/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicColoredTarget.kt new file mode 100644 index 00000000..281dc96a --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicColoredTarget.kt @@ -0,0 +1,47 @@ +package code.name.monkey.retromusic.glide + +import android.graphics.drawable.Drawable +import android.widget.ImageView + +import com.bumptech.glide.request.animation.GlideAnimation + +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.RetroApplication +import code.name.monkey.retromusic.glide.palette.BitmapPaletteTarget +import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper +import code.name.monkey.retromusic.util.PreferenceUtil + +import code.name.monkey.retromusic.util.RetroColorUtil.getColor +import code.name.monkey.retromusic.util.RetroColorUtil.getDominantColor + + +abstract class RetroMusicColoredTarget(view: ImageView) : BitmapPaletteTarget(view) { + + protected val defaultFooterColor: Int + get() = ATHUtil.resolveColor(getView().context, R.attr.defaultFooterColor) + + protected val albumArtistFooterColor: Int + get() = ATHUtil.resolveColor(getView().context, R.attr.cardBackgroundColor) + + override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) { + super.onLoadFailed(e, errorDrawable) + onColorReady(defaultFooterColor) + } + + override fun onResourceReady(resource: BitmapPaletteWrapper, + glideAnimation: GlideAnimation?) { + super.onResourceReady(resource, glideAnimation) + val defaultColor = defaultFooterColor + + val primaryColor = getColor(resource.palette, defaultColor) + val dominantColor = getDominantColor(resource.bitmap, defaultColor) + + onColorReady(if (PreferenceUtil.getInstance().isDominantColor) + dominantColor + else + primaryColor) + } + + abstract fun onColorReady(color: Int) +} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.java b/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.java index 0d44984c..39e28d7b 100644 --- a/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.java +++ b/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.java @@ -29,14 +29,14 @@ public class SongGlideRequest { static DrawableTypeRequest createBaseRequest(RequestManager requestManager, Song song, boolean ignoreMediaStore) { if (ignoreMediaStore) { - return requestManager.load(new AudioFileCover(song.data)); + return requestManager.load(new AudioFileCover(song.getData())); } else { - return requestManager.loadFromMediaStore(MusicUtil.getMediaStoreAlbumCoverUri(song.albumId)); + return requestManager.loadFromMediaStore(MusicUtil.getMediaStoreAlbumCoverUri(song.getAlbumId())); } } static Key createSignature(Song song) { - return new MediaStoreSignature("", song.dateModified, 0); + return new MediaStoreSignature("", song.getDateModified(), 0); } public static class Builder { diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTarget.java b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTarget.java deleted file mode 100644 index 662db217..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTarget.java +++ /dev/null @@ -1,17 +0,0 @@ -package code.name.monkey.retromusic.glide.palette; - -import android.widget.ImageView; -import com.bumptech.glide.request.target.ImageViewTarget; - -public class BitmapPaletteTarget extends ImageViewTarget { - - public BitmapPaletteTarget(ImageView view) { - super(view); - } - - @Override - protected void setResource(BitmapPaletteWrapper bitmapPaletteWrapper) { - view.setImageBitmap(bitmapPaletteWrapper.getBitmap()); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTarget.kt b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTarget.kt new file mode 100644 index 00000000..663927fb --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTarget.kt @@ -0,0 +1,12 @@ +package code.name.monkey.retromusic.glide.palette + +import android.widget.ImageView +import com.bumptech.glide.request.target.ImageViewTarget + +open class BitmapPaletteTarget(view: ImageView) : ImageViewTarget(view) { + + override fun setResource(bitmapPaletteWrapper: BitmapPaletteWrapper) { + view.setImageBitmap(bitmapPaletteWrapper.bitmap) + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/EqualizerHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/EqualizerHelper.java deleted file mode 100644 index 12f98ba4..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/EqualizerHelper.java +++ /dev/null @@ -1,171 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.media.audiofx.BassBoost; -import android.media.audiofx.Equalizer; -import android.media.audiofx.Virtualizer; -import android.util.Log; - -import code.name.monkey.retromusic.interfaces.EqualizerInterface; - -/** - * @author Hemanth S (h4h13). - */ - -public class EqualizerHelper implements EqualizerInterface { - private static final String TAG = "EqualizerHelper"; - private static volatile EqualizerHelper ourInstance; - private Equalizer mEqualizer; - private BassBoost mBassBoost; - private Virtualizer mVirtualizer; - - private int mMaxLevel, mMinLevel; - private boolean isRunning = false; - - private EqualizerHelper() { - - //Prevent form the reflection api. - if (ourInstance != null) { - throw new RuntimeException("Use getInstance() method to get the single instance of this class."); - } - - int i = MusicPlayerRemote.getAudioSessionId(); - - mEqualizer = new Equalizer(100, i); - if (mEqualizer == null) { - Log.i(TAG, "onCreate: Equalizer is null"); - return; - } - mEqualizer.setEnabled(true); - - - mBassBoost = new BassBoost(100, i); - if (mBassBoost == null) { - Log.i(TAG, "onCreate: BassBoost is null"); - return; - } - - mVirtualizer = new Virtualizer(100, i); - if (mVirtualizer == null) { - Log.i(TAG, "onCreate: Virtualizer is null"); - return; - } - - mMaxLevel = (int) mEqualizer.getBandLevelRange()[1]; - mMinLevel = (int) mEqualizer.getBandLevelRange()[0]; - - Log.i(TAG, "onCreate: " + mMaxLevel + " " + mMinLevel); - isRunning = true; - } - - public static EqualizerHelper getInstance() { - //Double check locking pattern - if (ourInstance == null) {//Check for the first time - - synchronized (EqualizerHelper.class) {//Check for the second time. - - //if there is no instance available... create new one - if (ourInstance == null) { - ourInstance = new EqualizerHelper(); - } - } - } - return ourInstance; - } - - //Make singleton from serialize and deserialize operation. - protected EqualizerHelper readResolve() { - return getInstance(); - } - - @Override - public Equalizer getEqualizer() { - return mEqualizer; - } - - @Override - public BassBoost getBassBoost() { - return mBassBoost; - } - - @Override - public Virtualizer getVirtualizer() { - return mVirtualizer; - } - - @Override - public int getBandLevelLow() { - return mMinLevel; - } - - @Override - public int getBandLevelHigh() { - return mMaxLevel; - } - - @Override - public int getNumberOfBands() { - return (int) mEqualizer.getNumberOfBands(); - } - - @Override - public int getCenterFreq(int band) { - return (int) mEqualizer.getCenterFreq((short) band); - } - - - @Override - public int getBandLevel(int band) { - return (int) mEqualizer.getBandLevel((short) band); - } - - @Override - public void setBandLevel(int band, int level) { - mEqualizer.setBandLevel((short) band, (short) level); - } - - @Override - public boolean isBassBoostEnabled() { - return mBassBoost.getEnabled(); - } - - @Override - public void setBassBoostEnabled(boolean isEnabled) { - mBassBoost.setEnabled(isEnabled); - } - - @Override - public int getBassBoostStrength() { - return (int) mBassBoost.getRoundedStrength(); - } - - @Override - public void setBassBoostStrength(int strength) { - mBassBoost.setStrength((short) strength); - } - - @Override - public boolean isVirtualizerEnabled() { - return mVirtualizer.getEnabled(); - } - - @Override - public void setVirtualizerEnabled(boolean isEnabled) { - mVirtualizer.setEnabled(isEnabled); - } - - @Override - public int getVirtualizerStrength() { - return mVirtualizer.getRoundedStrength(); - } - - @Override - public void setVirtualizerStrength(int strength) { - mVirtualizer.setStrength((short) strength); - } - - @Override - public boolean isRunning() { - return isRunning; - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/EqualizerHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/EqualizerHelper.kt new file mode 100644 index 00000000..262ac7d3 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/EqualizerHelper.kt @@ -0,0 +1,109 @@ +package code.name.monkey.retromusic.helper + +import android.media.audiofx.BassBoost +import android.media.audiofx.Equalizer +import android.media.audiofx.Virtualizer +import android.util.Log + +import code.name.monkey.retromusic.interfaces.EqualizerInterface + +/** + * @author Hemanth S (h4h13). + */ + +class EqualizerHelper private constructor() : EqualizerInterface { + override val equalizer: Equalizer + override val bassBoost: BassBoost + override val virtualizer: Virtualizer + + override val bandLevelHigh: Int + override val bandLevelLow: Int + override var isRunning = false + + override val numberOfBands: Int + get() = equalizer.numberOfBands.toInt() + + override var isBassBoostEnabled: Boolean + get() = bassBoost.enabled + set(isEnabled) { + bassBoost.enabled = isEnabled + } + + override var bassBoostStrength: Int + get() = bassBoost.roundedStrength.toInt() + set(strength) = bassBoost.setStrength(strength.toShort()) + + override var isVirtualizerEnabled: Boolean + get() = virtualizer.enabled + set(isEnabled) { + virtualizer.enabled = isEnabled + } + + override var virtualizerStrength: Int + get() = virtualizer.roundedStrength.toInt() + set(strength) = virtualizer.setStrength(strength.toShort()) + + init { + + //Prevent form the reflection api. + if (ourInstance != null) { + throw RuntimeException("Use getInstance() method to get the single instance of this class.") + } + + val i = MusicPlayerRemote.audioSessionId + + equalizer = Equalizer(100, i) + + equalizer.enabled = true + bassBoost = BassBoost(100, i) + virtualizer = Virtualizer(100, i) + + bandLevelHigh = equalizer.bandLevelRange[1].toInt() + bandLevelLow = equalizer.bandLevelRange[0].toInt() + + Log.i(TAG, "onCreate: $bandLevelHigh $bandLevelLow") + isRunning = true + } + + //Make singleton from serialize and deserialize operation. + protected fun readResolve(): EqualizerHelper? { + return instance + } + + override fun getCenterFreq(band: Int): Int { + return equalizer.getCenterFreq(band.toShort()) + } + + + override fun getBandLevel(band: Int): Int { + return equalizer.getBandLevel(band.toShort()).toInt() + } + + override fun setBandLevel(band: Int, level: Int) { + equalizer.setBandLevel(band.toShort(), level.toShort()) + } + + companion object { + private val TAG = "EqualizerHelper" + @Volatile + private var ourInstance: EqualizerHelper? = null + + //Double check locking pattern + //Check for the first time + //Check for the second time. + //if there is no instance available... create new one + val instance: EqualizerHelper? + get() { + if (ourInstance == null) { + + synchronized(EqualizerHelper::class.java) { + if (ourInstance == null) { + ourInstance = EqualizerHelper() + } + } + } + return ourInstance + } + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/HorizontalAdapterHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/HorizontalAdapterHelper.java deleted file mode 100644 index fd1ae91a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/HorizontalAdapterHelper.java +++ /dev/null @@ -1,36 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.content.Context; -import android.view.ViewGroup; -import code.name.monkey.retromusic.R; - - -public class HorizontalAdapterHelper { - - public static final int LAYOUT_RES = R.layout.item_image; - - public static final int TYPE_FIRST = 1; - public static final int TYPE_MIDDLE = 2; - public static final int TYPE_LAST = 3; - - public static void applyMarginToLayoutParams(Context context, - ViewGroup.MarginLayoutParams layoutParams, int viewType) { - int listMargin = context.getResources() - .getDimensionPixelSize(R.dimen.now_playing_top_margin); - if (viewType == TYPE_FIRST) { - layoutParams.leftMargin = listMargin; - } else if (viewType == TYPE_LAST) { - layoutParams.rightMargin = listMargin; - } - } - - public static int getItemViewtype(int position, int itemCount) { - if (position == 0) { - return TYPE_FIRST; - } else if (position == itemCount - 1) { - return TYPE_LAST; - } else { - return TYPE_MIDDLE; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/HorizontalAdapterHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/HorizontalAdapterHelper.kt new file mode 100644 index 00000000..613dc7e3 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/HorizontalAdapterHelper.kt @@ -0,0 +1,36 @@ +package code.name.monkey.retromusic.helper + +import android.content.Context +import android.view.ViewGroup +import code.name.monkey.retromusic.R + + +object HorizontalAdapterHelper { + + val LAYOUT_RES = R.layout.item_image + + val TYPE_FIRST = 1 + val TYPE_MIDDLE = 2 + val TYPE_LAST = 3 + + fun applyMarginToLayoutParams(context: Context, + layoutParams: ViewGroup.MarginLayoutParams, viewType: Int) { + val listMargin = context.resources + .getDimensionPixelSize(R.dimen.now_playing_top_margin) + if (viewType == TYPE_FIRST) { + layoutParams.leftMargin = listMargin + } else if (viewType == TYPE_LAST) { + layoutParams.rightMargin = listMargin + } + } + + fun getItemViewtype(position: Int, itemCount: Int): Int { + return if (position == 0) { + TYPE_FIRST + } else if (position == itemCount - 1) { + TYPE_LAST + } else { + TYPE_MIDDLE + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/M3UConstants.java b/app/src/main/java/code/name/monkey/retromusic/helper/M3UConstants.java deleted file mode 100644 index e6ffdf39..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/M3UConstants.java +++ /dev/null @@ -1,8 +0,0 @@ -package code.name.monkey.retromusic.helper; - -public interface M3UConstants { - String EXTENSION = "m3u"; - String HEADER = "#EXTM3U"; - String ENTRY = "#EXTINF:"; - String DURATION_SEPARATOR = ","; -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/M3UConstants.kt b/app/src/main/java/code/name/monkey/retromusic/helper/M3UConstants.kt new file mode 100644 index 00000000..93850141 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/M3UConstants.kt @@ -0,0 +1,10 @@ +package code.name.monkey.retromusic.helper + +interface M3UConstants { + companion object { + val EXTENSION = "m3u" + val HEADER = "#EXTM3U" + val ENTRY = "#EXTINF:" + val DURATION_SEPARATOR = "," + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/M3UWriter.java b/app/src/main/java/code/name/monkey/retromusic/helper/M3UWriter.java deleted file mode 100644 index c976b74f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/M3UWriter.java +++ /dev/null @@ -1,58 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.content.Context; -import androidx.annotation.NonNull; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; - -import code.name.monkey.retromusic.loaders.PlaylistSongsLoader; -import code.name.monkey.retromusic.model.AbsCustomPlaylist; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import io.reactivex.Observable; -import io.reactivex.ObservableEmitter; - -public class M3UWriter implements M3UConstants { - public static final String TAG = M3UWriter.class.getSimpleName(); - - public static Observable write(@NonNull Context context, - @NonNull File dir, @NonNull Playlist playlist) { - if (!dir.exists()) //noinspection ResultOfMethodCallIgnored - dir.mkdirs(); - File file = new File(dir, playlist.name.concat("." + EXTENSION)); - - if (playlist instanceof AbsCustomPlaylist) { - return Observable.create(e -> { - ((AbsCustomPlaylist) playlist).getSongs(context).subscribe(songs -> { - saveSongsToFile(file, e, songs); - }); - }); - } else - return Observable.create(e -> - PlaylistSongsLoader.getPlaylistSongList(context, playlist.id) - .subscribe(songs -> { - saveSongsToFile(file, e, songs); - })); - } - - private static void saveSongsToFile(File file, ObservableEmitter e, ArrayList songs) throws IOException { - if (songs.size() > 0) { - BufferedWriter bw = new BufferedWriter(new FileWriter(file)); - bw.write(HEADER); - for (Song song : songs) { - bw.newLine(); - bw.write(ENTRY + song.duration + DURATION_SEPARATOR + song.artistName + " - " + song.title); - bw.newLine(); - bw.write(song.data); - } - - bw.close(); - } - e.onNext(file); - e.onComplete(); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/M3UWriter.kt b/app/src/main/java/code/name/monkey/retromusic/helper/M3UWriter.kt new file mode 100644 index 00000000..1bd284fe --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/M3UWriter.kt @@ -0,0 +1,53 @@ +package code.name.monkey.retromusic.helper + +import android.content.Context + +import java.io.BufferedWriter +import java.io.File +import java.io.FileWriter +import java.io.IOException +import java.util.ArrayList + +import code.name.monkey.retromusic.loaders.PlaylistSongsLoader +import code.name.monkey.retromusic.model.AbsCustomPlaylist +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.Song +import io.reactivex.Observable +import io.reactivex.ObservableEmitter + +class M3UWriter : M3UConstants { + companion object { + val TAG: String = M3UWriter::class.java.simpleName + + fun write(context: Context, + dir: File, playlist: Playlist): Observable { + if (!dir.exists()) + + dir.mkdirs() + val file = File(dir, playlist.name + ("." + M3UConstants.EXTENSION)) + + return if (playlist is AbsCustomPlaylist) { + Observable.create { e -> playlist.getSongs(context).subscribe { songs -> saveSongsToFile(file, e, songs) } } + } else + Observable.create { e -> PlaylistSongsLoader.getPlaylistSongList(context, playlist.id).subscribe { songs -> saveSongsToFile(file, e, songs) } } + } + + @Throws(IOException::class) + private fun saveSongsToFile(file: File, e: ObservableEmitter, songs: ArrayList) { + if (songs.size > 0) { + val bw = BufferedWriter(FileWriter(file)) + bw.write(M3UConstants.HEADER) + for (song in songs) { + bw.newLine() + bw.write(M3UConstants.ENTRY + song.duration + M3UConstants.DURATION_SEPARATOR + song.artistName + " - " + song.title) + bw.newLine() + bw.write(song.data) + } + + bw.close() + } + e.onNext(file) + e.onComplete() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/MusicPlayerRemote.java b/app/src/main/java/code/name/monkey/retromusic/helper/MusicPlayerRemote.java deleted file mode 100644 index a26f6b76..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/MusicPlayerRemote.java +++ /dev/null @@ -1,496 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.annotation.TargetApi; -import android.app.Activity; -import android.content.ComponentName; -import android.content.ContentResolver; -import android.content.Context; -import android.content.ContextWrapper; -import android.content.Intent; -import android.content.ServiceConnection; -import android.database.Cursor; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.os.IBinder; -import android.provider.DocumentsContract; -import android.provider.MediaStore; -import android.util.Log; -import android.widget.Toast; - -import com.google.android.gms.cast.framework.CastContext; -import com.google.android.gms.cast.framework.CastSession; - -import java.io.File; -import java.util.ArrayList; -import java.util.Random; -import java.util.WeakHashMap; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.RetroApplication; -import code.name.monkey.retromusic.loaders.SongLoader; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.schedulers.Schedulers; - - -public class MusicPlayerRemote { - public static final String TAG = MusicPlayerRemote.class.getSimpleName(); - private static final WeakHashMap mConnectionMap = new WeakHashMap<>(); - @Nullable - public static MusicService musicService; - private static int playbackLocation = PlaybackLocation.LOCAL; - - - private static CastSession getCastSession() { - CastSession castSession = CastContext.getSharedInstance(RetroApplication.getInstance()).getSessionManager().getCurrentCastSession(); - if (castSession != null) { - playbackLocation = PlaybackLocation.REMOTE; - } else { - playbackLocation = PlaybackLocation.LOCAL; - } - return castSession; - } - - public static ServiceToken bindToService(@NonNull final Context context, - final ServiceConnection callback) { - - Activity realActivity = ((Activity) context).getParent(); - if (realActivity == null) { - realActivity = (Activity) context; - } - - final ContextWrapper contextWrapper = new ContextWrapper(realActivity); - contextWrapper.startService(new Intent(contextWrapper, MusicService.class)); - - final ServiceBinder binder = new ServiceBinder(callback); - - if (contextWrapper.bindService(new Intent().setClass(contextWrapper, MusicService.class), binder, Context.BIND_AUTO_CREATE)) { - mConnectionMap.put(contextWrapper, binder); - return new ServiceToken(contextWrapper); - } - return null; - } - - public static void unbindFromService(@Nullable final ServiceToken token) { - if (token == null) { - return; - } - final ContextWrapper mContextWrapper = token.mWrappedContext; - final ServiceBinder mBinder = mConnectionMap.remove(mContextWrapper); - if (mBinder == null) { - return; - } - mContextWrapper.unbindService(mBinder); - if (mConnectionMap.isEmpty()) { - musicService = null; - } - } - - @Nullable - private static String getFilePathFromUri(Context context, Uri uri) { - - final String column = "_data"; - final String[] projection = { - column - }; - try (Cursor cursor = context.getContentResolver().query(uri, projection, null, null, - null)) { - if (cursor != null && cursor.moveToFirst()) { - final int column_index = cursor.getColumnIndexOrThrow(column); - return cursor.getString(column_index); - } - } catch (Exception e) { - Log.e(TAG, e.getMessage()); - } - return null; - } - - /** - * Async - */ - public static void playSongAt(final int position) { - if (musicService != null) { - musicService.playSongAt(position); - } - } - - public static void pauseSong() { - if (musicService != null) { - musicService.pause(); - } - } - - /** - * Async - */ - public static void playNextSong() { - if (musicService != null) { - musicService.playNextSong(true); - } - } - - /** - * Async - */ - public static void playPreviousSong() { - if (musicService != null) { - musicService.playPreviousSong(true); - } - } - - /** - * Async - */ - public static void back() { - if (musicService != null) { - musicService.back(true); - } - } - - public static boolean isPlaying() { - return musicService != null && musicService.isPlaying(); - } - - public static void resumePlaying() { - if (musicService != null) { - musicService.play(); - } - } - - /** - * Async - */ - public static void openQueue(final ArrayList queue, final int startPosition, final boolean startPlaying) { - if (!tryToHandleOpenPlayingQueue(queue, startPosition, startPlaying) && musicService != null) { - musicService.openQueue(queue, startPosition, startPlaying); - if (PreferenceUtil.getInstance().isShuffleModeOn()) - setShuffleMode(MusicService.SHUFFLE_MODE_NONE); - } - } - - /** - * Async - */ - public static void openAndShuffleQueue(final ArrayList queue, boolean startPlaying) { - int startPosition = 0; - if (!queue.isEmpty()) { - startPosition = new Random().nextInt(queue.size()); - } - - if (!tryToHandleOpenPlayingQueue(queue, startPosition, startPlaying) && musicService != null) { - openQueue(queue, startPosition, startPlaying); - setShuffleMode(MusicService.SHUFFLE_MODE_SHUFFLE); - } - } - - private static boolean tryToHandleOpenPlayingQueue(final ArrayList queue, final int startPosition, final boolean startPlaying) { - if (getPlayingQueue() == queue) { - if (startPlaying) { - playSongAt(startPosition); - } else { - setPosition(startPosition); - } - return true; - } - return false; - } - - public static Song getCurrentSong() { - if (musicService != null) { - return musicService.getCurrentSong(); - } - return Song.EMPTY_SONG; - } - - public static int getPosition() { - if (musicService != null) { - return musicService.getPosition(); - } - return -1; - } - - /** - * Async - */ - public static void setPosition(final int position) { - if (musicService != null) { - musicService.setPosition(position); - } - } - - public static ArrayList getPlayingQueue() { - if (musicService != null) { - return musicService.getPlayingQueue(); - } - return new ArrayList<>(); - } - - public static int getSongProgressMillis() { - if (musicService != null) { - return musicService.getSongProgressMillis(); - } - return -1; - } - - public static int getSongDurationMillis() { - if (musicService != null) { - return musicService.getSongDurationMillis(); - } - return -1; - } - - public static long getQueueDurationMillis(int position) { - if (musicService != null) { - return musicService.getQueueDurationMillis(position); - } - return -1; - } - - public static int seekTo(int millis) { - if (musicService != null) { - return musicService.seek(millis); - } - return -1; - } - - public static int getRepeatMode() { - if (musicService != null) { - return musicService.getRepeatMode(); - } - return MusicService.REPEAT_MODE_NONE; - } - - public static int getShuffleMode() { - if (musicService != null) { - return musicService.getShuffleMode(); - } - return MusicService.SHUFFLE_MODE_NONE; - } - - public static boolean cycleRepeatMode() { - if (musicService != null) { - musicService.cycleRepeatMode(); - return true; - } - return false; - } - - public static boolean toggleShuffleMode() { - if (musicService != null) { - musicService.toggleShuffle(); - return true; - } - return false; - } - - public static boolean setShuffleMode(final int shuffleMode) { - if (musicService != null) { - musicService.setShuffleMode(shuffleMode); - return true; - } - return false; - } - - public static boolean playNext(Song song) { - if (musicService != null) { - if (getPlayingQueue().size() > 0) { - musicService.addSong(getPosition() + 1, song); - } else { - ArrayList queue = new ArrayList<>(); - queue.add(song); - openQueue(queue, 0, false); - } - Toast.makeText(musicService, musicService.getResources().getString(R.string.added_title_to_playing_queue), Toast.LENGTH_SHORT).show(); - return true; - } - return false; - } - - public static boolean playNext(@NonNull ArrayList songs) { - if (musicService != null) { - if (getPlayingQueue().size() > 0) { - musicService.addSongs(getPosition() + 1, songs); - } else { - openQueue(songs, 0, false); - } - final String toast = songs.size() == 1 ? musicService.getResources().getString(R.string.added_title_to_playing_queue) : musicService.getResources().getString(R.string.added_x_titles_to_playing_queue, songs.size()); - Toast.makeText(musicService, toast, Toast.LENGTH_SHORT).show(); - return true; - } - return false; - } - - public static boolean enqueue(Song song) { - if (musicService != null) { - if (getPlayingQueue().size() > 0) { - musicService.addSong(song); - } else { - ArrayList queue = new ArrayList<>(); - queue.add(song); - openQueue(queue, 0, false); - } - Toast.makeText(musicService, musicService.getResources().getString(R.string.added_title_to_playing_queue), Toast.LENGTH_SHORT).show(); - return true; - } - return false; - } - - public static boolean enqueue(@NonNull ArrayList songs) { - if (musicService != null) { - if (getPlayingQueue().size() > 0) { - musicService.addSongs(songs); - } else { - openQueue(songs, 0, false); - } - final String toast = songs.size() == 1 ? musicService.getResources().getString(R.string.added_title_to_playing_queue) : musicService.getResources().getString(R.string.added_x_titles_to_playing_queue, songs.size()); - Toast.makeText(musicService, toast, Toast.LENGTH_SHORT).show(); - return true; - } - return false; - } - - public static boolean removeFromQueue(@NonNull Song song) { - if (musicService != null) { - musicService.removeSong(song); - return true; - } - return false; - } - - public static boolean removeFromQueue(int position) { - if (musicService != null && position >= 0 && position < getPlayingQueue().size()) { - musicService.removeSong(position); - return true; - } - return false; - } - - public static boolean moveSong(int from, int to) { - if (musicService != null && from >= 0 && to >= 0 && from < getPlayingQueue().size() && to < getPlayingQueue().size()) { - musicService.moveSong(from, to); - return true; - } - return false; - } - - public static boolean clearQueue() { - if (musicService != null) { - musicService.clearQueue(); - return true; - } - return false; - } - - public static int getAudioSessionId() { - if (musicService != null) { - return musicService.getAudioSessionId(); - } - return -1; - } - - public static void playFromUri(Uri uri) { - if (musicService != null) { - ArrayList songs = null; - if (uri.getScheme() != null && uri.getAuthority() != null) { - if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) { - String songId = null; - if (uri.getAuthority().equals("com.android.providers.media.documents")) { - songId = getSongIdFromMediaProvider(uri); - } else if (uri.getAuthority().equals("media")) { - songId = uri.getLastPathSegment(); - } - if (songId != null) { - /* songs = SongLoader.getSongs(SongLoader.makeSongCursor( - musicService, - MediaStore.Audio.AudioColumns._ID + "=?", - new String[]{songId} - ));*/ - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor( - musicService, - MediaStore.Audio.AudioColumns._ID + "=?", - new String[]{songId})) - .subscribeOn(Schedulers.io()).blockingFirst(); - } - } - } - if (songs == null) { - File songFile = null; - if (uri.getAuthority() != null && uri.getAuthority().equals("com.android.externalstorage.documents")) { - songFile = new File(Environment.getExternalStorageDirectory(), uri.getPath().split(":", 2)[1]); - } - if (songFile == null) { - String path = getFilePathFromUri(musicService, uri); - if (path != null) - songFile = new File(path); - } - if (songFile == null && uri.getPath() != null) { - songFile = new File(uri.getPath()); - } - if (songFile != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor( - musicService, - MediaStore.Audio.AudioColumns.DATA + "=?", - new String[]{songFile.getAbsolutePath()} - )).blockingFirst(); - } - } - if (songs != null && !songs.isEmpty()) { - openQueue(songs, 0, true); - } else { - //TODO the file is not listed in the media store - } - } - } - - @TargetApi(Build.VERSION_CODES.KITKAT) - private static String getSongIdFromMediaProvider(Uri uri) { - return DocumentsContract.getDocumentId(uri).split(":")[1]; - } - - public static boolean isServiceConnected() { - return musicService != null; - } - - @interface PlaybackLocation { - int REMOTE = 0; - int LOCAL = 1; - } - - public static final class ServiceBinder implements ServiceConnection { - private final ServiceConnection mCallback; - - ServiceBinder(final ServiceConnection callback) { - mCallback = callback; - } - - @Override - public void onServiceConnected(final ComponentName className, final IBinder service) { - MusicService.MusicBinder binder = (MusicService.MusicBinder) service; - musicService = binder.getService(); - if (mCallback != null) { - mCallback.onServiceConnected(className, service); - } - } - - @Override - public void onServiceDisconnected(final ComponentName className) { - if (mCallback != null) { - mCallback.onServiceDisconnected(className); - } - musicService = null; - } - } - - public static final class ServiceToken { - ContextWrapper mWrappedContext; - - ServiceToken(final ContextWrapper context) { - mWrappedContext = context; - } - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/MusicPlayerRemote.kt b/app/src/main/java/code/name/monkey/retromusic/helper/MusicPlayerRemote.kt new file mode 100644 index 00000000..cf685bb2 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/MusicPlayerRemote.kt @@ -0,0 +1,440 @@ +package code.name.monkey.retromusic.helper + +import android.annotation.TargetApi +import android.app.Activity +import android.content.* +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.os.IBinder +import android.provider.DocumentsContract +import android.provider.MediaStore +import android.util.Log +import android.widget.Toast +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.RetroApplication +import code.name.monkey.retromusic.loaders.SongLoader +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.service.MusicService +import code.name.monkey.retromusic.util.PreferenceUtil +import com.google.android.gms.cast.framework.CastContext +import com.google.android.gms.cast.framework.CastSession +import io.reactivex.schedulers.Schedulers +import java.io.File +import java.util.* + + +object MusicPlayerRemote { + val TAG = MusicPlayerRemote::class.java.simpleName + private val mConnectionMap = WeakHashMap() + var musicService: MusicService? = null + private var playbackLocation = PlaybackLocation.LOCAL + + + private val castSession: CastSession? + get() { + val castSession = CastContext.getSharedInstance(RetroApplication.instance).sessionManager.currentCastSession + if (castSession != null) { + playbackLocation = PlaybackLocation.REMOTE + } else { + playbackLocation = PlaybackLocation.LOCAL + } + return castSession + } + + val isPlaying: Boolean + get() = musicService != null && musicService!!.isPlaying + + val currentSong: Song + get() = if (musicService != null) { + musicService!!.currentSong + } else Song.EMPTY_SONG + + /** + * Async + */ + var position: Int + get() = if (musicService != null) { + musicService!!.position + } else -1 + set(position) { + if (musicService != null) { + musicService!!.position = position + } + } + + val playingQueue: ArrayList + get() = if (musicService != null) { + musicService!!.playingQueue + } else ArrayList() + + val songProgressMillis: Int + get() = if (musicService != null) { + musicService!!.songProgressMillis + } else -1 + + val songDurationMillis: Int + get() = if (musicService != null) { + musicService!!.songDurationMillis + } else -1 + + val repeatMode: Int + get() = if (musicService != null) { + musicService!!.repeatMode + } else MusicService.REPEAT_MODE_NONE + + val shuffleMode: Int + get() = if (musicService != null) { + musicService!!.shuffleMode + } else MusicService.SHUFFLE_MODE_NONE + + val audioSessionId: Int + get() = if (musicService != null) { + musicService!!.audioSessionId + } else -1 + + val isServiceConnected: Boolean + get() = musicService != null + + fun bindToService(context: Context, + callback: ServiceConnection): ServiceToken? { + + var realActivity: Activity? = (context as Activity).parent + if (realActivity == null) { + realActivity = context + } + + val contextWrapper = ContextWrapper(realActivity) + contextWrapper.startService(Intent(contextWrapper, MusicService::class.java)) + + val binder = ServiceBinder(callback) + + if (contextWrapper.bindService(Intent().setClass(contextWrapper, MusicService::class.java), binder, Context.BIND_AUTO_CREATE)) { + mConnectionMap[contextWrapper] = binder + return ServiceToken(contextWrapper) + } + return null + } + + fun unbindFromService(token: ServiceToken?) { + if (token == null) { + return + } + val mContextWrapper = token.mWrappedContext + val mBinder = mConnectionMap.remove(mContextWrapper) ?: return + mContextWrapper.unbindService(mBinder) + if (mConnectionMap.isEmpty()) { + musicService = null + } + } + + private fun getFilePathFromUri(context: Context, uri: Uri): String? { + + val column = "_data" + val projection = arrayOf(column) + try { + context.contentResolver.query(uri, projection, null, null, null)!!.use { cursor -> + if (cursor.moveToFirst()) { + val column_index = cursor.getColumnIndexOrThrow(column) + return cursor.getString(column_index) + } + } + } catch (e: Exception) { + Log.e(TAG, e.message) + } + + return null + } + + /** + * Async + */ + fun playSongAt(position: Int) { + if (musicService != null) { + musicService!!.playSongAt(position) + } + } + + fun pauseSong() { + if (musicService != null) { + musicService!!.pause() + } + } + + /** + * Async + */ + fun playNextSong() { + if (musicService != null) { + musicService!!.playNextSong(true) + } + } + + /** + * Async + */ + fun playPreviousSong() { + if (musicService != null) { + musicService!!.playPreviousSong(true) + } + } + + /** + * Async + */ + fun back() { + if (musicService != null) { + musicService!!.back(true) + } + } + + fun resumePlaying() { + if (musicService != null) { + musicService!!.play() + } + } + + /** + * Async + */ + fun openQueue(queue: ArrayList, startPosition: Int, startPlaying: Boolean) { + if (!tryToHandleOpenPlayingQueue(queue, startPosition, startPlaying) && musicService != null) { + musicService!!.openQueue(queue, startPosition, startPlaying) + if (PreferenceUtil.getInstance().isShuffleModeOn) + setShuffleMode(MusicService.SHUFFLE_MODE_NONE) + } + } + + /** + * Async + */ + fun openAndShuffleQueue(queue: ArrayList, startPlaying: Boolean) { + var startPosition = 0 + if (!queue.isEmpty()) { + startPosition = Random().nextInt(queue.size) + } + + if (!tryToHandleOpenPlayingQueue(queue, startPosition, startPlaying) && musicService != null) { + openQueue(queue, startPosition, startPlaying) + setShuffleMode(MusicService.SHUFFLE_MODE_SHUFFLE) + } + } + + private fun tryToHandleOpenPlayingQueue(queue: ArrayList, startPosition: Int, startPlaying: Boolean): Boolean { + if (playingQueue === queue) { + if (startPlaying) { + playSongAt(startPosition) + } else { + position = startPosition + } + return true + } + return false + } + + fun getQueueDurationMillis(position: Int): Long { + return if (musicService != null) { + musicService!!.getQueueDurationMillis(position) + } else -1 + } + + fun seekTo(millis: Int): Int { + return if (musicService != null) { + musicService!!.seek(millis) + } else -1 + } + + fun cycleRepeatMode(): Boolean { + if (musicService != null) { + musicService!!.cycleRepeatMode() + return true + } + return false + } + + fun toggleShuffleMode(): Boolean { + if (musicService != null) { + musicService!!.toggleShuffle() + return true + } + return false + } + + fun setShuffleMode(shuffleMode: Int): Boolean { + if (musicService != null) { + musicService!!.shuffleMode = shuffleMode + return true + } + return false + } + + fun playNext(song: Song): Boolean { + if (musicService != null) { + if (playingQueue.size > 0) { + musicService!!.addSong(position + 1, song) + } else { + val queue = ArrayList() + queue.add(song) + openQueue(queue, 0, false) + } + Toast.makeText(musicService, musicService!!.resources.getString(R.string.added_title_to_playing_queue), Toast.LENGTH_SHORT).show() + return true + } + return false + } + + fun playNext(songs: ArrayList): Boolean { + if (musicService != null) { + if (playingQueue.size > 0) { + musicService!!.addSongs(position + 1, songs) + } else { + openQueue(songs, 0, false) + } + val toast = if (songs.size == 1) musicService!!.resources.getString(R.string.added_title_to_playing_queue) else musicService!!.resources.getString(R.string.added_x_titles_to_playing_queue, songs.size) + Toast.makeText(musicService, toast, Toast.LENGTH_SHORT).show() + return true + } + return false + } + + fun enqueue(song: Song): Boolean { + if (musicService != null) { + if (playingQueue.size > 0) { + musicService!!.addSong(song) + } else { + val queue = ArrayList() + queue.add(song) + openQueue(queue, 0, false) + } + Toast.makeText(musicService, musicService!!.resources.getString(R.string.added_title_to_playing_queue), Toast.LENGTH_SHORT).show() + return true + } + return false + } + + fun enqueue(songs: ArrayList): Boolean { + if (musicService != null) { + if (playingQueue.size > 0) { + musicService!!.addSongs(songs) + } else { + openQueue(songs, 0, false) + } + val toast = if (songs.size == 1) musicService!!.resources.getString(R.string.added_title_to_playing_queue) else musicService!!.resources.getString(R.string.added_x_titles_to_playing_queue, songs.size) + Toast.makeText(musicService, toast, Toast.LENGTH_SHORT).show() + return true + } + return false + } + + fun removeFromQueue(song: Song): Boolean { + if (musicService != null) { + musicService!!.removeSong(song) + return true + } + return false + } + + fun removeFromQueue(position: Int): Boolean { + if (musicService != null && position >= 0 && position < playingQueue.size) { + musicService!!.removeSong(position) + return true + } + return false + } + + fun moveSong(from: Int, to: Int): Boolean { + if (musicService != null && from >= 0 && to >= 0 && from < playingQueue.size && to < playingQueue.size) { + musicService!!.moveSong(from, to) + return true + } + return false + } + + fun clearQueue(): Boolean { + if (musicService != null) { + musicService!!.clearQueue() + return true + } + return false + } + + fun playFromUri(uri: Uri) { + if (musicService != null) { + var songs: ArrayList? = null + if (uri.scheme != null && uri.authority != null) { + if (uri.scheme == ContentResolver.SCHEME_CONTENT) { + var songId: String? = null + if (uri.authority == "com.android.providers.media.documents") { + songId = getSongIdFromMediaProvider(uri) + } else if (uri.authority == "media") { + songId = uri.lastPathSegment + } + if (songId != null) { + /* songs = SongLoader.getSongs(SongLoader.makeSongCursor( + musicService, + MediaStore.Audio.AudioColumns._ID + "=?", + new String[]{songId} + ));*/ + songs = SongLoader.getSongs(SongLoader.makeSongCursor( + musicService!!, + MediaStore.Audio.AudioColumns._ID + "=?", + arrayOf(songId))) + .subscribeOn(Schedulers.io()).blockingFirst() + } + } + } + if (songs == null) { + var songFile: File? = null + if (uri.authority != null && uri.authority == "com.android.externalstorage.documents") { + songFile = File(Environment.getExternalStorageDirectory(), uri.path!!.split(":".toRegex(), 2).toTypedArray()[1]) + } + if (songFile == null) { + val path = getFilePathFromUri(musicService!!, uri) + if (path != null) + songFile = File(path) + } + if (songFile == null && uri.path != null) { + songFile = File(uri.path) + } + if (songFile != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(musicService!!, MediaStore.Audio.AudioColumns.DATA + "=?", arrayOf(songFile.absolutePath) + )).blockingFirst() + } + } + if (songs != null && !songs.isEmpty()) { + openQueue(songs, 0, true) + } else { + //TODO the file is not listed in the media store + } + } + } + + @TargetApi(Build.VERSION_CODES.KITKAT) + private fun getSongIdFromMediaProvider(uri: Uri): String { + return DocumentsContract.getDocumentId(uri).split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1] + } + + internal annotation class PlaybackLocation { + companion object { + val REMOTE = 0 + val LOCAL = 1 + } + } + + class ServiceBinder internal constructor(private val mCallback: ServiceConnection?) : ServiceConnection { + + override fun onServiceConnected(className: ComponentName, service: IBinder) { + val binder = service as MusicService.MusicBinder + musicService = binder.service + mCallback?.onServiceConnected(className, service) + } + + override fun onServiceDisconnected(className: ComponentName) { + mCallback?.onServiceDisconnected(className) + musicService = null + } + } + + class ServiceToken internal constructor(internal var mWrappedContext: ContextWrapper) + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/MusicProgressViewUpdateHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/MusicProgressViewUpdateHelper.java deleted file mode 100644 index 4559a240..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/MusicProgressViewUpdateHelper.java +++ /dev/null @@ -1,71 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.os.Handler; -import android.os.Message; -import androidx.annotation.NonNull; - - -public class MusicProgressViewUpdateHelper extends Handler { - private static final int CMD_REFRESH_PROGRESS_VIEWS = 1; - - private static final int MIN_INTERVAL = 20; - private static final int UPDATE_INTERVAL_PLAYING = 1000; - private static final int UPDATE_INTERVAL_PAUSED = 500; - - private Callback callback; - private int intervalPlaying; - private int intervalPaused; - - public void start() { - queueNextRefresh(1); - } - - public void stop() { - removeMessages(CMD_REFRESH_PROGRESS_VIEWS); - } - - public MusicProgressViewUpdateHelper(Callback callback) { - this.callback = callback; - this.intervalPlaying = UPDATE_INTERVAL_PLAYING; - this.intervalPaused = UPDATE_INTERVAL_PAUSED; - } - - public MusicProgressViewUpdateHelper(Callback callback, int intervalPlaying, int intervalPaused) { - this.callback = callback; - this.intervalPlaying = intervalPlaying; - this.intervalPaused = intervalPaused; - } - - @Override - public void handleMessage(@NonNull Message msg) { - super.handleMessage(msg); - if (msg.what == CMD_REFRESH_PROGRESS_VIEWS) { - queueNextRefresh(refreshProgressViews()); - } - } - - private int refreshProgressViews() { - final int progressMillis = MusicPlayerRemote.getSongProgressMillis(); - final int totalMillis = MusicPlayerRemote.getSongDurationMillis(); - - callback.onUpdateProgressViews(progressMillis, totalMillis); - - if (!MusicPlayerRemote.isPlaying()) { - return intervalPaused; - } - - final int remainingMillis = intervalPlaying - progressMillis % intervalPlaying; - - return Math.max(MIN_INTERVAL, remainingMillis); - } - - private void queueNextRefresh(final long delay) { - final Message message = obtainMessage(CMD_REFRESH_PROGRESS_VIEWS); - removeMessages(CMD_REFRESH_PROGRESS_VIEWS); - sendMessageDelayed(message, delay); - } - - public interface Callback { - void onUpdateProgressViews(int progress, int total); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/MusicProgressViewUpdateHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/MusicProgressViewUpdateHelper.kt new file mode 100644 index 00000000..3103452e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/MusicProgressViewUpdateHelper.kt @@ -0,0 +1,72 @@ +package code.name.monkey.retromusic.helper + +import android.os.Handler +import android.os.Message + + +class MusicProgressViewUpdateHelper : Handler { + + private var callback: Callback? = null + private var intervalPlaying: Int = 0 + private var intervalPaused: Int = 0 + + fun start() { + queueNextRefresh(1) + } + + fun stop() { + removeMessages(CMD_REFRESH_PROGRESS_VIEWS) + } + + constructor(callback: Callback) { + this.callback = callback + this.intervalPlaying = UPDATE_INTERVAL_PLAYING + this.intervalPaused = UPDATE_INTERVAL_PAUSED + } + + constructor(callback: Callback, intervalPlaying: Int, intervalPaused: Int) { + this.callback = callback + this.intervalPlaying = intervalPlaying + this.intervalPaused = intervalPaused + } + + override fun handleMessage(msg: Message) { + super.handleMessage(msg) + if (msg.what == CMD_REFRESH_PROGRESS_VIEWS) { + queueNextRefresh(refreshProgressViews().toLong()) + } + } + + private fun refreshProgressViews(): Int { + val progressMillis = MusicPlayerRemote.songProgressMillis + val totalMillis = MusicPlayerRemote.songDurationMillis + + callback!!.onUpdateProgressViews(progressMillis, totalMillis) + + if (!MusicPlayerRemote.isPlaying) { + return intervalPaused + } + + val remainingMillis = intervalPlaying - progressMillis % intervalPlaying + + return Math.max(MIN_INTERVAL, remainingMillis) + } + + private fun queueNextRefresh(delay: Long) { + val message = obtainMessage(CMD_REFRESH_PROGRESS_VIEWS) + removeMessages(CMD_REFRESH_PROGRESS_VIEWS) + sendMessageDelayed(message, delay) + } + + interface Callback { + fun onUpdateProgressViews(progress: Int, total: Int) + } + + companion object { + private val CMD_REFRESH_PROGRESS_VIEWS = 1 + + private val MIN_INTERVAL = 20 + private val UPDATE_INTERVAL_PLAYING = 1000 + private val UPDATE_INTERVAL_PAUSED = 500 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/PlayPauseButtonOnClickHandler.java b/app/src/main/java/code/name/monkey/retromusic/helper/PlayPauseButtonOnClickHandler.java deleted file mode 100644 index 4d69a5a4..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/PlayPauseButtonOnClickHandler.java +++ /dev/null @@ -1,15 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.view.View; - - -public class PlayPauseButtonOnClickHandler implements View.OnClickListener { - @Override - public void onClick(View v) { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/PlayPauseButtonOnClickHandler.kt b/app/src/main/java/code/name/monkey/retromusic/helper/PlayPauseButtonOnClickHandler.kt new file mode 100644 index 00000000..5e8b3c66 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/PlayPauseButtonOnClickHandler.kt @@ -0,0 +1,14 @@ +package code.name.monkey.retromusic.helper + +import android.view.View + + +class PlayPauseButtonOnClickHandler : View.OnClickListener { + override fun onClick(v: View) { + if (MusicPlayerRemote.isPlaying) { + MusicPlayerRemote.pauseSong() + } else { + MusicPlayerRemote.resumePlaying() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/SearchQueryHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/SearchQueryHelper.java deleted file mode 100644 index acef195a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/SearchQueryHelper.java +++ /dev/null @@ -1,91 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import android.app.SearchManager; -import android.content.Context; -import android.os.Bundle; -import android.provider.MediaStore; -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.loaders.SongLoader; -import code.name.monkey.retromusic.model.Song; - - -public class SearchQueryHelper { - private static final String TITLE_SELECTION = "lower(" + MediaStore.Audio.AudioColumns.TITLE + ") = ?"; - private static final String ALBUM_SELECTION = "lower(" + MediaStore.Audio.AudioColumns.ALBUM + ") = ?"; - private static final String ARTIST_SELECTION = "lower(" + MediaStore.Audio.AudioColumns.ARTIST + ") = ?"; - private static final String AND = " AND "; - private static ArrayList songs = new ArrayList<>(); - - public static ArrayList getSongs() { - return songs; - } - - public static void setSongs(ArrayList songs) { - SearchQueryHelper.songs = songs; - } - - @NonNull - public static ArrayList getSongs(@NonNull final Context context, @NonNull final Bundle extras) { - final String query = extras.getString(SearchManager.QUERY, null); - final String artistName = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST, null); - final String albumName = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM, null); - final String titleName = extras.getString(MediaStore.EXTRA_MEDIA_TITLE, null); - - ArrayList songs = new ArrayList<>(); - if (artistName != null && albumName != null && titleName != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ARTIST_SELECTION + AND + ALBUM_SELECTION + AND + TITLE_SELECTION, new String[]{artistName.toLowerCase(), albumName.toLowerCase(), titleName.toLowerCase()})).blockingFirst(); - } - if (!songs.isEmpty()) { - return songs; - } - if (artistName != null && titleName != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ARTIST_SELECTION + AND + TITLE_SELECTION, new String[]{artistName.toLowerCase(), titleName.toLowerCase()})).blockingFirst(); - } - if (!songs.isEmpty()) { - return songs; - } - if (albumName != null && titleName != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ALBUM_SELECTION + AND + TITLE_SELECTION, new String[]{albumName.toLowerCase(), titleName.toLowerCase()})).blockingFirst(); - } - if (!songs.isEmpty()) { - return songs; - } - if (artistName != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ARTIST_SELECTION, new String[]{artistName.toLowerCase()})).blockingFirst(); - } - if (!songs.isEmpty()) { - return songs; - } - if (albumName != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ALBUM_SELECTION, new String[]{albumName.toLowerCase()})).blockingFirst(); - } - if (!songs.isEmpty()) { - return songs; - } - if (titleName != null) { - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, TITLE_SELECTION, new String[]{titleName.toLowerCase()})).blockingFirst(); - } - if (!songs.isEmpty()) { - return songs; - } - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ARTIST_SELECTION, new String[]{query.toLowerCase()})).blockingFirst(); - - if (!songs.isEmpty()) { - return songs; - } - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, ALBUM_SELECTION, new String[]{query.toLowerCase()})).blockingFirst(); - if (!songs.isEmpty()) { - return songs; - } - songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, TITLE_SELECTION, new String[]{query.toLowerCase()})).blockingFirst(); - if (!songs.isEmpty()) { - return songs; - } - return new ArrayList(); - } - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/SearchQueryHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/SearchQueryHelper.kt new file mode 100644 index 00000000..44b09581 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/SearchQueryHelper.kt @@ -0,0 +1,78 @@ +package code.name.monkey.retromusic.helper + +import android.app.SearchManager +import android.content.Context +import android.os.Bundle +import android.provider.MediaStore +import code.name.monkey.retromusic.loaders.SongLoader +import code.name.monkey.retromusic.model.Song +import java.util.* + + +object SearchQueryHelper { + private val TITLE_SELECTION = "lower(" + MediaStore.Audio.AudioColumns.TITLE + ") = ?" + private val ALBUM_SELECTION = "lower(" + MediaStore.Audio.AudioColumns.ALBUM + ") = ?" + private val ARTIST_SELECTION = "lower(" + MediaStore.Audio.AudioColumns.ARTIST + ") = ?" + private val AND = " AND " + var songs = ArrayList() + + fun getSongs(context: Context, extras: Bundle): ArrayList { + val query = extras.getString(SearchManager.QUERY, null) + val artistName = extras.getString(MediaStore.EXTRA_MEDIA_ARTIST, null) + val albumName = extras.getString(MediaStore.EXTRA_MEDIA_ALBUM, null) + val titleName = extras.getString(MediaStore.EXTRA_MEDIA_TITLE, null) + + var songs = ArrayList() + if (artistName != null && albumName != null && titleName != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ARTIST_SELECTION + AND + ALBUM_SELECTION + AND + TITLE_SELECTION, arrayOf(artistName.toLowerCase(), albumName.toLowerCase(), titleName.toLowerCase()))).blockingFirst() + } + if (!songs.isEmpty()) { + return songs + } + if (artistName != null && titleName != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ARTIST_SELECTION + AND + TITLE_SELECTION, arrayOf(artistName.toLowerCase(), titleName.toLowerCase()))).blockingFirst() + } + if (!songs.isEmpty()) { + return songs + } + if (albumName != null && titleName != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ALBUM_SELECTION + AND + TITLE_SELECTION, arrayOf(albumName.toLowerCase(), titleName.toLowerCase()))).blockingFirst() + } + if (!songs.isEmpty()) { + return songs + } + if (artistName != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ARTIST_SELECTION, arrayOf(artistName.toLowerCase()))).blockingFirst() + } + if (!songs.isEmpty()) { + return songs + } + if (albumName != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ALBUM_SELECTION, arrayOf(albumName.toLowerCase()))).blockingFirst() + } + if (!songs.isEmpty()) { + return songs + } + if (titleName != null) { + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, TITLE_SELECTION, arrayOf(titleName.toLowerCase()))).blockingFirst() + } + if (!songs.isEmpty()) { + return songs + } + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ARTIST_SELECTION, arrayOf(query.toLowerCase()))).blockingFirst() + + if (!songs.isEmpty()) { + return songs + } + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, ALBUM_SELECTION, arrayOf(query.toLowerCase()))).blockingFirst() + if (!songs.isEmpty()) { + return songs + } + songs = SongLoader.getSongs(SongLoader.makeSongCursor(context, TITLE_SELECTION, arrayOf(query.toLowerCase()))).blockingFirst() + return if (!songs.isEmpty()) { + songs + } else ArrayList() + } + + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/ShuffleHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/ShuffleHelper.java deleted file mode 100644 index 46721017..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/ShuffleHelper.java +++ /dev/null @@ -1,25 +0,0 @@ -package code.name.monkey.retromusic.helper; - -import androidx.annotation.NonNull; - -import code.name.monkey.retromusic.model.Song; - -import java.util.Collections; -import java.util.List; - - -public class ShuffleHelper { - - public static void makeShuffleList(@NonNull List listToShuffle, final int current) { - if (listToShuffle.isEmpty()) return; - if (current >= 0) { - Song song = listToShuffle.remove(current); - Collections.shuffle(listToShuffle); - listToShuffle.add(0, song); - } else { - Collections.shuffle(listToShuffle); - } - } - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/ShuffleHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/ShuffleHelper.kt new file mode 100644 index 00000000..aa50421b --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/ShuffleHelper.kt @@ -0,0 +1,20 @@ +package code.name.monkey.retromusic.helper + +import code.name.monkey.retromusic.model.Song + +import java.util.Collections + + +object ShuffleHelper { + + fun makeShuffleList(listToShuffle: MutableList, current: Int) { + if (listToShuffle.isEmpty()) return + if (current >= 0) { + val song = listToShuffle.removeAt(current) + listToShuffle.shuffle() + listToShuffle.add(0, song) + } else { + listToShuffle.shuffle() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/SortOrder.java b/app/src/main/java/code/name/monkey/retromusic/helper/SortOrder.java deleted file mode 100644 index 2c871702..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/SortOrder.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (C) 2012 Andrew Neal 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 code.name.monkey.retromusic.helper; - -import android.provider.MediaStore; - -/** - * Holds all of the sort orders for each list type. - * - * @author Andrew Neal (andrewdneal@gmail.com) - */ -public final class SortOrder { - - /** - * This class is never instantiated - */ - public SortOrder() { - } - - /** - * Artist sort order entries. - */ - public interface ArtistSortOrder { - - /* Artist sort order A-Z */ - String ARTIST_A_Z = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER; - - /* Artist sort order Z-A */ - String ARTIST_Z_A = ARTIST_A_Z + " DESC"; - - /* Artist sort order number of songs */ - String ARTIST_NUMBER_OF_SONGS = MediaStore.Audio.Artists.NUMBER_OF_TRACKS - + " DESC"; - - /* Artist sort order number of albums */ - String ARTIST_NUMBER_OF_ALBUMS = MediaStore.Audio.Artists.NUMBER_OF_ALBUMS - + " DESC"; - } - - /** - * Album sort order entries. - */ - public interface AlbumSortOrder { - - /* Album sort order A-Z */ - String ALBUM_A_Z = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER; - - /* Album sort order Z-A */ - String ALBUM_Z_A = ALBUM_A_Z + " DESC"; - - /* Album sort order songs */ - String ALBUM_NUMBER_OF_SONGS = MediaStore.Audio.Albums.NUMBER_OF_SONGS - + " DESC"; - - /* Album sort order artist */ - String ALBUM_ARTIST = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER - + ", " + MediaStore.Audio.Albums.DEFAULT_SORT_ORDER; - - /* Album sort order year */ - String ALBUM_YEAR = MediaStore.Audio.Media.YEAR + " DESC"; - } - - /** - * Song sort order entries. - */ - public interface SongSortOrder { - - /* Song sort order A-Z */ - String SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER; - - /* Song sort order Z-A */ - String SONG_Z_A = SONG_A_Z + " DESC"; - - /* Song sort order artist */ - String SONG_ARTIST = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER; - - /* Song sort order album */ - String SONG_ALBUM = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER; - - /* Song sort order year */ - String SONG_YEAR = MediaStore.Audio.Media.YEAR + " DESC"; - - /* Song sort order duration */ - String SONG_DURATION = MediaStore.Audio.Media.DURATION + " DESC"; - - /* Song sort order date */ - String SONG_DATE = MediaStore.Audio.Media.DATE_ADDED + " DESC"; - } - - /** - * Album song sort order entries. - */ - public interface AlbumSongSortOrder { - - /* Album song sort order A-Z */ - String SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER; - - /* Album song sort order Z-A */ - String SONG_Z_A = SONG_A_Z + " DESC"; - - /* Album song sort order track list */ - String SONG_TRACK_LIST = MediaStore.Audio.Media.TRACK + ", " - + MediaStore.Audio.Media.DEFAULT_SORT_ORDER; - - /* Album song sort order duration */ - String SONG_DURATION = SongSortOrder.SONG_DURATION; - } - - /** - * Artist song sort order entries. - */ - public interface ArtistSongSortOrder { - - /* Artist song sort order A-Z */ - String SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER; - - /* Artist song sort order Z-A */ - String SONG_Z_A = SONG_A_Z + " DESC"; - - /* Artist song sort order album */ - String SONG_ALBUM = MediaStore.Audio.Media.ALBUM; - - /* Artist song sort order year */ - String SONG_YEAR = MediaStore.Audio.Media.YEAR + " DESC"; - - /* Artist song sort order duration */ - String SONG_DURATION = MediaStore.Audio.Media.DURATION + " DESC"; - - /* Artist song sort order date */ - String SONG_DATE = MediaStore.Audio.Media.DATE_ADDED + " DESC"; - } - - /** - * Artist album sort order entries. - */ - public interface ArtistAlbumSortOrder { - - /* Artist album sort order A-Z */ - String ALBUM_A_Z = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER; - - /* Artist album sort order Z-A */ - String ALBUM_Z_A = ALBUM_A_Z + " DESC"; - - /* Artist album sort order year */ - String ALBUM_YEAR = MediaStore.Audio.Media.YEAR - + " DESC"; - - /* Artist album sort order year */ - String ALBUM_YEAR_ASC = MediaStore.Audio.Media.YEAR - + " ASC"; - } - - /** - * Genre sort order entries. - */ - public interface GenreSortOrder { - - /* Genre sort order A-Z */ - String GENRE_A_Z = MediaStore.Audio.Genres.DEFAULT_SORT_ORDER; - - /* Genre sort order Z-A */ - String ALBUM_Z_A = GENRE_A_Z + " DESC"; - } - -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/SortOrder.kt b/app/src/main/java/code/name/monkey/retromusic/helper/SortOrder.kt new file mode 100644 index 00000000..b2fb952e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/SortOrder.kt @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2012 Andrew Neal 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 code.name.monkey.retromusic.helper + +import android.provider.MediaStore + +/** + * Holds all of the sort orders for each list type. + * + * @author Andrew Neal (andrewdneal@gmail.com) + */ +/** + * This class is never instantiated + */ +class SortOrder { + + /** + * Artist sort order entries. + */ + interface ArtistSortOrder { + companion object { + + /* Artist sort order A-Z */ + val ARTIST_A_Z = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER + + /* Artist sort order Z-A */ + val ARTIST_Z_A = "$ARTIST_A_Z DESC" + + /* Artist sort order number of songs */ + val ARTIST_NUMBER_OF_SONGS = MediaStore.Audio.Artists.NUMBER_OF_TRACKS + " DESC" + + /* Artist sort order number of albums */ + val ARTIST_NUMBER_OF_ALBUMS = MediaStore.Audio.Artists.NUMBER_OF_ALBUMS + " DESC" + } + } + + /** + * Album sort order entries. + */ + interface AlbumSortOrder { + companion object { + + /* Album sort order A-Z */ + val ALBUM_A_Z = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER + + /* Album sort order Z-A */ + val ALBUM_Z_A = "$ALBUM_A_Z DESC" + + /* Album sort order songs */ + val ALBUM_NUMBER_OF_SONGS = MediaStore.Audio.Albums.NUMBER_OF_SONGS + " DESC" + + /* Album sort order artist */ + val ALBUM_ARTIST = (MediaStore.Audio.Artists.DEFAULT_SORT_ORDER + + ", " + MediaStore.Audio.Albums.DEFAULT_SORT_ORDER) + + /* Album sort order year */ + val ALBUM_YEAR = MediaStore.Audio.Media.YEAR + " DESC" + } + } + + /** + * Song sort order entries. + */ + interface SongSortOrder { + companion object { + + /* Song sort order A-Z */ + val SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER + + /* Song sort order Z-A */ + val SONG_Z_A = "$SONG_A_Z DESC" + + /* Song sort order artist */ + val SONG_ARTIST = MediaStore.Audio.Artists.DEFAULT_SORT_ORDER + + /* Song sort order album */ + val SONG_ALBUM = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER + + /* Song sort order year */ + val SONG_YEAR = MediaStore.Audio.Media.YEAR + " DESC" + + /* Song sort order duration */ + val SONG_DURATION = MediaStore.Audio.Media.DURATION + " DESC" + + /* Song sort order date */ + val SONG_DATE = MediaStore.Audio.Media.DATE_ADDED + " DESC" + } + } + + /** + * Album song sort order entries. + */ + interface AlbumSongSortOrder { + companion object { + + /* Album song sort order A-Z */ + val SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER + + /* Album song sort order Z-A */ + val SONG_Z_A = "$SONG_A_Z DESC" + + /* Album song sort order track list */ + val SONG_TRACK_LIST = (MediaStore.Audio.Media.TRACK + ", " + + MediaStore.Audio.Media.DEFAULT_SORT_ORDER) + + /* Album song sort order duration */ + val SONG_DURATION = SongSortOrder.SONG_DURATION + } + } + + /** + * Artist song sort order entries. + */ + interface ArtistSongSortOrder { + companion object { + + /* Artist song sort order A-Z */ + val SONG_A_Z = MediaStore.Audio.Media.DEFAULT_SORT_ORDER + + /* Artist song sort order Z-A */ + val SONG_Z_A = "$SONG_A_Z DESC" + + /* Artist song sort order album */ + val SONG_ALBUM = MediaStore.Audio.Media.ALBUM + + /* Artist song sort order year */ + val SONG_YEAR = MediaStore.Audio.Media.YEAR + " DESC" + + /* Artist song sort order duration */ + val SONG_DURATION = MediaStore.Audio.Media.DURATION + " DESC" + + /* Artist song sort order date */ + val SONG_DATE = MediaStore.Audio.Media.DATE_ADDED + " DESC" + } + } + + /** + * Artist album sort order entries. + */ + interface ArtistAlbumSortOrder { + companion object { + + /* Artist album sort order A-Z */ + val ALBUM_A_Z = MediaStore.Audio.Albums.DEFAULT_SORT_ORDER + + /* Artist album sort order Z-A */ + val ALBUM_Z_A = "$ALBUM_A_Z DESC" + + /* Artist album sort order year */ + val ALBUM_YEAR = MediaStore.Audio.Media.YEAR + " DESC" + + /* Artist album sort order year */ + val ALBUM_YEAR_ASC = MediaStore.Audio.Media.YEAR + " ASC" + } + } + + /** + * Genre sort order entries. + */ + interface GenreSortOrder { + companion object { + + /* Genre sort order A-Z */ + val GENRE_A_Z = MediaStore.Audio.Genres.DEFAULT_SORT_ORDER + + /* Genre sort order Z-A */ + val ALBUM_Z_A = "$GENRE_A_Z DESC" + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/StopWatch.java b/app/src/main/java/code/name/monkey/retromusic/helper/StopWatch.java deleted file mode 100644 index 896f68ac..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/StopWatch.java +++ /dev/null @@ -1,82 +0,0 @@ -package code.name.monkey.retromusic.helper; - -/** - * Simple thread safe stop watch. - * - * @author Karim Abou Zeid (kabouzeid) - */ -public class StopWatch { - - /** - * The time the stop watch was last started. - */ - private long startTime; - - /** - * The time elapsed before the current {@link #startTime}. - */ - private long previousElapsedTime; - - /** - * Whether the stop watch is currently running or not. - */ - private boolean isRunning; - - /** - * Starts or continues the stop watch. - * - * @see #pause() - * @see #reset() - */ - public void start() { - synchronized (this) { - startTime = System.currentTimeMillis(); - isRunning = true; - } - } - - /** - * Pauses the stop watch. It can be continued later from {@link #start()}. - * - * @see #start() - * @see #reset() - */ - public void pause() { - synchronized (this) { - previousElapsedTime += System.currentTimeMillis() - startTime; - isRunning = false; - } - } - - /** - * Stops and resets the stop watch to zero milliseconds. - * - * @see #start() - * @see #pause() - */ - public void reset() { - synchronized (this) { - startTime = 0; - previousElapsedTime = 0; - isRunning = false; - } - } - - /** - * @return the total elapsed time in milliseconds - */ - public final long getElapsedTime() { - synchronized (this) { - long currentElapsedTime = 0; - if (isRunning) { - currentElapsedTime = System.currentTimeMillis() - startTime; - } - return previousElapsedTime + currentElapsedTime; - } - } - - @Override - public String toString() { - return String.format("%d millis", getElapsedTime()); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/StopWatch.kt b/app/src/main/java/code/name/monkey/retromusic/helper/StopWatch.kt new file mode 100644 index 00000000..21ab67fa --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/StopWatch.kt @@ -0,0 +1,80 @@ +package code.name.monkey.retromusic.helper + +/** + * Simple thread safe stop watch. + * + * @author Karim Abou Zeid (kabouzeid) + */ +class StopWatch { + + /** + * The time the stop watch was last started. + */ + private var startTime: Long = 0 + + /** + * The time elapsed before the current [.startTime]. + */ + private var previousElapsedTime: Long = 0 + + /** + * Whether the stop watch is currently running or not. + */ + private var isRunning: Boolean = false + + /** + * @return the total elapsed time in milliseconds + */ + val elapsedTime: Long + get() = synchronized(this) { + var currentElapsedTime: Long = 0 + if (isRunning) { + currentElapsedTime = System.currentTimeMillis() - startTime + } + return previousElapsedTime + currentElapsedTime + } + + /** + * Starts or continues the stop watch. + * + * @see .pause + * @see .reset + */ + fun start() { + synchronized(this) { + startTime = System.currentTimeMillis() + isRunning = true + } + } + + /** + * Pauses the stop watch. It can be continued later from [.start]. + * + * @see .start + * @see .reset + */ + fun pause() { + synchronized(this) { + previousElapsedTime += System.currentTimeMillis() - startTime + isRunning = false + } + } + + /** + * Stops and resets the stop watch to zero milliseconds. + * + * @see .start + * @see .pause + */ + fun reset() { + synchronized(this) { + startTime = 0 + previousElapsedTime = 0 + isRunning = false + } + } + + override fun toString(): String { + return String.format("%d millis", elapsedTime) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/GenreMenuHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/menu/GenreMenuHelper.java deleted file mode 100644 index f78ec189..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/menu/GenreMenuHelper.java +++ /dev/null @@ -1,50 +0,0 @@ -package code.name.monkey.retromusic.helper.menu; - -import android.app.Activity; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import android.view.MenuItem; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.loaders.GenreLoader; -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; - -/** - * @author Hemanth S (h4h13). - */ - -public class GenreMenuHelper { - public static boolean handleMenuClick(@NonNull AppCompatActivity activity, - @NonNull Genre genre, - @NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.action_play: - MusicPlayerRemote.openQueue(getGenreSongs(activity, genre), 0, true); - return true; - case R.id.action_play_next: - MusicPlayerRemote.playNext(getGenreSongs(activity, genre)); - return true; - case R.id.action_add_to_playlist: - AddToPlaylistDialog.create(getGenreSongs(activity, genre)) - .show(activity.getSupportFragmentManager(), "ADD_PLAYLIST"); - return true; - case R.id.action_add_to_current_playing: - MusicPlayerRemote.enqueue(getGenreSongs(activity, genre)); - return true; - } - return false; - } - - @NonNull - private static ArrayList getGenreSongs(@NonNull Activity activity, - @NonNull Genre genre) { - ArrayList songs; - songs = GenreLoader.getSongs(activity, genre.id).blockingFirst(); - return songs; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/GenreMenuHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/menu/GenreMenuHelper.kt new file mode 100644 index 00000000..6796361f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/menu/GenreMenuHelper.kt @@ -0,0 +1,52 @@ +package code.name.monkey.retromusic.helper.menu + +import android.app.Activity +import androidx.appcompat.app.AppCompatActivity +import android.view.MenuItem + +import java.util.ArrayList + +import code.name.monkey.retromusic.loaders.GenreLoader +import code.name.monkey.retromusic.model.Genre +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog +import code.name.monkey.retromusic.helper.MusicPlayerRemote + +/** + * @author Hemanth S (h4h13). + */ + +object GenreMenuHelper { + fun handleMenuClick(activity: AppCompatActivity, + genre: Genre, + item: MenuItem): Boolean { + when (item.itemId) { + R.id.action_play -> { + MusicPlayerRemote.openQueue(getGenreSongs(activity, genre), 0, true) + return true + } + R.id.action_play_next -> { + MusicPlayerRemote.playNext(getGenreSongs(activity, genre)) + return true + } + R.id.action_add_to_playlist -> { + AddToPlaylistDialog.create(getGenreSongs(activity, genre)) + .show(activity.supportFragmentManager, "ADD_PLAYLIST") + return true + } + R.id.action_add_to_current_playing -> { + MusicPlayerRemote.enqueue(getGenreSongs(activity, genre)) + return true + } + } + return false + } + + private fun getGenreSongs(activity: Activity, + genre: Genre): ArrayList { + val songs: ArrayList + songs = GenreLoader.getSongs(activity, genre.id).blockingFirst() + return songs + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/PlaylistMenuHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/menu/PlaylistMenuHelper.java deleted file mode 100644 index 214ae79c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/menu/PlaylistMenuHelper.java +++ /dev/null @@ -1,91 +0,0 @@ -package code.name.monkey.retromusic.helper.menu; - -import android.app.Activity; -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import android.view.MenuItem; -import android.widget.Toast; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.RetroApplication; -import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog; -import code.name.monkey.retromusic.dialogs.DeletePlaylistDialog; -import code.name.monkey.retromusic.dialogs.RenamePlaylistDialog; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.loaders.PlaylistSongsLoader; -import code.name.monkey.retromusic.misc.WeakContextAsyncTask; -import code.name.monkey.retromusic.model.AbsCustomPlaylist; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.PlaylistsUtil; - - -public class PlaylistMenuHelper { - - public static boolean handleMenuClick(@NonNull AppCompatActivity activity, - @NonNull final Playlist playlist, @NonNull MenuItem item) { - switch (item.getItemId()) { - case R.id.action_play: - MusicPlayerRemote.openQueue(getPlaylistSongs(activity, playlist), 9, true); - return true; - case R.id.action_play_next: - MusicPlayerRemote.playNext(getPlaylistSongs(activity, playlist)); - return true; - case R.id.action_add_to_playlist: - AddToPlaylistDialog.create(getPlaylistSongs(activity, playlist)) - .show(activity.getSupportFragmentManager(), "ADD_PLAYLIST"); - return true; - case R.id.action_add_to_current_playing: - MusicPlayerRemote.enqueue(getPlaylistSongs(activity, playlist)); - return true; - case R.id.action_rename_playlist: - RenamePlaylistDialog.create(playlist.id) - .show(activity.getSupportFragmentManager(), "RENAME_PLAYLIST"); - return true; - case R.id.action_delete_playlist: - DeletePlaylistDialog.create(playlist) - .show(activity.getSupportFragmentManager(), "DELETE_PLAYLIST"); - return true; - case R.id.action_save_playlist: - new SavePlaylistAsyncTask(activity).execute(playlist); - return true; - } - return false; - } - - @NonNull - private static ArrayList getPlaylistSongs(@NonNull Activity activity, - @NonNull Playlist playlist) { - ArrayList songs; - if (playlist instanceof AbsCustomPlaylist) { - songs = ((AbsCustomPlaylist) playlist).getSongs(activity).blockingFirst(); - } else { - songs = PlaylistSongsLoader.getPlaylistSongList(activity, playlist).blockingFirst(); - } - return songs; - } - - private static class SavePlaylistAsyncTask extends WeakContextAsyncTask { - SavePlaylistAsyncTask(Context context) { - super(context); - } - - @Override - protected String doInBackground(Playlist... params) { - return String.format(RetroApplication.getInstance().getApplicationContext().getString(R.string - .saved_playlist_to), PlaylistsUtil.savePlaylist(RetroApplication.getInstance().getApplicationContext(), params[0]).blockingFirst()); - } - - @Override - protected void onPostExecute(String string) { - super.onPostExecute(string); - Context context = getContext(); - if (context != null) { - Toast.makeText(context, string, Toast.LENGTH_LONG).show(); - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/PlaylistMenuHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/menu/PlaylistMenuHelper.kt new file mode 100644 index 00000000..5289ad31 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/menu/PlaylistMenuHelper.kt @@ -0,0 +1,91 @@ +package code.name.monkey.retromusic.helper.menu + +import android.app.Activity +import android.content.Context +import androidx.appcompat.app.AppCompatActivity +import android.view.MenuItem +import android.widget.Toast + +import java.util.ArrayList + +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.RetroApplication +import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog +import code.name.monkey.retromusic.dialogs.DeletePlaylistDialog +import code.name.monkey.retromusic.dialogs.RenamePlaylistDialog +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.loaders.PlaylistSongsLoader +import code.name.monkey.retromusic.misc.WeakContextAsyncTask +import code.name.monkey.retromusic.model.AbsCustomPlaylist +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.PlaylistsUtil + + +object PlaylistMenuHelper { + + fun handleMenuClick(activity: AppCompatActivity, + playlist: Playlist, item: MenuItem): Boolean { + when (item.itemId) { + R.id.action_play -> { + MusicPlayerRemote.openQueue(getPlaylistSongs(activity, playlist), 9, true) + return true + } + R.id.action_play_next -> { + MusicPlayerRemote.playNext(getPlaylistSongs(activity, playlist)) + return true + } + R.id.action_add_to_playlist -> { + AddToPlaylistDialog.create(getPlaylistSongs(activity, playlist)) + .show(activity.supportFragmentManager, "ADD_PLAYLIST") + return true + } + R.id.action_add_to_current_playing -> { + MusicPlayerRemote.enqueue(getPlaylistSongs(activity, playlist)) + return true + } + R.id.action_rename_playlist -> { + RenamePlaylistDialog.create(playlist.id.toLong()) + .show(activity.supportFragmentManager, "RENAME_PLAYLIST") + return true + } + R.id.action_delete_playlist -> { + DeletePlaylistDialog.create(playlist) + .show(activity.supportFragmentManager, "DELETE_PLAYLIST") + return true + } + R.id.action_save_playlist -> { + SavePlaylistAsyncTask(activity).execute(playlist) + return true + } + } + return false + } + + private fun getPlaylistSongs(activity: Activity, + playlist: Playlist): ArrayList { + val songs: ArrayList + if (playlist is AbsCustomPlaylist) { + songs = playlist.getSongs(activity).blockingFirst() + } else { + songs = PlaylistSongsLoader.getPlaylistSongList(activity, playlist).blockingFirst() + } + return songs + } + + private class SavePlaylistAsyncTask internal constructor(context: Context) : WeakContextAsyncTask(context) { + + override fun doInBackground(vararg params: Playlist): String { + return String.format(RetroApplication.instance.applicationContext.getString(R.string + .saved_playlist_to), PlaylistsUtil.savePlaylist(RetroApplication.instance.applicationContext, params[0]).blockingFirst()) + } + + override fun onPostExecute(string: String) { + super.onPostExecute(string) + val context = context + if (context != null) { + Toast.makeText(context, string, Toast.LENGTH_LONG).show() + } + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongMenuHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongMenuHelper.java deleted file mode 100644 index 23265664..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongMenuHelper.java +++ /dev/null @@ -1,93 +0,0 @@ -package code.name.monkey.retromusic.helper.menu; - -import android.content.Intent; -import androidx.annotation.NonNull; -import androidx.fragment.app.FragmentActivity; -import androidx.appcompat.app.AppCompatActivity; -import android.view.MenuItem; -import android.view.View; -import android.widget.PopupMenu; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog; -import code.name.monkey.retromusic.dialogs.DeleteSongsDialog; -import code.name.monkey.retromusic.dialogs.SongDetailDialog; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.interfaces.PaletteColorHolder; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.activities.tageditor.AbsTagEditorActivity; -import code.name.monkey.retromusic.ui.activities.tageditor.SongTagEditorActivity; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; - - -public class SongMenuHelper { - public static final int MENU_RES = R.menu.menu_item_song; - - public static boolean handleMenuClick(@NonNull FragmentActivity activity, @NonNull Song song, int menuItemId) { - switch (menuItemId) { - case R.id.action_set_as_ringtone: - MusicUtil.setRingtone(activity, song.id); - return true; - case R.id.action_share: - activity.startActivity(Intent.createChooser(MusicUtil.createShareSongFileIntent(song, activity), null)); - return true; - case R.id.action_delete_from_device: - DeleteSongsDialog.create(song).show(activity.getSupportFragmentManager(), "DELETE_SONGS"); - return true; - case R.id.action_add_to_playlist: - AddToPlaylistDialog.create(song).show(activity.getSupportFragmentManager(), "ADD_PLAYLIST"); - return true; - case R.id.action_play_next: - MusicPlayerRemote.playNext(song); - return true; - case R.id.action_add_to_current_playing: - MusicPlayerRemote.enqueue(song); - return true; - case R.id.action_tag_editor: - Intent tagEditorIntent = new Intent(activity, SongTagEditorActivity.class); - tagEditorIntent.putExtra(AbsTagEditorActivity.EXTRA_ID, song.id); - if (activity instanceof PaletteColorHolder) - tagEditorIntent.putExtra(AbsTagEditorActivity.EXTRA_PALETTE, ((PaletteColorHolder) activity).getPaletteColor()); - activity.startActivity(tagEditorIntent); - return true; - case R.id.action_details: - SongDetailDialog.create(song).show(activity.getSupportFragmentManager(), "SONG_DETAILS"); - return true; - case R.id.action_go_to_album: - NavigationUtil.goToAlbum(activity, song.albumId); - return true; - case R.id.action_go_to_artist: - NavigationUtil.goToArtist(activity, song.artistId); - return true; - } - return false; - } - - public static abstract class OnClickSongMenu implements View.OnClickListener, PopupMenu.OnMenuItemClickListener { - private AppCompatActivity activity; - - protected OnClickSongMenu(@NonNull AppCompatActivity activity) { - this.activity = activity; - } - - public int getMenuRes() { - return MENU_RES; - } - - @Override - public void onClick(View v) { - PopupMenu popupMenu = new PopupMenu(activity, v); - popupMenu.inflate(getMenuRes()); - popupMenu.setOnMenuItemClickListener(this); - popupMenu.show(); - } - - @Override - public boolean onMenuItemClick(MenuItem item) { - return handleMenuClick(activity, getSong(), item.getItemId()); - } - - public abstract Song getSong(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongMenuHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongMenuHelper.kt new file mode 100644 index 00000000..ac6adc85 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongMenuHelper.kt @@ -0,0 +1,93 @@ +package code.name.monkey.retromusic.helper.menu + +import android.content.Intent +import android.view.MenuItem +import android.view.View +import android.widget.PopupMenu +import androidx.appcompat.app.AppCompatActivity +import androidx.fragment.app.FragmentActivity +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog +import code.name.monkey.retromusic.dialogs.DeleteSongsDialog +import code.name.monkey.retromusic.dialogs.SongDetailDialog +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.interfaces.PaletteColorHolder +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.activities.tageditor.AbsTagEditorActivity +import code.name.monkey.retromusic.ui.activities.tageditor.SongTagEditorActivity +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil + + +object SongMenuHelper { + val MENU_RES = R.menu.menu_item_song + + fun handleMenuClick(activity: FragmentActivity, song: Song, menuItemId: Int): Boolean { + when (menuItemId) { + R.id.action_set_as_ringtone -> { + MusicUtil.setRingtone(activity, song.id) + return true + } + R.id.action_share -> { + activity.startActivity(Intent.createChooser(MusicUtil.createShareSongFileIntent(song, activity), null)) + return true + } + R.id.action_delete_from_device -> { + DeleteSongsDialog.create(song).show(activity.supportFragmentManager, "DELETE_SONGS") + return true + } + R.id.action_add_to_playlist -> { + AddToPlaylistDialog.create(song).show(activity.supportFragmentManager, "ADD_PLAYLIST") + return true + } + R.id.action_play_next -> { + MusicPlayerRemote.playNext(song) + return true + } + R.id.action_add_to_current_playing -> { + MusicPlayerRemote.enqueue(song) + return true + } + R.id.action_tag_editor -> { + val tagEditorIntent = Intent(activity, SongTagEditorActivity::class.java) + tagEditorIntent.putExtra(AbsTagEditorActivity.EXTRA_ID, song.id) + if (activity is PaletteColorHolder) + tagEditorIntent.putExtra(AbsTagEditorActivity.EXTRA_PALETTE, (activity as PaletteColorHolder).paletteColor) + activity.startActivity(tagEditorIntent) + return true + } + R.id.action_details -> { + SongDetailDialog.create(song).show(activity.supportFragmentManager, "SONG_DETAILS") + return true + } + R.id.action_go_to_album -> { + NavigationUtil.goToAlbum(activity, song.albumId) + return true + } + R.id.action_go_to_artist -> { + NavigationUtil.goToArtist(activity, song.artistId) + return true + } + } + return false + } + + abstract class OnClickSongMenu protected constructor(private val activity: AppCompatActivity) : View.OnClickListener, PopupMenu.OnMenuItemClickListener { + + open val menuRes: Int + get() = MENU_RES + + abstract val song: Song + + override fun onClick(v: View) { + val popupMenu = PopupMenu(activity, v) + popupMenu.inflate(menuRes) + popupMenu.setOnMenuItemClickListener(this) + popupMenu.show() + } + + override fun onMenuItemClick(item: MenuItem): Boolean { + return handleMenuClick(activity, song, item.itemId) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongsMenuHelper.java b/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongsMenuHelper.java deleted file mode 100644 index e341e976..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongsMenuHelper.java +++ /dev/null @@ -1,35 +0,0 @@ -package code.name.monkey.retromusic.helper.menu; - -import androidx.annotation.NonNull; -import androidx.fragment.app.FragmentActivity; - -import code.name.monkey.retromusic.model.Song; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog; -import code.name.monkey.retromusic.dialogs.DeleteSongsDialog; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; - - - -public class SongsMenuHelper { - public static boolean handleMenuClick(@NonNull FragmentActivity activity, @NonNull ArrayList songs, int menuItemId) { - switch (menuItemId) { - case R.id.action_play_next: - MusicPlayerRemote.playNext(songs); - return true; - case R.id.action_add_to_current_playing: - MusicPlayerRemote.enqueue(songs); - return true; - case R.id.action_add_to_playlist: - AddToPlaylistDialog.create(songs).show(activity.getSupportFragmentManager(), "ADD_PLAYLIST"); - return true; - case R.id.action_delete_from_device: - DeleteSongsDialog.create(songs).show(activity.getSupportFragmentManager(), "DELETE_SONGS"); - return true; - } - return false; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongsMenuHelper.kt b/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongsMenuHelper.kt new file mode 100644 index 00000000..b246864a --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/helper/menu/SongsMenuHelper.kt @@ -0,0 +1,34 @@ +package code.name.monkey.retromusic.helper.menu + +import androidx.fragment.app.FragmentActivity +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog +import code.name.monkey.retromusic.dialogs.DeleteSongsDialog +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.model.Song +import java.util.* + + +object SongsMenuHelper { + fun handleMenuClick(activity: FragmentActivity, songs: ArrayList, menuItemId: Int): Boolean { + when (menuItemId) { + R.id.action_play_next -> { + MusicPlayerRemote.playNext(songs) + return true + } + R.id.action_add_to_current_playing -> { + MusicPlayerRemote.enqueue(songs) + return true + } + R.id.action_add_to_playlist -> { + AddToPlaylistDialog.create(songs).show(activity.supportFragmentManager, "ADD_PLAYLIST") + return true + } + R.id.action_delete_from_device -> { + DeleteSongsDialog.create(songs).show(activity.supportFragmentManager, "DELETE_SONGS") + return true + } + } + return false + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/CabHolder.java b/app/src/main/java/code/name/monkey/retromusic/interfaces/CabHolder.java deleted file mode 100644 index e55195de..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/interfaces/CabHolder.java +++ /dev/null @@ -1,12 +0,0 @@ -package code.name.monkey.retromusic.interfaces; - -import androidx.annotation.NonNull; - -import com.afollestad.materialcab.MaterialCab; - - -public interface CabHolder { - - @NonNull - MaterialCab openCab(final int menuRes, final MaterialCab.Callback callback); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/CabHolder.kt b/app/src/main/java/code/name/monkey/retromusic/interfaces/CabHolder.kt new file mode 100644 index 00000000..88378195 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/interfaces/CabHolder.kt @@ -0,0 +1,9 @@ +package code.name.monkey.retromusic.interfaces + +import com.afollestad.materialcab.MaterialCab + + +interface CabHolder { + + fun openCab(menuRes: Int, callback: MaterialCab.Callback): MaterialCab +} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/EqualizerInterface.java b/app/src/main/java/code/name/monkey/retromusic/interfaces/EqualizerInterface.java deleted file mode 100644 index 88143418..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/interfaces/EqualizerInterface.java +++ /dev/null @@ -1,49 +0,0 @@ -package code.name.monkey.retromusic.interfaces; - -import android.media.audiofx.BassBoost; -import android.media.audiofx.Equalizer; -import android.media.audiofx.Virtualizer; - -/** - * @author Hemanth S (h4h13). - */ - -public interface EqualizerInterface { - int getBandLevelLow(); - - int getBandLevelHigh(); - - int getNumberOfBands(); - - int getCenterFreq(int band); - - int getBandLevel(int band); - - void setBandLevel(int band, int level); - - boolean isBassBoostEnabled(); - - void setBassBoostEnabled(boolean isEnabled); - - int getBassBoostStrength(); - - void setBassBoostStrength(int strength); - - boolean isVirtualizerEnabled(); - - void setVirtualizerEnabled(boolean isEnabled); - - int getVirtualizerStrength(); - - void setVirtualizerStrength(int strength); - - boolean isRunning(); - - Equalizer getEqualizer(); - - BassBoost getBassBoost(); - - Virtualizer getVirtualizer(); - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/EqualizerInterface.kt b/app/src/main/java/code/name/monkey/retromusic/interfaces/EqualizerInterface.kt new file mode 100644 index 00000000..5b3570b8 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/interfaces/EqualizerInterface.kt @@ -0,0 +1,41 @@ +package code.name.monkey.retromusic.interfaces + +import android.media.audiofx.BassBoost +import android.media.audiofx.Equalizer +import android.media.audiofx.Virtualizer + +/** + * @author Hemanth S (h4h13). + */ + +interface EqualizerInterface { + val bandLevelLow: Int + + val bandLevelHigh: Int + + val numberOfBands: Int + + var isBassBoostEnabled: Boolean + + var bassBoostStrength: Int + + var isVirtualizerEnabled: Boolean + + var virtualizerStrength: Int + + val isRunning: Boolean + + val equalizer: Equalizer + + val bassBoost: BassBoost + + val virtualizer: Virtualizer + + fun getCenterFreq(band: Int): Int + + fun getBandLevel(band: Int): Int + + fun setBandLevel(band: Int, level: Int) + + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.java b/app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.java deleted file mode 100644 index e7792818..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.java +++ /dev/null @@ -1,6 +0,0 @@ -package code.name.monkey.retromusic.interfaces; - - -public interface LoaderIds { - int FOLDERS_FRAGMENT = 5; -} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.kt b/app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.kt new file mode 100644 index 00000000..90f23871 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/interfaces/LoaderIds.kt @@ -0,0 +1,8 @@ +package code.name.monkey.retromusic.interfaces + + +interface LoaderIds { + companion object { + val FOLDERS_FRAGMENT = 5 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/MainActivityFragmentCallbacks.java b/app/src/main/java/code/name/monkey/retromusic/interfaces/MainActivityFragmentCallbacks.java deleted file mode 100644 index 81dbbccb..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/interfaces/MainActivityFragmentCallbacks.java +++ /dev/null @@ -1,11 +0,0 @@ -package code.name.monkey.retromusic.interfaces; - -/** - * Created by hemanths on 14/08/17. - */ - -public interface MainActivityFragmentCallbacks { - boolean handleBackPress(); - - //void selectedFragment(Fragment fragment); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/MainActivityFragmentCallbacks.kt b/app/src/main/java/code/name/monkey/retromusic/interfaces/MainActivityFragmentCallbacks.kt new file mode 100644 index 00000000..537e80b0 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/interfaces/MainActivityFragmentCallbacks.kt @@ -0,0 +1,11 @@ +package code.name.monkey.retromusic.interfaces + +/** + * Created by hemanths on 14/08/17. + */ + +interface MainActivityFragmentCallbacks { + fun handleBackPress(): Boolean + + //void selectedFragment(Fragment fragment); +} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/MusicServiceEventListener.java b/app/src/main/java/code/name/monkey/retromusic/interfaces/MusicServiceEventListener.java deleted file mode 100644 index ea609019..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/interfaces/MusicServiceEventListener.java +++ /dev/null @@ -1,20 +0,0 @@ -package code.name.monkey.retromusic.interfaces; - - -public interface MusicServiceEventListener { - void onServiceConnected(); - - void onServiceDisconnected(); - - void onQueueChanged(); - - void onPlayingMetaChanged(); - - void onPlayStateChanged(); - - void onRepeatModeChanged(); - - void onShuffleModeChanged(); - - void onMediaStoreChanged(); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/MusicServiceEventListener.kt b/app/src/main/java/code/name/monkey/retromusic/interfaces/MusicServiceEventListener.kt new file mode 100644 index 00000000..66a1a016 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/interfaces/MusicServiceEventListener.kt @@ -0,0 +1,20 @@ +package code.name.monkey.retromusic.interfaces + + +interface MusicServiceEventListener { + fun onServiceConnected() + + fun onServiceDisconnected() + + fun onQueueChanged() + + fun onPlayingMetaChanged() + + fun onPlayStateChanged() + + fun onRepeatModeChanged() + + fun onShuffleModeChanged() + + fun onMediaStoreChanged() +} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/PaletteColorHolder.java b/app/src/main/java/code/name/monkey/retromusic/interfaces/PaletteColorHolder.java deleted file mode 100644 index f20757c0..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/interfaces/PaletteColorHolder.java +++ /dev/null @@ -1,12 +0,0 @@ -package code.name.monkey.retromusic.interfaces; - -import androidx.annotation.ColorInt; - -/** - * @author Aidan Follestad (afollestad) - */ -public interface PaletteColorHolder { - - @ColorInt - int getPaletteColor(); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/interfaces/PaletteColorHolder.kt b/app/src/main/java/code/name/monkey/retromusic/interfaces/PaletteColorHolder.kt new file mode 100644 index 00000000..70d3778d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/interfaces/PaletteColorHolder.kt @@ -0,0 +1,12 @@ +package code.name.monkey.retromusic.interfaces + +import androidx.annotation.ColorInt + +/** + * @author Aidan Follestad (afollestad) + */ +interface PaletteColorHolder { + + @get:ColorInt + val paletteColor: Int +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/AlbumLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/AlbumLoader.java deleted file mode 100644 index 0edf4ebc..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/AlbumLoader.java +++ /dev/null @@ -1,104 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.provider.MediaStore.Audio.AudioColumns; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.Observable; -import java.util.ArrayList; - -/** - * Created by hemanths on 11/08/17. - */ - -public class AlbumLoader { - - public static Observable> getAllAlbums(@NonNull Context context) { - Observable> songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor( - context, - null, - null, - getSongLoaderSortOrder(context)) - ); - - return splitIntoAlbums(songs); - } - - @NonNull - public static Observable> getAlbums(@NonNull final Context context, - String query) { - Observable> songs = SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor( - context, - AudioColumns.ALBUM + " LIKE ?", - new String[]{"%" + query + "%"}, - getSongLoaderSortOrder(context)) - ); - return splitIntoAlbums(songs); - } - - @NonNull - public static Observable getAlbum(@NonNull final Context context, int albumId) { - return Observable.create(e -> { - Observable> songs = SongLoader.Companion.getSongs(SongLoader.Companion - .makeSongCursor(context, AudioColumns.ALBUM_ID + "=?", - new String[]{String.valueOf(albumId)}, getSongLoaderSortOrder(context))); - songs.subscribe(songs1 -> { - e.onNext(new Album(songs1)); - e.onComplete(); - }); - }); - } - - @NonNull - public static Observable> splitIntoAlbums( - @Nullable final Observable> songs) { - return Observable.create(e -> { - ArrayList albums = new ArrayList<>(); - if (songs != null) { - songs.subscribe(songs1 -> { - for (Song song : songs1) { - getOrCreateAlbum(albums, song.albumId).subscribe(album -> album.songs.add(song)); - } - }); - } - e.onNext(albums); - e.onComplete(); - }); - } - - @NonNull - public static ArrayList splitIntoAlbums(@Nullable final ArrayList songs) { - ArrayList albums = new ArrayList<>(); - if (songs != null) { - for (Song song : songs) { - getOrCreateAlbum(albums, song.albumId).subscribe(album -> album.songs.add(song)); - } - } - return albums; - } - - private static Observable getOrCreateAlbum(ArrayList albums, int albumId) { - return Observable.create(e -> { - for (Album album : albums) { - if (!album.songs.isEmpty() && album.songs.get(0).albumId == albumId) { - e.onNext(album); - e.onComplete(); - return; - } - } - Album album = new Album(); - albums.add(album); - e.onNext(album); - e.onComplete(); - }); - } - - public static String getSongLoaderSortOrder(Context context) { - return PreferenceUtil.getInstance().getAlbumSortOrder() + ", " + - //PreferenceUtil.getInstance().getAlbumSongSortOrder() + "," + - PreferenceUtil.getInstance().getAlbumDetailSongSortOrder(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/AlbumLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/AlbumLoader.kt new file mode 100644 index 00000000..b0dc7da4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/AlbumLoader.kt @@ -0,0 +1,95 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.provider.MediaStore.Audio.AudioColumns +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.PreferenceUtil +import io.reactivex.Observable +import java.util.* + +/** + * Created by hemanths on 11/08/17. + */ + +open class AlbumLoader { + companion object { + fun getAllAlbums(context: Context): Observable> { + val songs = SongLoader.getSongs(SongLoader.makeSongCursor( + context, null, null, + getSongLoaderSortOrder()) + ) + + return splitIntoAlbums(songs) + } + + fun getAlbums(context: Context, + query: String): Observable> { + val songs = SongLoader.getSongs(SongLoader.makeSongCursor( + context, + AudioColumns.ALBUM + " LIKE ?", + arrayOf("%$query%"), + getSongLoaderSortOrder()) + ) + return splitIntoAlbums(songs) + } + + fun getAlbum(context: Context, albumId: Int): Observable { + return Observable.create { e -> + val songs = SongLoader.getSongs(SongLoader + .makeSongCursor(context, AudioColumns.ALBUM_ID + "=?", + arrayOf(albumId.toString()), getSongLoaderSortOrder())) + songs.subscribe { songs1 -> + e.onNext(Album(songs1)) + e.onComplete() + } + } + } + + fun splitIntoAlbums( + songs: Observable>?): Observable> { + return Observable.create { e -> + val albums = ArrayList() + songs?.subscribe { songs1 -> + for (song in songs1) { + getOrCreateAlbum(albums, song.albumId).subscribe { album -> album.songs!!.add(song) } + } + } + e.onNext(albums) + e.onComplete() + } + } + + fun splitIntoAlbums(songs: ArrayList?): ArrayList { + val albums = ArrayList() + if (songs != null) { + for (song in songs) { + getOrCreateAlbum(albums, song.albumId).subscribe { album -> album.songs!!.add(song) } + } + } + return albums + } + + private fun getOrCreateAlbum(albums: ArrayList, albumId: Int): Observable { + return Observable.create { e -> + for (album in albums) { + if (!album.songs!!.isEmpty() && album.songs[0].albumId == albumId) { + e.onNext(album) + e.onComplete() + return@create + } + } + val album = Album() + albums.add(album) + e.onNext(album) + e.onComplete() + } + } + + fun getSongLoaderSortOrder(): String { + return PreferenceUtil.getInstance().albumSortOrder + ", " + + //PreferenceUtil.getInstance().getAlbumSongSortOrder() + "," + + PreferenceUtil.getInstance().albumDetailSongSortOrder + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistLoader.java deleted file mode 100644 index 88e8fa57..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistLoader.java +++ /dev/null @@ -1,101 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.provider.MediaStore.Audio.AudioColumns; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.Observable; - -public class ArtistLoader { - private static String getSongLoaderSortOrder(Context context) { - return PreferenceUtil.getInstance().getArtistSortOrder() + ", " + - PreferenceUtil.getInstance().getArtistAlbumSortOrder() + ", " + - PreferenceUtil.getInstance().getAlbumDetailSongSortOrder() + ", " + - PreferenceUtil.getInstance().getArtistDetailSongSortOrder(); - } - - @NonNull - public static Observable getArtist(@NonNull final Context context, int artistId) { - return Observable.create(e -> SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor( - context, - AudioColumns.ARTIST_ID + "=?", - new String[]{String.valueOf(artistId)}, - getSongLoaderSortOrder(context))) - .subscribe(songs -> { - Artist artist = new Artist(AlbumLoader.splitIntoAlbums(songs)); - e.onNext(artist); - e.onComplete(); - })); - } - - @NonNull - public static Observable> getAllArtists(@NonNull final Context context) { - return Observable.create(e -> SongLoader.Companion - .getSongs(SongLoader.Companion.makeSongCursor( - context, - null, - null, - getSongLoaderSortOrder(context)) - ).subscribe(songs -> { - e.onNext(splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))); - e.onComplete(); - })); - - } - - @NonNull - public static Observable> getArtists(@NonNull final Context context, String query) { - return Observable.create(e -> SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor( - context, - AudioColumns.ARTIST + " LIKE ?", - new String[]{"%" + query + "%"}, - getSongLoaderSortOrder(context)) - ).subscribe(songs -> { - e.onNext(splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))); - e.onComplete(); - })); - } - - @NonNull - public static ArrayList splitIntoArtists(@Nullable final ArrayList albums) { - ArrayList artists = new ArrayList<>(); - if (albums != null) { - for (Album album : albums) { - getOrCreateArtist(artists, album.getArtistId()).albums.add(album); - } - } - return artists; - } - - private static Artist getOrCreateArtist(ArrayList artists, int artistId) { - for (Artist artist : artists) { - if (!artist.albums.isEmpty() && !artist.albums.get(0).songs.isEmpty() && artist.albums.get(0).songs.get(0).artistId == artistId) { - return artist; - } - } - Artist album = new Artist(); - artists.add(album); - return album; - } - - public static Observable> splitIntoArtists(Observable> albums) { - return Observable.create(e -> { - ArrayList artists = new ArrayList<>(); - albums.subscribe(localAlbums -> { - if (localAlbums != null) { - for (Album album : localAlbums) { - getOrCreateArtist(artists, album.getArtistId()).albums.add(album); - } - } - e.onNext(artists); - e.onComplete(); - }); - }); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistLoader.kt new file mode 100644 index 00000000..96f778fe --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistLoader.kt @@ -0,0 +1,99 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.provider.MediaStore.Audio.AudioColumns + +import java.util.ArrayList + +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.util.PreferenceUtil +import io.reactivex.Observable + +object ArtistLoader { + private fun getSongLoaderSortOrder(): String { + return PreferenceUtil.getInstance().artistSortOrder + ", " + + PreferenceUtil.getInstance().artistAlbumSortOrder + ", " + + PreferenceUtil.getInstance().albumDetailSongSortOrder + ", " + + PreferenceUtil.getInstance().artistDetailSongSortOrder + } + + fun getArtist(context: Context, artistId: Int): Observable { + return Observable.create { e -> + SongLoader.getSongs(SongLoader.makeSongCursor( + context, + AudioColumns.ARTIST_ID + "=?", + arrayOf(artistId.toString()), + getSongLoaderSortOrder())) + .subscribe { songs -> + val artist = Artist(AlbumLoader.splitIntoAlbums(songs)) + e.onNext(artist) + e.onComplete() + } + } + } + + fun getAllArtists(context: Context): Observable> { + return Observable.create { e -> + SongLoader + .getSongs(SongLoader.makeSongCursor( + context, null, null, + getSongLoaderSortOrder()) + ).subscribe { songs -> + e.onNext(splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))) + e.onComplete() + } + } + + } + + fun getArtists(context: Context, query: String): Observable> { + return Observable.create { e -> + SongLoader.getSongs(SongLoader.makeSongCursor( + context, + AudioColumns.ARTIST + " LIKE ?", + arrayOf("%$query%"), + getSongLoaderSortOrder()) + ).subscribe { songs -> + e.onNext(splitIntoArtists(AlbumLoader.splitIntoAlbums(songs))) + e.onComplete() + } + } + } + + fun splitIntoArtists(albums: ArrayList?): ArrayList { + val artists = ArrayList() + if (albums != null) { + for (album in albums) { + getOrCreateArtist(artists, album.artistId).albums!!.add(album) + } + } + return artists + } + + private fun getOrCreateArtist(artists: ArrayList, artistId: Int): Artist { + for (artist in artists) { + if (!artist.albums!!.isEmpty() && !artist.albums[0].songs!!.isEmpty() && artist.albums[0].songs!![0].artistId == artistId) { + return artist + } + } + val album = Artist() + artists.add(album) + return album + } + + fun splitIntoArtists(albums: Observable>): Observable> { + return Observable.create { e -> + val artists = ArrayList() + albums.subscribe { localAlbums -> + if (localAlbums != null) { + for (album in localAlbums) { + getOrCreateArtist(artists, album.artistId).albums!!.add(album) + } + } + e.onNext(artists) + e.onComplete() + } + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistSongLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistSongLoader.java deleted file mode 100644 index 99be9459..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/ArtistSongLoader.java +++ /dev/null @@ -1,37 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.provider.MediaStore; -import androidx.annotation.NonNull; - -import code.name.monkey.retromusic.model.Song; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.Observable; - - -public class ArtistSongLoader extends SongLoader { - - @NonNull - public static Observable> getArtistSongList(@NonNull final Context context, final int artistId) { - return Companion.getSongs(makeArtistSongCursor(context, artistId)); - } - - public static Cursor makeArtistSongCursor(@NonNull final Context context, final int artistId) { - try { - return Companion.makeSongCursor( - context, - MediaStore.Audio.AudioColumns.ARTIST_ID + "=?", - new String[]{ - String.valueOf(artistId) - }, - PreferenceUtil.getInstance().getArtistSongSortOrder() - ); - } catch (SecurityException e) { - return null; - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/GenreLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/GenreLoader.java deleted file mode 100644 index 34f9b059..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/GenreLoader.java +++ /dev/null @@ -1,133 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.provider.BaseColumns; -import android.provider.MediaStore.Audio.Genres; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.Observable; - -public class GenreLoader { - - @NonNull - public static Observable> getAllGenres(@NonNull final Context context) { - return getGenresFromCursor(context, makeGenreCursor(context)); - } - - @NonNull - public static Observable> getSongs(@NonNull final Context context, final int genreId) { - // The genres table only stores songs that have a genre specified, - // so we need to get songs without a genre a different way. - if (genreId == -1) { - return getSongsWithNoGenre(context); - } - - return SongLoader.Companion.getSongs(makeGenreSongCursor(context, genreId)); - } - - @NonNull - private static Genre getGenreFromCursor(@NonNull Context context, @NonNull final Cursor cursor) { - final int id = cursor.getInt(0); - final String name = cursor.getString(1); - final int songCount = getSongs(context, id).blockingFirst().size(); - return new Genre(id, name, songCount); - - } - - @NonNull - private static Observable> getSongsWithNoGenre(@NonNull final Context context) { - String selection = BaseColumns._ID + " NOT IN " + - "(SELECT " + Genres.Members.AUDIO_ID + " FROM audio_genres_map)"; - return SongLoader.Companion.getSongs(SongLoader.Companion.makeSongCursor(context, selection, null)); - } - - private static boolean hasSongsWithNoGenre(@NonNull final Context context) { - final Cursor allSongsCursor = SongLoader.Companion.makeSongCursor(context, null, null); - final Cursor allSongsWithGenreCursor = makeAllSongsWithGenreCursor(context); - - if (allSongsCursor == null || allSongsWithGenreCursor == null) { - return false; - } - - final boolean hasSongsWithNoGenre = allSongsCursor.getCount() > allSongsWithGenreCursor.getCount(); - allSongsCursor.close(); - allSongsWithGenreCursor.close(); - return hasSongsWithNoGenre; - } - - @Nullable - private static Cursor makeAllSongsWithGenreCursor(@NonNull final Context context) { - try { - return context.getContentResolver().query( - Uri.parse("content://media/external/audio/genres/all/members"), - new String[]{Genres.Members.AUDIO_ID}, null, null, null); - } catch (SecurityException e) { - return null; - } - } - - @Nullable - private static Cursor makeGenreSongCursor(@NonNull final Context context, int genreId) { - try { - return context.getContentResolver().query( - Genres.Members.getContentUri("external", genreId), - SongLoader.Companion.getBASE_PROJECTION(), SongLoader.BASE_SELECTION, null, PreferenceUtil.getInstance().getSongSortOrder()); - } catch (SecurityException e) { - return null; - } - } - - @NonNull - private static Observable> getGenresFromCursor(@NonNull final Context context, @Nullable final Cursor cursor) { - return Observable.create(e -> { - final ArrayList genres = new ArrayList<>(); - if (cursor != null) { - if (cursor.moveToFirst()) { - do { - Genre genre = getGenreFromCursor(context, cursor); - if (genre.songCount > 0) { - genres.add(genre); - } else { - // try to remove the empty genre from the media store - try { - context.getContentResolver().delete(Genres.EXTERNAL_CONTENT_URI, Genres._ID + " == " + genre.id, null); - } catch (Exception ex) { - ex.printStackTrace(); - // nothing we can do then - } - } - } while (cursor.moveToNext()); - } - cursor.close(); - } - e.onNext(genres); - e.onComplete(); - }); - } - - - @Nullable - private static Cursor makeGenreCursor(@NonNull final Context context) { - final String[] projection = new String[]{ - Genres._ID, - Genres.NAME - }; - - try { - return context.getContentResolver().query( - Genres.EXTERNAL_CONTENT_URI, - projection, null, null, PreferenceUtil.getInstance().getGenreSortOrder()); - } catch (SecurityException e) { - return null; - } - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/GenreLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/GenreLoader.kt new file mode 100644 index 00000000..96a9ad51 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/GenreLoader.kt @@ -0,0 +1,123 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.provider.BaseColumns +import android.provider.MediaStore.Audio.Genres +import code.name.monkey.retromusic.Constants.BASE_PROJECTION +import code.name.monkey.retromusic.Constants.BASE_SELECTION +import code.name.monkey.retromusic.model.Genre +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.PreferenceUtil +import io.reactivex.Observable +import java.util.* + +object GenreLoader { + + fun getAllGenres(context: Context): Observable> { + return getGenresFromCursor(context, makeGenreCursor(context)) + } + + fun getSongs(context: Context, genreId: Int): Observable> { + // The genres table only stores songs that have a genre specified, + // so we need to get songs without a genre a different way. + return if (genreId == -1) { + getSongsWithNoGenre(context) + } else SongLoader.getSongs(makeGenreSongCursor(context, genreId)) + + } + + private fun getGenreFromCursor(context: Context, cursor: Cursor): Genre { + val id = cursor.getInt(0) + val name = cursor.getString(1) + val songCount = getSongs(context, id).blockingFirst().size + return Genre(id, name, songCount) + + } + + private fun getSongsWithNoGenre(context: Context): Observable> { + val selection = BaseColumns._ID + " NOT IN " + + "(SELECT " + Genres.Members.AUDIO_ID + " FROM audio_genres_map)" + return SongLoader.getSongs(SongLoader.makeSongCursor(context, selection, null)) + } + + private fun hasSongsWithNoGenre(context: Context): Boolean { + val allSongsCursor = SongLoader.makeSongCursor(context, null, null) + val allSongsWithGenreCursor = makeAllSongsWithGenreCursor(context) + + if (allSongsCursor == null || allSongsWithGenreCursor == null) { + return false + } + + val hasSongsWithNoGenre = allSongsCursor.count > allSongsWithGenreCursor.count + allSongsCursor.close() + allSongsWithGenreCursor.close() + return hasSongsWithNoGenre + } + + private fun makeAllSongsWithGenreCursor(context: Context): Cursor? { + try { + return context.contentResolver.query( + Uri.parse("content://media/external/audio/genres/all/members"), + arrayOf(Genres.Members.AUDIO_ID), null, null, null) + } catch (e: SecurityException) { + return null + } + + } + + private fun makeGenreSongCursor(context: Context, genreId: Int): Cursor? { + try { + return context.contentResolver.query( + Genres.Members.getContentUri("external", genreId.toLong()), + BASE_PROJECTION, BASE_SELECTION, null, PreferenceUtil.getInstance().songSortOrder) + } catch (e: SecurityException) { + return null + } + + } + + private fun getGenresFromCursor(context: Context, cursor: Cursor?): Observable> { + return Observable.create { e -> + val genres = ArrayList() + if (cursor != null) { + if (cursor.moveToFirst()) { + do { + val genre = getGenreFromCursor(context, cursor) + if (genre.songCount > 0) { + genres.add(genre) + } else { + // try to remove the empty genre from the media store + try { + context.contentResolver.delete(Genres.EXTERNAL_CONTENT_URI, Genres._ID + " == " + genre.id, null) + } catch (ex: Exception) { + ex.printStackTrace() + // nothing we can do then + } + + } + } while (cursor.moveToNext()) + } + cursor.close() + } + e.onNext(genres) + e.onComplete() + } + } + + + private fun makeGenreCursor(context: Context): Cursor? { + val projection = arrayOf(Genres._ID, Genres.NAME) + + try { + return context.contentResolver.query( + Genres.EXTERNAL_CONTENT_URI, + projection, null, null, PreferenceUtil.getInstance().genreSortOrder) + } catch (e: SecurityException) { + return null + } + + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/GenreSongsLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/GenreSongsLoader.java deleted file mode 100644 index bf53c13f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/GenreSongsLoader.java +++ /dev/null @@ -1,76 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.provider.MediaStore; -import android.provider.MediaStore.Audio.AudioColumns; - -import java.util.ArrayList; -import java.util.List; - -import androidx.annotation.NonNull; -import code.name.monkey.retromusic.model.Song; -import io.reactivex.Observable; - -/** - * @author Hemanth S (h4h13). - */ - -public class GenreSongsLoader { - - public static Observable> getGenreSongsList(@NonNull Context context, int genreId) { - return Observable.create(e -> { - ArrayList list = new ArrayList<>(); - Cursor cursor = makeGenreSongCursor(context, genreId); - if (cursor != null && cursor.moveToFirst()) { - do { - list.add(getGenreSongFromCursorImpl(cursor)); - } while (cursor.moveToNext()); - } - if (cursor != null) { - cursor.close(); - } - e.onNext((ArrayList) (List) list); - e.onComplete(); - }); - } - - @NonNull - private static Song getGenreSongFromCursorImpl(@NonNull Cursor cursor) { - final int id = cursor.getInt(0); - final String title = cursor.getString(1); - final int trackNumber = cursor.getInt(2); - final int year = cursor.getInt(3); - final long duration = cursor.getLong(4); - final String data = cursor.getString(5); - final int dateModified = cursor.getInt(6); - final int albumId = cursor.getInt(7); - final String albumName = cursor.getString(8); - final int artistId = cursor.getInt(9); - final String artistName = cursor.getString(10); - return new Song(id, title, trackNumber, year, duration, data, dateModified, albumId, albumName, artistId, artistName); - } - - private static Cursor makeGenreSongCursor(Context context, long genreId) { - try { - return context.getContentResolver().query( - MediaStore.Audio.Genres.Members.getContentUri("external", genreId), - new String[]{ - MediaStore.Audio.Playlists.Members.AUDIO_ID,// 0 - AudioColumns.TITLE,// 1 - AudioColumns.TRACK,// 2 - AudioColumns.YEAR,// 3 - AudioColumns.DURATION,// 4 - AudioColumns.DATA,// 5 - AudioColumns.DATE_MODIFIED,// 6 - AudioColumns.ALBUM_ID,// 7 - AudioColumns.ALBUM,// 8 - AudioColumns.ARTIST_ID,// 9 - AudioColumns.ARTIST,// 10 - }, SongLoader.BASE_SELECTION, null, - MediaStore.Audio.Genres.Members.DEFAULT_SORT_ORDER); - } catch (SecurityException e) { - return null; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/HomeLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/HomeLoader.java deleted file mode 100644 index cc181e79..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/HomeLoader.java +++ /dev/null @@ -1,63 +0,0 @@ -package code.name.monkey.retromusic.loaders; - - -import android.content.Context; -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.smartplaylist.AbsSmartPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.HistoryPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.MyTopTracksPlaylist; -import io.reactivex.Observable; - -public class HomeLoader { - - public static Observable> getRecentAndTopThings( - @NonNull Context context) { - ArrayList objects = new ArrayList<>(); - return Observable.create(e -> { - - new HistoryPlaylist(context).getSongs(context).subscribe(songs -> { - if (!songs.isEmpty()) { - objects.add(new HistoryPlaylist(context)); - } - }); - new LastAddedPlaylist(context).getSongs(context).subscribe(songs -> { - if (!songs.isEmpty()) { - objects.add(new LastAddedPlaylist(context)); - } - }); - new MyTopTracksPlaylist(context).getSongs(context).subscribe(songs -> { - if (!songs.isEmpty()) { - objects.add(new MyTopTracksPlaylist(context)); - } - }); - - e.onNext(objects); - e.onComplete(); - }); - } - - public static Observable> getHomeLoader(@NonNull Context context) { - ArrayList playlists = new ArrayList<>(); - PlaylistLoader.getAllPlaylists(context) - .subscribe(playlists1 -> { - if (playlists1.size() > 0) { - for (Playlist playlist : playlists1) { - PlaylistSongsLoader.getPlaylistSongList(context, playlist) - .subscribe(songs -> { - if (songs.size() > 0) { - playlists.add(playlist); - } - }); - } - } - }); - return Observable.just(playlists); - } - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/HomeLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/HomeLoader.kt new file mode 100644 index 00000000..273d1a81 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/HomeLoader.kt @@ -0,0 +1,61 @@ +package code.name.monkey.retromusic.loaders + + +import android.content.Context + +import java.util.ArrayList +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.smartplaylist.AbsSmartPlaylist +import code.name.monkey.retromusic.model.smartplaylist.HistoryPlaylist +import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist +import code.name.monkey.retromusic.model.smartplaylist.MyTopTracksPlaylist +import io.reactivex.Observable + +object HomeLoader { + + fun getRecentAndTopThings( + context: Context): Observable> { + val objects = ArrayList() + return Observable.create { e -> + + HistoryPlaylist(context).getSongs(context).subscribe { songs -> + if (!songs.isEmpty()) { + objects.add(HistoryPlaylist(context)) + } + } + LastAddedPlaylist(context).getSongs(context).subscribe { songs -> + if (!songs.isEmpty()) { + objects.add(LastAddedPlaylist(context)) + } + } + MyTopTracksPlaylist(context).getSongs(context).subscribe { songs -> + if (!songs.isEmpty()) { + objects.add(MyTopTracksPlaylist(context)) + } + } + + e.onNext(objects) + e.onComplete() + } + } + + fun getHomeLoader(context: Context): Observable> { + val playlists = ArrayList() + PlaylistLoader.getAllPlaylists(context) + .subscribe { playlists1 -> + if (playlists1.size > 0) { + for (playlist in playlists1) { + PlaylistSongsLoader.getPlaylistSongList(context, playlist) + .subscribe { songs -> + if (songs.size > 0) { + playlists.add(playlist) + } + } + } + } + } + return Observable.just(playlists) + } + + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/LastAddedSongsLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/LastAddedSongsLoader.java deleted file mode 100644 index 2de6083d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/LastAddedSongsLoader.java +++ /dev/null @@ -1,46 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.provider.MediaStore; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.Observable; -import io.reactivex.annotations.NonNull; - -/** - * Created by hemanths on 16/08/17. - */ - -public class LastAddedSongsLoader { - - @NonNull - public static Observable> getLastAddedSongs(@NonNull Context context) { - return SongLoader.Companion.getSongs(makeLastAddedCursor(context)); - } - - public static Cursor makeLastAddedCursor(@NonNull final Context context) { - long cutoff = PreferenceUtil.getInstance().getLastAddedCutoff(); - - return SongLoader.Companion.makeSongCursor( - context, - MediaStore.Audio.Media.DATE_ADDED + ">?", - new String[]{String.valueOf(cutoff)}, - MediaStore.Audio.Media.DATE_ADDED + " DESC"); - } - - @NonNull - public static Observable> getLastAddedAlbums(@NonNull Context context) { - return AlbumLoader.splitIntoAlbums(getLastAddedSongs(context)); - } - - @NonNull - public static Observable> getLastAddedArtists(@NonNull Context context) { - return ArtistLoader.splitIntoArtists(getLastAddedAlbums(context)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/LastAddedSongsLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/LastAddedSongsLoader.kt new file mode 100644 index 00000000..3aa2ab06 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/LastAddedSongsLoader.kt @@ -0,0 +1,46 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.database.Cursor +import android.provider.MediaStore + +import java.util.ArrayList + +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.PreferenceUtil +import io.reactivex.Observable +import io.reactivex.annotations.NonNull + +/** + * Created by hemanths on 16/08/17. + */ + +object LastAddedSongsLoader { + + @NonNull + fun getLastAddedSongs(@NonNull context: Context): Observable> { + return SongLoader.getSongs(makeLastAddedCursor(context)) + } + + fun makeLastAddedCursor(@NonNull context: Context): Cursor? { + val cutoff = PreferenceUtil.getInstance().lastAddedCutoff + + return SongLoader.makeSongCursor( + context, + MediaStore.Audio.Media.DATE_ADDED + ">?", + arrayOf(cutoff.toString()), + MediaStore.Audio.Media.DATE_ADDED + " DESC") + } + + @NonNull + fun getLastAddedAlbums(@NonNull context: Context): Observable> { + return AlbumLoader.splitIntoAlbums(getLastAddedSongs(context)) + } + + @NonNull + fun getLastAddedArtists(@NonNull context: Context): Observable> { + return ArtistLoader.splitIntoArtists(getLastAddedAlbums(context)) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistLoader.java deleted file mode 100644 index c382f283..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistLoader.java +++ /dev/null @@ -1,118 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.provider.BaseColumns; -import android.provider.MediaStore; -import android.provider.MediaStore.Audio.PlaylistsColumns; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import code.name.monkey.retromusic.model.Playlist; - -import java.util.ArrayList; - -import io.reactivex.Observable; - -/** - * Created by hemanths on 16/08/17. - */ - -public class PlaylistLoader { - @Nullable - public static Cursor makePlaylistCursor(@NonNull final Context context, final String selection, final String[] values) { - try { - return context.getContentResolver().query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, - new String[]{ - /* 0 */ - BaseColumns._ID, - /* 1 */ - PlaylistsColumns.NAME - }, selection, values, MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER); - } catch (SecurityException e) { - return null; - } - } - - @NonNull - public static Observable getPlaylist(@Nullable final Cursor cursor) { - return Observable.create(e -> { - Playlist playlist = new Playlist(); - - if (cursor != null && cursor.moveToFirst()) { - playlist = getPlaylistFromCursorImpl(cursor); - } - if (cursor != null) - cursor.close(); - - e.onNext(playlist); - e.onComplete(); - }); - - - } - - @NonNull - public static Observable getPlaylist(@NonNull final Context context, final String playlistName) { - return getPlaylist(makePlaylistCursor( - context, - PlaylistsColumns.NAME + "=?", - new String[]{ - playlistName - } - )); - } - - @NonNull - public static Observable getPlaylist(@NonNull final Context context, final int playlistId) { - return getPlaylist(makePlaylistCursor( - context, - BaseColumns._ID + "=?", - new String[]{ - String.valueOf(playlistId) - } - )); - } - - @NonNull - private static Playlist getPlaylistFromCursorImpl(@NonNull final Cursor cursor) { - - final int id = cursor.getInt(0); - final String name = cursor.getString(1); - return new Playlist(id, name); - } - - - @NonNull - public static Observable> getAllPlaylists(@Nullable final Cursor cursor) { - return Observable.create(e -> { - ArrayList playlists = new ArrayList<>(); - - if (cursor != null && cursor.moveToFirst()) { - do { - playlists.add(getPlaylistFromCursorImpl(cursor)); - } while (cursor.moveToNext()); - } - if (cursor != null) - cursor.close(); - - e.onNext(playlists); - e.onComplete(); - }); - } - - @NonNull - public static Observable> getAllPlaylists(@NonNull final Context context) { - return getAllPlaylists(makePlaylistCursor(context, null, null)); - } - - public static void deletePlaylists(Context context, long playlistId) { - Uri localUri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI; - StringBuilder localStringBuilder = new StringBuilder(); - localStringBuilder.append("_id IN ("); - localStringBuilder.append((playlistId)); - localStringBuilder.append(")"); - context.getContentResolver().delete(localUri, localStringBuilder.toString(), null); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistLoader.kt new file mode 100644 index 00000000..4602708f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistLoader.kt @@ -0,0 +1,103 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.provider.BaseColumns +import android.provider.MediaStore +import android.provider.MediaStore.Audio.PlaylistsColumns + +import code.name.monkey.retromusic.model.Playlist + +import java.util.ArrayList + +import io.reactivex.Observable + +/** + * Created by hemanths on 16/08/17. + */ + +object PlaylistLoader { + fun makePlaylistCursor(context: Context, selection: String?, values: Array?): Cursor? { + try { + return context.contentResolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, + arrayOf( + /* 0 */ + BaseColumns._ID, + /* 1 */ + PlaylistsColumns.NAME), selection, values, MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER) + } catch (e: SecurityException) { + return null + } + + } + + fun getPlaylist(cursor: Cursor?): Observable { + return Observable.create { e -> + var playlist = Playlist() + + if (cursor != null && cursor.moveToFirst()) { + playlist = getPlaylistFromCursorImpl(cursor) + } + cursor?.close() + + e.onNext(playlist) + e.onComplete() + } + + + } + + fun getPlaylist(context: Context, playlistName: String): Observable { + return getPlaylist(makePlaylistCursor( + context, + PlaylistsColumns.NAME + "=?", + arrayOf(playlistName) + )) + } + + fun getPlaylist(context: Context, playlistId: Int): Observable { + return getPlaylist(makePlaylistCursor( + context, + BaseColumns._ID + "=?", + arrayOf(playlistId.toString()) + )) + } + + private fun getPlaylistFromCursorImpl(cursor: Cursor): Playlist { + + val id = cursor.getInt(0) + val name = cursor.getString(1) + return Playlist(id, name) + } + + + fun getAllPlaylists(cursor: Cursor?): Observable> { + return Observable.create { e -> + val playlists = ArrayList() + + if (cursor != null && cursor.moveToFirst()) { + do { + playlists.add(getPlaylistFromCursorImpl(cursor)) + } while (cursor.moveToNext()) + } + cursor?.close() + + e.onNext(playlists) + e.onComplete() + } + } + + fun getAllPlaylists(context: Context): Observable> { + return getAllPlaylists(makePlaylistCursor(context, null, null)) + } + + fun deletePlaylists(context: Context, playlistId: Long) { + val localUri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI + val localStringBuilder = StringBuilder() + localStringBuilder.append("_id IN (") + localStringBuilder.append(playlistId) + localStringBuilder.append(")") + context.contentResolver.delete(localUri, localStringBuilder.toString(), null) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistSongsLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistSongsLoader.java deleted file mode 100644 index 2e434778..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistSongsLoader.java +++ /dev/null @@ -1,94 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.provider.MediaStore; -import android.provider.MediaStore.Audio.AudioColumns; - -import java.util.ArrayList; -import java.util.List; - -import code.name.monkey.retromusic.model.AbsCustomPlaylist; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.PlaylistSong; -import code.name.monkey.retromusic.model.Song; -import io.reactivex.Observable; -import io.reactivex.annotations.NonNull; - -/** - * Created by hemanths on 16/08/17. - */ - -public class PlaylistSongsLoader { - - @NonNull - public static Observable> getPlaylistSongList(@NonNull Context context, Playlist playlist) { - if (playlist instanceof AbsCustomPlaylist) { - return ((AbsCustomPlaylist) playlist).getSongs(context); - } else { - //noinspection unchecked - return getPlaylistSongList(context, playlist.id); - } - } - - @NonNull - public static Observable> getPlaylistSongList(@NonNull Context context, final int playlistId) { - return Observable.create(e -> { - ArrayList songs = new ArrayList<>(); - Cursor cursor = makePlaylistSongCursor(context, playlistId); - - if (cursor != null && cursor.moveToFirst()) { - do { - songs.add(getPlaylistSongFromCursorImpl(cursor, playlistId)); - } while (cursor.moveToNext()); - } - if (cursor != null) { - cursor.close(); - } - e.onNext((ArrayList) (List) songs); - e.onComplete(); - }); - } - - @NonNull - private static PlaylistSong getPlaylistSongFromCursorImpl(@NonNull Cursor cursor, int playlistId) { - final int id = cursor.getInt(0); - final String title = cursor.getString(1); - final int trackNumber = cursor.getInt(2); - final int year = cursor.getInt(3); - final long duration = cursor.getLong(4); - final String data = cursor.getString(5); - final int dateModified = cursor.getInt(6); - final int albumId = cursor.getInt(7); - final String albumName = cursor.getString(8); - final int artistId = cursor.getInt(9); - final String artistName = cursor.getString(10); - final int idInPlaylist = cursor.getInt(11); - - return new PlaylistSong(id, title, trackNumber, year, duration, data, dateModified, albumId, albumName, artistId, artistName, playlistId, idInPlaylist); - } - - private static Cursor makePlaylistSongCursor(@NonNull final Context context, final int playlistId) { - try { - return context.getContentResolver().query( - MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId), - new String[]{ - MediaStore.Audio.Playlists.Members.AUDIO_ID,// 0 - AudioColumns.TITLE,// 1 - AudioColumns.TRACK,// 2 - AudioColumns.YEAR,// 3 - AudioColumns.DURATION,// 4 - AudioColumns.DATA,// 5 - AudioColumns.DATE_MODIFIED,// 6 - AudioColumns.ALBUM_ID,// 7 - AudioColumns.ALBUM,// 8 - AudioColumns.ARTIST_ID,// 9 - AudioColumns.ARTIST,// 10 - MediaStore.Audio.Playlists.Members._ID, // 11 - }, SongLoader.BASE_SELECTION, null, - MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER); - } catch (SecurityException e) { - return null; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistSongsLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistSongsLoader.kt new file mode 100644 index 00000000..41aadb2c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/PlaylistSongsLoader.kt @@ -0,0 +1,86 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.database.Cursor +import android.provider.MediaStore +import android.provider.MediaStore.Audio.AudioColumns +import code.name.monkey.retromusic.Constants.BASE_SELECTION +import code.name.monkey.retromusic.model.AbsCustomPlaylist +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.PlaylistSong +import code.name.monkey.retromusic.model.Song +import io.reactivex.Observable +import io.reactivex.annotations.NonNull +import java.util.* + +/** + * Created by hemanths on 16/08/17. + */ + +object PlaylistSongsLoader { + + @NonNull + fun getPlaylistSongList(@NonNull context: Context, playlist: Playlist): Observable> { + return (playlist as? AbsCustomPlaylist)?.getSongs(context) + ?: getPlaylistSongList(context, playlist.id) + } + + @NonNull + fun getPlaylistSongList(@NonNull context: Context, playlistId: Int): Observable> { + return Observable.create { e -> + val songs = ArrayList() + val cursor = makePlaylistSongCursor(context, playlistId) + + if (cursor != null && cursor.moveToFirst()) { + do { + songs.add(getPlaylistSongFromCursorImpl(cursor, playlistId)) + } while (cursor.moveToNext()) + } + cursor?.close() + e.onNext(songs) + e.onComplete() + } + } + + @NonNull + private fun getPlaylistSongFromCursorImpl(@NonNull cursor: Cursor, playlistId: Int): PlaylistSong { + val id = cursor.getInt(0) + val title = cursor.getString(1) + val trackNumber = cursor.getInt(2) + val year = cursor.getInt(3) + val duration = cursor.getLong(4) + val data = cursor.getString(5) + val dateModified = cursor.getInt(6) + val albumId = cursor.getInt(7) + val albumName = cursor.getString(8) + val artistId = cursor.getInt(9) + val artistName = cursor.getString(10) + val idInPlaylist = cursor.getInt(11) + + return PlaylistSong(id, title, trackNumber, year, duration, data, dateModified, albumId, albumName, artistId, artistName, playlistId, idInPlaylist) + } + + private fun makePlaylistSongCursor(@NonNull context: Context, playlistId: Int): Cursor? { + try { + return context.contentResolver.query( + MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId.toLong()), + arrayOf(MediaStore.Audio.Playlists.Members.AUDIO_ID, // 0 + AudioColumns.TITLE, // 1 + AudioColumns.TRACK, // 2 + AudioColumns.YEAR, // 3 + AudioColumns.DURATION, // 4 + AudioColumns.DATA, // 5 + AudioColumns.DATE_MODIFIED, // 6 + AudioColumns.ALBUM_ID, // 7 + AudioColumns.ALBUM, // 8 + AudioColumns.ARTIST_ID, // 9 + AudioColumns.ARTIST, // 10 + MediaStore.Audio.Playlists.Members._ID)// 11 + , BASE_SELECTION, null, + MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER) + } catch (e: SecurityException) { + return null + } + + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/SearchLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/SearchLoader.java deleted file mode 100644 index 7117e7db..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/SearchLoader.java +++ /dev/null @@ -1,44 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import androidx.annotation.NonNull; -import android.text.TextUtils; -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import io.reactivex.Observable; - -public class SearchLoader { - - public static Observable> searchAll(@NonNull Context context, @NonNull String query) { - ArrayList results = new ArrayList<>(); - return Observable.create(e -> { - if (!TextUtils.isEmpty(query)) { - SongLoader.Companion.getSongs(context, query) - .subscribe(songs -> { - if (!songs.isEmpty()) { - results.add(context.getResources().getString(R.string.songs)); - results.addAll(songs); - } - }); - - ArtistLoader.getArtists(context, query) - .subscribe(artists -> { - if (!artists.isEmpty()) { - results.add(context.getResources().getString(R.string.artists)); - results.addAll(artists); - } - }); - AlbumLoader.getAlbums(context, query) - .subscribe(albums -> { - if (!albums.isEmpty()) { - results.add(context.getResources().getString(R.string.albums)); - results.addAll(albums); - } - }); - } - e.onNext(results); - e.onComplete(); - }); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/SearchLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/SearchLoader.kt new file mode 100644 index 00000000..adbb8599 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/SearchLoader.kt @@ -0,0 +1,43 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.text.TextUtils +import java.util.ArrayList + +import code.name.monkey.retromusic.R +import io.reactivex.Observable + +object SearchLoader { + + fun searchAll(context: Context, query: String): Observable> { + val results = ArrayList() + return Observable.create { e -> + if (!TextUtils.isEmpty(query)) { + SongLoader.getSongs(context, query) + .subscribe { songs -> + if (!songs.isEmpty()) { + results.add(context.resources.getString(R.string.songs)) + results.addAll(songs) + } + } + + ArtistLoader.getArtists(context, query) + .subscribe { artists -> + if (!artists.isEmpty()) { + results.add(context.resources.getString(R.string.artists)) + results.addAll(artists) + } + } + AlbumLoader.getAlbums(context, query) + .subscribe { albums -> + if (!albums.isEmpty()) { + results.add(context.resources.getString(R.string.albums)) + results.addAll(albums) + } + } + } + e.onNext(results) + e.onComplete() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/SongLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/SongLoader.kt index 4691189a..c6e7f40c 100644 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/SongLoader.kt +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/SongLoader.kt @@ -2,9 +2,10 @@ package code.name.monkey.retromusic.loaders import android.content.Context import android.database.Cursor -import android.provider.BaseColumns import android.provider.MediaStore import android.provider.MediaStore.Audio.AudioColumns +import code.name.monkey.retromusic.Constants.BASE_PROJECTION +import code.name.monkey.retromusic.Constants.BASE_SELECTION import code.name.monkey.retromusic.helper.ShuffleHelper import code.name.monkey.retromusic.model.Song import code.name.monkey.retromusic.providers.BlacklistStore @@ -16,167 +17,152 @@ import java.util.* * Created by hemanths on 10/08/17. */ -open class SongLoader { - companion object { - const val BASE_SELECTION = AudioColumns.IS_MUSIC + "=1" + " AND " + AudioColumns.TITLE + " != ''" - val BASE_PROJECTION = arrayOf(BaseColumns._ID, // 0 - AudioColumns.TITLE, // 1 - AudioColumns.TRACK, // 2 - AudioColumns.YEAR, // 3 - AudioColumns.DURATION, // 4 - AudioColumns.DATA, // 5 - AudioColumns.DATE_MODIFIED, // 6 - AudioColumns.ALBUM_ID, // 7 - AudioColumns.ALBUM, // 8 - AudioColumns.ARTIST_ID, // 9 - AudioColumns.ARTIST)// 10 +object SongLoader { - fun getAllSongs(context: Context): Observable> { - val cursor = makeSongCursor(context, null, null) - return getSongs(cursor) - } + fun getAllSongs(context: Context): Observable> { + val cursor = makeSongCursor(context, null, null) + return getSongs(cursor) + } - fun getSongs(context: Context, query: String): Observable> { - val cursor = makeSongCursor(context, AudioColumns.TITLE + " LIKE ?", arrayOf("%$query%")) - return getSongs(cursor) - } + fun getSongs(context: Context, query: String): Observable> { + val cursor = makeSongCursor(context, AudioColumns.TITLE + " LIKE ?", arrayOf("%$query%")) + return getSongs(cursor) + } - fun getSongs(cursor: Cursor?): Observable> { - return Observable.create { e -> - val songs = ArrayList() - if (cursor != null && cursor.moveToFirst()) { - do { - songs.add(getSongFromCursorImpl(cursor)) - } while (cursor.moveToNext()) - } - - cursor?.close() - e.onNext(songs) - e.onComplete() - } - } - - private fun getSongFromCursorImpl(cursor: Cursor): Song { - val id = cursor.getInt(0) - val title = cursor.getString(1) - val trackNumber = cursor.getInt(2) - val year = cursor.getInt(3) - val duration = cursor.getLong(4) - val data = cursor.getString(5) - val dateModified = cursor.getLong(6) - val albumId = cursor.getInt(7) - val albumName = cursor.getString(8) - val artistId = cursor.getInt(9) - val artistName = cursor.getString(10) - - return Song(id, title, trackNumber, year, duration, data, dateModified, albumId, albumName, - artistId, artistName) - } - - @JvmOverloads - fun makeSongCursor(context: Context, selection: String?, selectionValues: Array?, sortOrder: String = PreferenceUtil.getInstance().songSortOrder): Cursor? { - var selectionFinal = selection - var selectionValuesFinal = selectionValues - selectionFinal = if (selection != null && selection.trim { it <= ' ' } != "") { - "$BASE_SELECTION AND $selectionFinal" - } else { - BASE_SELECTION + fun getSongs(cursor: Cursor?): Observable> { + return Observable.create { e -> + val songs = ArrayList() + if (cursor != null && cursor.moveToFirst()) { + do { + songs.add(getSongFromCursorImpl(cursor)) + } while (cursor.moveToNext()) } - // Blacklist - val paths = BlacklistStore.getInstance(context).paths - if (!paths.isEmpty()) { - selectionFinal = generateBlacklistSelection(selectionFinal, paths.size) - selectionValuesFinal = addBlacklistSelectionValues(selectionValuesFinal, paths) - } - - try { - return context.contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, - BASE_PROJECTION, selectionFinal, selectionValuesFinal, sortOrder) - } catch (e: SecurityException) { - return null - } - - } - - private fun generateBlacklistSelection(selection: String?, pathCount: Int): String { - val newSelection = StringBuilder( - if (selection != null && selection.trim { it <= ' ' } != "") "$selection AND " else "") - newSelection.append(AudioColumns.DATA + " NOT LIKE ?") - for (i in 0 until pathCount - 1) { - newSelection.append(" AND " + AudioColumns.DATA + " NOT LIKE ?") - } - return newSelection.toString() - } - - private fun addBlacklistSelectionValues(selectionValues: Array?, - paths: ArrayList): Array? { - var selectionValuesFinal = selectionValues - if (selectionValuesFinal == null) { - selectionValuesFinal = emptyArray() - } - val newSelectionValues = Array(selectionValuesFinal.size + paths.size) { - "n = $it" - } - System.arraycopy(selectionValuesFinal, 0, newSelectionValues, 0, selectionValuesFinal.size) - for (i in selectionValuesFinal.size until newSelectionValues.size) { - newSelectionValues[i] = paths[i - selectionValuesFinal.size] + "%" - } - return newSelectionValues - } - - fun getSong(cursor: Cursor?): Observable { - return Observable.create { e -> - val song: Song - if (cursor != null && cursor.moveToFirst()) { - song = getSongFromCursorImpl(cursor) - } else { - song = Song.EMPTY_SONG - } - cursor?.close() - e.onNext(song) - e.onComplete() - } - } - - fun getSong(context: Context, queryId: Int): Observable { - val cursor = makeSongCursor(context, AudioColumns._ID + "=?", - arrayOf(queryId.toString())) - return getSong(cursor) - } - - fun suggestSongs(context: Context): Observable> { - return SongLoader.getAllSongs(context) - .flatMap { - val list = ArrayList() - ShuffleHelper.makeShuffleList(it, -1) - if (it.size > 9) { - list.addAll(it.subList(0, 9)) - } - return@flatMap Observable.just(list) - } - /*.flatMap({ songs -> - val list = ArrayList() - ShuffleHelper.makeShuffleList(songs, -1) - if (songs.size > 9) { - list.addAll(songs.subList(0, 9)) - } - Observable.just(list) - } as Function, ObservableSource>>)*/ - /*.subscribe(songs -> { - ArrayList list = new ArrayList<>(); - if (songs.isEmpty()) { - return; - } - ShuffleHelper.makeShuffleList(songs, -1); - if (songs.size() > 10) { - list.addAll(songs.subList(0, 10)); - } else { - list.addAll(songs); - } - return; - });*/ + cursor?.close() + e.onNext(songs) + e.onComplete() } } + + private fun getSongFromCursorImpl(cursor: Cursor): Song { + val id = cursor.getInt(0) + val title = cursor.getString(1) + val trackNumber = cursor.getInt(2) + val year = cursor.getInt(3) + val duration = cursor.getLong(4) + val data = cursor.getString(5) + val dateModified = cursor.getLong(6) + val albumId = cursor.getInt(7) + val albumName = cursor.getString(8) + val artistId = cursor.getInt(9) + val artistName = cursor.getString(10) + + return Song(id, title, trackNumber, year, duration, data, dateModified, albumId, albumName, + artistId, artistName) + } + + @JvmOverloads + fun makeSongCursor(context: Context, selection: String?, selectionValues: Array?, sortOrder: String = PreferenceUtil.getInstance().songSortOrder): Cursor? { + var selectionFinal = selection + var selectionValuesFinal = selectionValues + selectionFinal = if (selection != null && selection.trim { it <= ' ' } != "") { + "$BASE_SELECTION AND $selectionFinal" + } else { + BASE_SELECTION + } + + // Blacklist + val paths = BlacklistStore.getInstance(context).paths + if (!paths.isEmpty()) { + selectionFinal = generateBlacklistSelection(selectionFinal, paths.size) + selectionValuesFinal = addBlacklistSelectionValues(selectionValuesFinal, paths) + } + + try { + return context.contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, + BASE_PROJECTION, selectionFinal, selectionValuesFinal, sortOrder) + } catch (e: SecurityException) { + return null + } + + } + + private fun generateBlacklistSelection(selection: String?, pathCount: Int): String { + val newSelection = StringBuilder( + if (selection != null && selection.trim { it <= ' ' } != "") "$selection AND " else "") + newSelection.append(AudioColumns.DATA + " NOT LIKE ?") + for (i in 0 until pathCount - 1) { + newSelection.append(" AND " + AudioColumns.DATA + " NOT LIKE ?") + } + return newSelection.toString() + } + + private fun addBlacklistSelectionValues(selectionValues: Array?, + paths: ArrayList): Array? { + var selectionValuesFinal = selectionValues + if (selectionValuesFinal == null) { + selectionValuesFinal = emptyArray() + } + val newSelectionValues = Array(selectionValuesFinal.size + paths.size) { + "n = $it" + } + System.arraycopy(selectionValuesFinal, 0, newSelectionValues, 0, selectionValuesFinal.size) + for (i in selectionValuesFinal.size until newSelectionValues.size) { + newSelectionValues[i] = paths[i - selectionValuesFinal.size] + "%" + } + return newSelectionValues + } + + fun getSong(cursor: Cursor?): Observable { + return Observable.create { e -> + val song: Song = if (cursor != null && cursor.moveToFirst()) { + getSongFromCursorImpl(cursor) + } else { + Song.EMPTY_SONG + } + cursor?.close() + e.onNext(song) + e.onComplete() + } + } + + fun getSong(context: Context, queryId: Int): Observable { + val cursor = makeSongCursor(context, AudioColumns._ID + "=?", + arrayOf(queryId.toString())) + return getSong(cursor) + } + + fun suggestSongs(context: Context): Observable> { + return SongLoader.getAllSongs(context) + .flatMap { + val list = ArrayList() + ShuffleHelper.makeShuffleList(it, -1) + if (it.size > 9) { + list.addAll(it.subList(0, 9)) + } + return@flatMap Observable.just(list) + } + /*.flatMap({ songs -> + val list = ArrayList() + ShuffleHelper.makeShuffleList(songs, -1) + if (songs.size > 9) { + list.addAll(songs.subList(0, 9)) + } + Observable.just(list) + } as Function, ObservableSource>>)*/ + /*.subscribe(songs -> { + ArrayList list = new ArrayList<>(); + if (songs.isEmpty()) { + return; + } + ShuffleHelper.makeShuffleList(songs, -1); + if (songs.size() > 10) { + list.addAll(songs.subList(0, 10)); + } else { + list.addAll(songs); + } + return; + });*/ + } } diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/TopAndRecentlyPlayedTracksLoader.java b/app/src/main/java/code/name/monkey/retromusic/loaders/TopAndRecentlyPlayedTracksLoader.java deleted file mode 100644 index 43244b14..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/loaders/TopAndRecentlyPlayedTracksLoader.java +++ /dev/null @@ -1,158 +0,0 @@ -package code.name.monkey.retromusic.loaders; - -import android.content.Context; -import android.database.Cursor; -import android.provider.BaseColumns; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.providers.HistoryStore; -import code.name.monkey.retromusic.providers.SongPlayCountStore; -import io.reactivex.Observable; -import java.util.ArrayList; - -/** - * Created by hemanths on 16/08/17. - */ - -public class TopAndRecentlyPlayedTracksLoader { - - private static final int NUMBER_OF_TOP_TRACKS = 99; - - @NonNull - public static Observable> getRecentlyPlayedTracks(@NonNull Context context) { - return SongLoader.Companion.getSongs(makeRecentTracksCursorAndClearUpDatabase(context)); - } - - @NonNull - public static Observable> getTopTracks(@NonNull Context context) { - return SongLoader.Companion.getSongs(makeTopTracksCursorAndClearUpDatabase(context)); - } - - @Nullable - private static Cursor makeRecentTracksCursorAndClearUpDatabase(@NonNull final Context context) { - SortedLongCursor retCursor = makeRecentTracksCursorImpl(context); - - // clean up the databases with any ids not found - if (retCursor != null) { - ArrayList missingIds = retCursor.getMissingIds(); - if (missingIds != null && missingIds.size() > 0) { - for (long id : missingIds) { - HistoryStore.getInstance(context).removeSongId(id); - } - } - } - return retCursor; - } - - @Nullable - private static Cursor makeTopTracksCursorAndClearUpDatabase(@NonNull final Context context) { - SortedLongCursor retCursor = makeTopTracksCursorImpl(context); - - // clean up the databases with any ids not found - if (retCursor != null) { - ArrayList missingIds = retCursor.getMissingIds(); - if (missingIds != null && missingIds.size() > 0) { - for (long id : missingIds) { - SongPlayCountStore.getInstance(context).removeItem(id); - } - } - } - return retCursor; - } - - @Nullable - private static SortedLongCursor makeRecentTracksCursorImpl(@NonNull final Context context) { - // first get the top results ids from the internal database - Cursor songs = HistoryStore.getInstance(context).queryRecentIds(); - - try { - return makeSortedCursor(context, songs, - songs.getColumnIndex(HistoryStore.RecentStoreColumns.ID)); - } finally { - if (songs != null) { - songs.close(); - } - } - } - - @Nullable - private static SortedLongCursor makeTopTracksCursorImpl(@NonNull final Context context) { - // first get the top results ids from the internal database - Cursor songs = SongPlayCountStore.getInstance(context) - .getTopPlayedResults(NUMBER_OF_TOP_TRACKS); - - try { - return makeSortedCursor(context, songs, - songs.getColumnIndex(SongPlayCountStore.SongPlayCountColumns.ID)); - } finally { - if (songs != null) { - songs.close(); - } - } - } - - @Nullable - private static SortedLongCursor makeSortedCursor(@NonNull final Context context, - @Nullable final Cursor cursor, final int idColumn) { - - if (cursor != null && cursor.moveToFirst()) { - // create the list of ids to select against - StringBuilder selection = new StringBuilder(); - selection.append(BaseColumns._ID); - selection.append(" IN ("); - - // this tracks the order of the ids - long[] order = new long[cursor.getCount()]; - - long id = cursor.getLong(idColumn); - selection.append(id); - order[cursor.getPosition()] = id; - - while (cursor.moveToNext()) { - selection.append(","); - - id = cursor.getLong(idColumn); - order[cursor.getPosition()] = id; - selection.append(String.valueOf(id)); - } - - selection.append(")"); - - // get a list of songs with the data given the selection statement - Cursor songCursor = SongLoader.Companion.makeSongCursor(context, selection.toString(), null); - if (songCursor != null) { - // now return the wrapped TopTracksCursor to handle sorting given order - return new SortedLongCursor(songCursor, order, BaseColumns._ID); - } - } - - return null; - } - - @NonNull - public static Observable> getTopAlbums(@NonNull Context context) { - return Observable.create(e -> { - getTopTracks(context).subscribe(songs -> { - if (songs.size() > 0) { - e.onNext(AlbumLoader.splitIntoAlbums(songs)); - } - e.onComplete(); - }); - }); - } - - @NonNull - public static Observable> getTopArtists(@NonNull Context context) { - return Observable.create(e -> { - getTopAlbums(context).subscribe(albums -> { - if (albums.size() > 0) { - e.onNext(ArtistLoader.splitIntoArtists(albums)); - } - e.onComplete(); - }); - }); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/loaders/TopAndRecentlyPlayedTracksLoader.kt b/app/src/main/java/code/name/monkey/retromusic/loaders/TopAndRecentlyPlayedTracksLoader.kt new file mode 100644 index 00000000..cce045f9 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/loaders/TopAndRecentlyPlayedTracksLoader.kt @@ -0,0 +1,142 @@ +package code.name.monkey.retromusic.loaders + +import android.content.Context +import android.database.Cursor +import android.provider.BaseColumns +import code.name.monkey.retromusic.Constants.NUMBER_OF_TOP_TRACKS +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.providers.HistoryStore +import code.name.monkey.retromusic.providers.SongPlayCountStore +import io.reactivex.Observable +import java.util.* + +/** + * Created by hemanths on 16/08/17. + */ + +object TopAndRecentlyPlayedTracksLoader { + + fun getRecentlyPlayedTracks(context: Context): Observable> { + return SongLoader.getSongs(makeRecentTracksCursorAndClearUpDatabase(context)) + } + + fun getTopTracks(context: Context): Observable> { + return SongLoader.getSongs(makeTopTracksCursorAndClearUpDatabase(context)) + } + + private fun makeRecentTracksCursorAndClearUpDatabase(context: Context): Cursor? { + val retCursor = makeRecentTracksCursorImpl(context) + + // clean up the databases with any ids not found + if (retCursor != null) { + val missingIds = retCursor.missingIds + if (missingIds != null && missingIds.size > 0) { + for (id in missingIds) { + HistoryStore.getInstance(context).removeSongId(id) + } + } + } + return retCursor + } + + private fun makeTopTracksCursorAndClearUpDatabase(context: Context): Cursor? { + val retCursor = makeTopTracksCursorImpl(context) + + // clean up the databases with any ids not found + if (retCursor != null) { + val missingIds = retCursor.missingIds + if (missingIds != null && missingIds.size > 0) { + for (id in missingIds) { + SongPlayCountStore.getInstance(context).removeItem(id) + } + } + } + return retCursor + } + + private fun makeRecentTracksCursorImpl(context: Context): SortedLongCursor? { + // first get the top results ids from the internal database + val songs = HistoryStore.getInstance(context).queryRecentIds() + + try { + return makeSortedCursor(context, songs, + songs!!.getColumnIndex(HistoryStore.RecentStoreColumns.ID)) + } finally { + songs?.close() + } + } + + private fun makeTopTracksCursorImpl(context: Context): SortedLongCursor? { + // first get the top results ids from the internal database + val songs = SongPlayCountStore.getInstance(context) + .getTopPlayedResults(NUMBER_OF_TOP_TRACKS) + + try { + return makeSortedCursor(context, songs, + songs!!.getColumnIndex(SongPlayCountStore.SongPlayCountColumns.ID)) + } finally { + songs?.close() + } + } + + private fun makeSortedCursor(context: Context, + cursor: Cursor?, idColumn: Int): SortedLongCursor? { + + if (cursor != null && cursor.moveToFirst()) { + // create the list of ids to select against + val selection = StringBuilder() + selection.append(BaseColumns._ID) + selection.append(" IN (") + + // this tracks the order of the ids + val order = LongArray(cursor.count) + + var id = cursor.getLong(idColumn) + selection.append(id) + order[cursor.position] = id + + while (cursor.moveToNext()) { + selection.append(",") + + id = cursor.getLong(idColumn) + order[cursor.position] = id + selection.append(id.toString()) + } + + selection.append(")") + + // get a list of songs with the data given the selection statement + val songCursor = SongLoader.makeSongCursor(context, selection.toString(), null) + if (songCursor != null) { + // now return the wrapped TopTracksCursor to handle sorting given order + return SortedLongCursor(songCursor, order, BaseColumns._ID) + } + } + + return null + } + + fun getTopAlbums(context: Context): Observable> { + return Observable.create { e -> + getTopTracks(context).subscribe { songs -> + if (songs.size > 0) { + e.onNext(AlbumLoader.splitIntoAlbums(songs)) + } + e.onComplete() + } + } + } + + fun getTopArtists(context: Context): Observable> { + return Observable.create { e -> + getTopAlbums(context).subscribe { albums -> + if (albums.size > 0) { + e.onNext(ArtistLoader.splitIntoArtists(albums)) + } + e.onComplete() + } + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/AppBarStateChangeListener.java b/app/src/main/java/code/name/monkey/retromusic/misc/AppBarStateChangeListener.java deleted file mode 100644 index a55676a3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/misc/AppBarStateChangeListener.java +++ /dev/null @@ -1,41 +0,0 @@ -package code.name.monkey.retromusic.misc; - -import com.google.android.material.appbar.AppBarLayout; - -/** - * @author Hemanth S (h4h13). - * https://stackoverflow.com/a/33891727 - */ - -public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener { - - private State mCurrentState = State.IDLE; - - @Override - public final void onOffsetChanged(AppBarLayout appBarLayout, int i) { - if (i == 0) { - if (mCurrentState != State.EXPANDED) { - onStateChanged(appBarLayout, State.EXPANDED); - } - mCurrentState = State.EXPANDED; - } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) { - if (mCurrentState != State.COLLAPSED) { - onStateChanged(appBarLayout, State.COLLAPSED); - } - mCurrentState = State.COLLAPSED; - } else { - if (mCurrentState != State.IDLE) { - onStateChanged(appBarLayout, State.IDLE); - } - mCurrentState = State.IDLE; - } - } - - public abstract void onStateChanged(AppBarLayout appBarLayout, State state); - - public enum State { - EXPANDED, - COLLAPSED, - IDLE - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/AppBarStateChangeListener.kt b/app/src/main/java/code/name/monkey/retromusic/misc/AppBarStateChangeListener.kt new file mode 100644 index 00000000..a76dd596 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/misc/AppBarStateChangeListener.kt @@ -0,0 +1,40 @@ +package code.name.monkey.retromusic.misc + +import com.google.android.material.appbar.AppBarLayout + +/** + * @author Hemanth S (h4h13). + * https://stackoverflow.com/a/33891727 + */ + +abstract class AppBarStateChangeListener : AppBarLayout.OnOffsetChangedListener { + + private var mCurrentState = State.IDLE + + override fun onOffsetChanged(appBarLayout: AppBarLayout, i: Int) { + if (i == 0) { + if (mCurrentState != State.EXPANDED) { + onStateChanged(appBarLayout, State.EXPANDED) + } + mCurrentState = State.EXPANDED + } else if (Math.abs(i) >= appBarLayout.totalScrollRange) { + if (mCurrentState != State.COLLAPSED) { + onStateChanged(appBarLayout, State.COLLAPSED) + } + mCurrentState = State.COLLAPSED + } else { + if (mCurrentState != State.IDLE) { + onStateChanged(appBarLayout, State.IDLE) + } + mCurrentState = State.IDLE + } + } + + abstract fun onStateChanged(appBarLayout: AppBarLayout, state: State) + + enum class State { + EXPANDED, + COLLAPSED, + IDLE + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/SimpleAnimatorListener.java b/app/src/main/java/code/name/monkey/retromusic/misc/SimpleAnimatorListener.java deleted file mode 100644 index 2f405577..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/misc/SimpleAnimatorListener.java +++ /dev/null @@ -1,26 +0,0 @@ -package code.name.monkey.retromusic.misc; - -import android.animation.Animator; - - -public abstract class SimpleAnimatorListener implements Animator.AnimatorListener { - @Override - public void onAnimationStart(Animator animation) { - - } - - @Override - public void onAnimationEnd(Animator animation) { - - } - - @Override - public void onAnimationCancel(Animator animation) { - - } - - @Override - public void onAnimationRepeat(Animator animation) { - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/SimpleAnimatorListener.kt b/app/src/main/java/code/name/monkey/retromusic/misc/SimpleAnimatorListener.kt new file mode 100644 index 00000000..8090be93 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/misc/SimpleAnimatorListener.kt @@ -0,0 +1,22 @@ +package code.name.monkey.retromusic.misc + +import android.animation.Animator + + +abstract class SimpleAnimatorListener : Animator.AnimatorListener { + override fun onAnimationStart(animation: Animator) { + + } + + override fun onAnimationEnd(animation: Animator) { + + } + + override fun onAnimationCancel(animation: Animator) { + + } + + override fun onAnimationRepeat(animation: Animator) { + + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/SimpleOnSeekbarChangeListener.java b/app/src/main/java/code/name/monkey/retromusic/misc/SimpleOnSeekbarChangeListener.java deleted file mode 100644 index 44a39f6e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/misc/SimpleOnSeekbarChangeListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package code.name.monkey.retromusic.misc; - -import android.widget.SeekBar; - - -public abstract class SimpleOnSeekbarChangeListener implements SeekBar.OnSeekBarChangeListener { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/SimpleOnSeekbarChangeListener.kt b/app/src/main/java/code/name/monkey/retromusic/misc/SimpleOnSeekbarChangeListener.kt new file mode 100644 index 00000000..f71a0a78 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/misc/SimpleOnSeekbarChangeListener.kt @@ -0,0 +1,18 @@ +package code.name.monkey.retromusic.misc + +import android.widget.SeekBar + + +abstract class SimpleOnSeekbarChangeListener : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { + + } + + override fun onStartTrackingTouch(seekBar: SeekBar) { + + } + + override fun onStopTrackingTouch(seekBar: SeekBar) { + + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/WeakContextAsyncTask.java b/app/src/main/java/code/name/monkey/retromusic/misc/WeakContextAsyncTask.java deleted file mode 100644 index a2a8b7dd..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/misc/WeakContextAsyncTask.java +++ /dev/null @@ -1 +0,0 @@ -package code.name.monkey.retromusic.misc; import android.content.Context; import android.os.AsyncTask; import androidx.annotation.Nullable; import java.lang.ref.WeakReference; public abstract class WeakContextAsyncTask extends AsyncTask { private WeakReference contextWeakReference; public WeakContextAsyncTask(Context context) { contextWeakReference = new WeakReference<>(context); } @Nullable protected Context getContext() { return contextWeakReference.get(); } } \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/WeakContextAsyncTask.kt b/app/src/main/java/code/name/monkey/retromusic/misc/WeakContextAsyncTask.kt new file mode 100644 index 00000000..29df9680 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/misc/WeakContextAsyncTask.kt @@ -0,0 +1 @@ +package code.name.monkey.retromusic.misc import android.content.Context import android.os.AsyncTask import java.lang.ref.WeakReference abstract class WeakContextAsyncTask(context: Context) : AsyncTask() { private val contextWeakReference: WeakReference = WeakReference(context) protected val context: Context? get() = contextWeakReference.get() } \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/WrappedAsyncTaskLoader.java b/app/src/main/java/code/name/monkey/retromusic/misc/WrappedAsyncTaskLoader.java deleted file mode 100644 index 599fe6ea..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/misc/WrappedAsyncTaskLoader.java +++ /dev/null @@ -1,72 +0,0 @@ - -package code.name.monkey.retromusic.misc; - -import android.content.Context; -import androidx.loader.content.AsyncTaskLoader; - -/** - * Issue - * 14944 - * - * @author Alexander Blom - */ -public abstract class WrappedAsyncTaskLoader extends AsyncTaskLoader { - - private D mData; - - /** - * Constructor of WrappedAsyncTaskLoader - * - * @param context The {@link Context} to use. - */ - public WrappedAsyncTaskLoader(Context context) { - super(context); - } - - /** - * {@inheritDoc} - */ - @Override - public void deliverResult(D data) { - if (!isReset()) { - this.mData = data; - super.deliverResult(data); - } else { - // An asynchronous query came in while the loader is stopped - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void onStartLoading() { - super.onStartLoading(); - if (this.mData != null) { - deliverResult(this.mData); - } else if (takeContentChanged() || this.mData == null) { - forceLoad(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void onStopLoading() { - super.onStopLoading(); - // Attempt to cancel the current load task if possible - cancelLoad(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void onReset() { - super.onReset(); - // Ensure the loader is stopped - onStopLoading(); - this.mData = null; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/misc/WrappedAsyncTaskLoader.kt b/app/src/main/java/code/name/monkey/retromusic/misc/WrappedAsyncTaskLoader.kt new file mode 100644 index 00000000..21f328fd --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/misc/WrappedAsyncTaskLoader.kt @@ -0,0 +1,64 @@ +package code.name.monkey.retromusic.misc + +import android.content.Context +import androidx.loader.content.AsyncTaskLoader + +/** + * [Issue + * 14944](http://code.google.com/p/android/issues/detail?id=14944) + * + * @author Alexander Blom + */ +abstract class WrappedAsyncTaskLoader +/** + * Constructor of `WrappedAsyncTaskLoader` + * + * @param context The [Context] to use. + */ +(context: Context) : AsyncTaskLoader(context) { + + private var mData: D? = null + + /** + * {@inheritDoc} + */ + override fun deliverResult(data: D?) { + if (!isReset) { + this.mData = data + super.deliverResult(data) + } else { + // An asynchronous query came in while the loader is stopped + } + } + + /** + * {@inheritDoc} + */ + override fun onStartLoading() { + super.onStartLoading() + if (this.mData != null) { + deliverResult(this.mData) + } else if (takeContentChanged() || this.mData == null) { + forceLoad() + } + } + + /** + * {@inheritDoc} + */ + override fun onStopLoading() { + super.onStopLoading() + // Attempt to cancel the current load task if possible + cancelLoad() + } + + /** + * {@inheritDoc} + */ + override fun onReset() { + super.onReset() + // Ensure the loader is stopped + onStopLoading() + this.mData = null + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Album.java b/app/src/main/java/code/name/monkey/retromusic/model/Album.java deleted file mode 100644 index 9d556b8a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/model/Album.java +++ /dev/null @@ -1,103 +0,0 @@ -package code.name.monkey.retromusic.model; - -import android.os.Parcel; -import android.os.Parcelable; -import androidx.annotation.NonNull; -import java.util.ArrayList; - - -public class Album implements Parcelable { - - public static final Creator CREATOR = new Creator() { - public Album createFromParcel(Parcel source) { - return new Album(source); - } - - public Album[] newArray(int size) { - return new Album[size]; - } - }; - public final ArrayList songs; - - public Album(ArrayList songs) { - this.songs = songs; - } - - public Album() { - this.songs = new ArrayList<>(); - } - - protected Album(Parcel in) { - this.songs = in.createTypedArrayList(Song.CREATOR); - } - - public int getId() { - return safeGetFirstSong().albumId; - } - - public String getTitle() { - return safeGetFirstSong().albumName; - } - - public int getArtistId() { - return safeGetFirstSong().artistId; - } - - public String getArtistName() { - return safeGetFirstSong().artistName; - } - - public int getYear() { - return safeGetFirstSong().year; - } - - public long getDateModified() { - return safeGetFirstSong().dateModified; - } - - public int getSongCount() { - return songs.size(); - } - - @NonNull - public Song safeGetFirstSong() { - return songs.isEmpty() ? Song.EMPTY_SONG : songs.get(0); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Album that = (Album) o; - - return songs != null ? songs.equals(that.songs) : that.songs == null; - - } - - @Override - public int hashCode() { - return songs != null ? songs.hashCode() : 0; - } - - @Override - public String toString() { - return "Album{" + - "songs=" + songs + - '}'; - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeTypedList(songs); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Album.kt b/app/src/main/java/code/name/monkey/retromusic/model/Album.kt new file mode 100644 index 00000000..27405c44 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/model/Album.kt @@ -0,0 +1,41 @@ +package code.name.monkey.retromusic.model + +import java.util.* + + +class Album { + val songs: ArrayList? + + val id: Int + get() = safeGetFirstSong().albumId + + val title: String? + get() = safeGetFirstSong().albumName + + val artistId: Int + get() = safeGetFirstSong().artistId + + val artistName: String? + get() = safeGetFirstSong().artistName + + val year: Int + get() = safeGetFirstSong().year + + val dateModified: Long + get() = safeGetFirstSong().dateModified + + val songCount: Int + get() = songs!!.size + + constructor(songs: ArrayList) { + this.songs = songs + } + + constructor() { + this.songs = ArrayList() + } + + fun safeGetFirstSong(): Song { + return if (songs!!.isEmpty()) Song.EMPTY_SONG else songs[0] + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Artist.java b/app/src/main/java/code/name/monkey/retromusic/model/Artist.java deleted file mode 100644 index 7cec500a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/model/Artist.java +++ /dev/null @@ -1,110 +0,0 @@ -package code.name.monkey.retromusic.model; - -import android.os.Parcel; -import android.os.Parcelable; -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.util.MusicUtil; - - -public class Artist implements Parcelable { - public static final String UNKNOWN_ARTIST_DISPLAY_NAME = "Unknown Artist"; - public final ArrayList albums; - - public Artist(ArrayList albums) { - this.albums = albums; - } - - public Artist() { - this.albums = new ArrayList<>(); - } - - public int getId() { - return safeGetFirstAlbum().getArtistId(); - } - - public String getName() { - String name = safeGetFirstAlbum().getArtistName(); - if (MusicUtil.isArtistNameUnknown(name)) { - return UNKNOWN_ARTIST_DISPLAY_NAME; - } - return name; - } - - public int getSongCount() { - int songCount = 0; - for (Album album : albums) { - songCount += album.getSongCount(); - } - return songCount; - } - - public int getAlbumCount() { - return albums.size(); - } - - public ArrayList getSongs() { - ArrayList songs = new ArrayList<>(); - for (Album album : albums) { - songs.addAll(album.songs); - } - return songs; - } - - @NonNull - public Album safeGetFirstAlbum() { - return albums.isEmpty() ? new Album() : albums.get(0); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Artist artist = (Artist) o; - - return albums != null ? albums.equals(artist.albums) : artist.albums == null; - - } - - @Override - public int hashCode() { - return albums != null ? albums.hashCode() : 0; - } - - @Override - public String toString() { - return "Artist{" + - "albums=" + albums + - '}'; - } - - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeTypedList(this.albums); - } - - protected Artist(Parcel in) { - this.albums = in.createTypedArrayList(Album.CREATOR); - } - - public static final Creator CREATOR = new Creator() { - @Override - public Artist createFromParcel(Parcel source) { - return new Artist(source); - } - - @Override - public Artist[] newArray(int size) { - return new Artist[size]; - } - }; -} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Artist.kt b/app/src/main/java/code/name/monkey/retromusic/model/Artist.kt new file mode 100644 index 00000000..0f5a5c35 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/model/Artist.kt @@ -0,0 +1,57 @@ +package code.name.monkey.retromusic.model + +import code.name.monkey.retromusic.util.MusicUtil +import java.util.* + + +class Artist { + val albums: ArrayList? + + val id: Int + get() = safeGetFirstAlbum().artistId + + val name: String + get() { + val name = safeGetFirstAlbum().artistName + return if (MusicUtil.isArtistNameUnknown(name)) { + UNKNOWN_ARTIST_DISPLAY_NAME + } else name!! + } + + val songCount: Int + get() { + var songCount = 0 + for (album in albums!!) { + songCount += album.songCount + } + return songCount + } + + val albumCount: Int + get() = albums!!.size + + val songs: ArrayList + get() { + val songs = ArrayList() + for (album in albums!!) { + songs.addAll(album.songs!!) + } + return songs + } + + constructor(albums: ArrayList) { + this.albums = albums + } + + constructor() { + this.albums = ArrayList() + } + + fun safeGetFirstAlbum(): Album { + return if (albums!!.isEmpty()) Album() else albums[0] + } + + companion object { + const val UNKNOWN_ARTIST_DISPLAY_NAME = "Unknown Artist" + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Contributor.java b/app/src/main/java/code/name/monkey/retromusic/model/Contributor.java deleted file mode 100644 index 0488f1ca..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/model/Contributor.java +++ /dev/null @@ -1,34 +0,0 @@ -package code.name.monkey.retromusic.model; - -public class Contributor { - private String name; - private String summary; - private String link; - private String profile_image; - - public Contributor() { - } - - public Contributor(String name, String summary, String link, String profile_image) { - this.name = name; - this.summary = summary; - this.link = link; - this.profile_image = profile_image; - } - - public String getName() { - return name; - } - - public String getSummary() { - return summary; - } - - public String getLink() { - return link; - } - - public String getProfileImage() { - return profile_image; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Contributor.kt b/app/src/main/java/code/name/monkey/retromusic/model/Contributor.kt new file mode 100644 index 00000000..de25933c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/model/Contributor.kt @@ -0,0 +1,3 @@ +package code.name.monkey.retromusic.model + +class Contributor(val name: String, val summary: String, val link: String, val profileImage: String) diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Genre.java b/app/src/main/java/code/name/monkey/retromusic/model/Genre.java deleted file mode 100644 index 9522536d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/model/Genre.java +++ /dev/null @@ -1,86 +0,0 @@ -package code.name.monkey.retromusic.model; - -import android.os.Parcel; -import android.os.Parcelable; - -/** - * @author Hemanth S (h4h13). - */ - -public class Genre implements Parcelable { - - public static final Creator CREATOR = new Creator() { - @Override - public Genre createFromParcel(Parcel in) { - return new Genre(in); - } - - @Override - public Genre[] newArray(int size) { - return new Genre[size]; - } - }; - public final int id; - public final String name; - public final int songCount; - - public Genre(final int id, final String name, int songCount) { - this.id = id; - this.name = name; - this.songCount = songCount; - } - - - // For unknown genre - public Genre(final String name, final int songCount) { - this.id = -1; - this.name = name; - this.songCount = songCount; - } - - protected Genre(Parcel in) { - id = in.readInt(); - name = in.readString(); - songCount = in.readInt(); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(id); - dest.writeString(name); - dest.writeInt(songCount); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Genre genre = (Genre) o; - - if (id != genre.id) return false; - return name != null ? name.equals(genre.name) : genre.name == null; - } - - @Override - public int hashCode() { - int result = id; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return "Genre{" + - "id=" + id + - ", name='" + name + '\'' + - '}'; - } - - -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Genre.kt b/app/src/main/java/code/name/monkey/retromusic/model/Genre.kt new file mode 100644 index 00000000..9448e18e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/model/Genre.kt @@ -0,0 +1,26 @@ +package code.name.monkey.retromusic.model + +import java.io.Serializable + +/** + * @author Hemanth S (h4h13). + */ + +class Genre : Serializable { + val id: Int + val name: String? + val songCount: Int + + constructor(id: Int, name: String, songCount: Int) { + this.id = id + this.name = name + this.songCount = songCount + } + + // For unknown genre + constructor(name: String, songCount: Int) { + this.id = -1 + this.name = name + this.songCount = songCount + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Home.java b/app/src/main/java/code/name/monkey/retromusic/model/Home.java deleted file mode 100755 index 2814bc9b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/model/Home.java +++ /dev/null @@ -1,29 +0,0 @@ -package code.name.monkey.retromusic.model; - -import androidx.annotation.StringRes; - -import java.util.ArrayList; - - -/** - * Created by BlackFootSanji on 5/22/2017. - */ - -public class Home { - - private int sectionTitle; - private ArrayList list; - - public Home(@StringRes int sectionTitle, ArrayList list) { - this.sectionTitle = sectionTitle; - this.list = list; - } - - public int getSectionTitle() { - return sectionTitle; - } - - public ArrayList getList() { - return list; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Song.java b/app/src/main/java/code/name/monkey/retromusic/model/Song.java deleted file mode 100644 index 54c95bd5..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/model/Song.java +++ /dev/null @@ -1,77 +0,0 @@ -package code.name.monkey.retromusic.model; - -import android.os.Parcel; -import android.os.Parcelable; - - -public class Song implements Parcelable { - public static final Song EMPTY_SONG = new Song(-1, "", -1, -1, -1, "", -1, -1, "", -1, ""); - public static final Creator CREATOR = new Creator() { - public Song createFromParcel(Parcel source) { - return new Song(source); - } - - public Song[] newArray(int size) { - return new Song[size]; - } - }; - public final int id; - public final String title; - public final int trackNumber; - public final int year; - public final long duration; - public final String data; - public final long dateModified; - public final int albumId; - public final String albumName; - public final int artistId; - public final String artistName; - - public Song(int id, String title, int trackNumber, int year, long duration, String data, long dateModified, int albumId, String albumName, int artistId, String artistName) { - this.id = id; - this.title = title; - this.trackNumber = trackNumber; - this.year = year; - this.duration = duration; - this.data = data; - this.dateModified = dateModified; - this.albumId = albumId; - this.albumName = albumName; - this.artistId = artistId; - this.artistName = artistName; - } - - protected Song(Parcel in) { - this.id = in.readInt(); - this.title = in.readString(); - this.trackNumber = in.readInt(); - this.year = in.readInt(); - this.duration = in.readLong(); - this.data = in.readString(); - this.dateModified = in.readLong(); - this.albumId = in.readInt(); - this.albumName = in.readString(); - this.artistId = in.readInt(); - this.artistName = in.readString(); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeInt(this.id); - dest.writeString(this.title); - dest.writeInt(this.trackNumber); - dest.writeInt(this.year); - dest.writeLong(this.duration); - dest.writeString(this.data); - dest.writeLong(this.dateModified); - dest.writeInt(this.albumId); - dest.writeString(this.albumName); - dest.writeInt(this.artistId); - dest.writeString(this.artistName); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/Song.kt b/app/src/main/java/code/name/monkey/retromusic/model/Song.kt new file mode 100644 index 00000000..fab260e2 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/model/Song.kt @@ -0,0 +1,79 @@ +package code.name.monkey.retromusic.model + +import android.os.Parcel +import android.os.Parcelable + + +open class Song : Parcelable { + val id: Int + val title: String? + val trackNumber: Int + val year: Int + val duration: Long + val data: String? + val dateModified: Long + val albumId: Int + val albumName: String? + val artistId: Int + val artistName: String? + + constructor(id: Int, title: String, trackNumber: Int, year: Int, duration: Long, data: String, dateModified: Long, albumId: Int, albumName: String, artistId: Int, artistName: String) { + this.id = id + this.title = title + this.trackNumber = trackNumber + this.year = year + this.duration = duration + this.data = data + this.dateModified = dateModified + this.albumId = albumId + this.albumName = albumName + this.artistId = artistId + this.artistName = artistName + } + + protected constructor(`in`: Parcel) { + this.id = `in`.readInt() + this.title = `in`.readString() + this.trackNumber = `in`.readInt() + this.year = `in`.readInt() + this.duration = `in`.readLong() + this.data = `in`.readString() + this.dateModified = `in`.readLong() + this.albumId = `in`.readInt() + this.albumName = `in`.readString() + this.artistId = `in`.readInt() + this.artistName = `in`.readString() + } + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeInt(this.id) + dest.writeString(this.title) + dest.writeInt(this.trackNumber) + dest.writeInt(this.year) + dest.writeLong(this.duration) + dest.writeString(this.data) + dest.writeLong(this.dateModified) + dest.writeInt(this.albumId) + dest.writeString(this.albumName) + dest.writeInt(this.artistId) + dest.writeString(this.artistName) + } + + companion object { + val EMPTY_SONG = Song(-1, "", -1, -1, -1, "", -1, -1, "", -1, "") + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(source: Parcel): Song { + return Song(source) + } + + override fun newArray(size: Int): Array { + return emptyArray() + } + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/HistoryPlaylist.java b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/HistoryPlaylist.java index ea748bc2..1ab5e0d7 100644 --- a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/HistoryPlaylist.java +++ b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/HistoryPlaylist.java @@ -37,7 +37,7 @@ public class HistoryPlaylist extends AbsSmartPlaylist { @NonNull @Override public Observable> getSongs(@NonNull Context context) { - return TopAndRecentlyPlayedTracksLoader.getRecentlyPlayedTracks(context); + return TopAndRecentlyPlayedTracksLoader.INSTANCE.getRecentlyPlayedTracks(context); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/LastAddedPlaylist.java b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/LastAddedPlaylist.java index ec8c5209..d4dd4c7c 100644 --- a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/LastAddedPlaylist.java +++ b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/LastAddedPlaylist.java @@ -38,7 +38,7 @@ public class LastAddedPlaylist extends AbsSmartPlaylist { @NonNull @Override public Observable> getSongs(@NonNull Context context) { - return LastAddedSongsLoader.getLastAddedSongs(context); + return LastAddedSongsLoader.INSTANCE.getLastAddedSongs(context); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/MyTopTracksPlaylist.java b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/MyTopTracksPlaylist.java index ee155ce4..18515d20 100644 --- a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/MyTopTracksPlaylist.java +++ b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/MyTopTracksPlaylist.java @@ -38,7 +38,7 @@ public class MyTopTracksPlaylist extends AbsSmartPlaylist implements Parcelable @NonNull @Override public Observable> getSongs(@NonNull Context context) { - return TopAndRecentlyPlayedTracksLoader.getTopTracks(context); + return TopAndRecentlyPlayedTracksLoader.INSTANCE.getTopTracks(context); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/ShuffleAllPlaylist.java b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/ShuffleAllPlaylist.java index ca4bcbbf..e4b752f0 100644 --- a/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/ShuffleAllPlaylist.java +++ b/app/src/main/java/code/name/monkey/retromusic/model/smartplaylist/ShuffleAllPlaylist.java @@ -37,7 +37,7 @@ public class ShuffleAllPlaylist extends AbsSmartPlaylist { @NonNull @Override public Observable> getSongs(@NonNull Context context) { - return SongLoader.Companion.getAllSongs(context); + return SongLoader.INSTANCE.getAllSongs(context); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.java index 5bc63f1c..59e52b04 100644 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.java +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.java @@ -20,8 +20,8 @@ public class Presenter { protected BaseSchedulerProvider schedulerProvider; public Presenter() { - this.repository = Injection.provideRepository(); - this.schedulerProvider = Injection.provideSchedulerProvider(); + this.repository = Injection.INSTANCE.provideRepository(); + this.schedulerProvider = Injection.INSTANCE.provideSchedulerProvider(); this.disposable = new CompositeDisposable(); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.java b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.java index e49bd8d2..6c68c8ca 100644 --- a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.java +++ b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.java @@ -5,10 +5,6 @@ import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.fragment.app.DialogFragment; -import androidx.viewpager.widget.PagerAdapter; -import androidx.viewpager.widget.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -20,6 +16,10 @@ import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.bumptech.glide.Glide; +import androidx.annotation.NonNull; +import androidx.fragment.app.DialogFragment; +import androidx.viewpager.widget.PagerAdapter; +import androidx.viewpager.widget.ViewPager; import code.name.monkey.retromusic.R; import code.name.monkey.retromusic.RetroApplication; import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen; @@ -83,12 +83,12 @@ public class NowPlayingScreenPreferenceDialog extends DialogFragment implements private boolean isNowPlayingThemes(NowPlayingScreen nowPlayingScreen) { - if (nowPlayingScreen.equals(NowPlayingScreen.BLUR_CARD)) { + /*if (nowPlayingScreen.equals(NowPlayingScreen.BLUR_CARD)) { PreferenceUtil.getInstance().resetCarouselEffect(); PreferenceUtil.getInstance().resetCircularAlbumArt(); - } + }*/ - return (nowPlayingScreen.equals(NowPlayingScreen.FULL) || + /* return (nowPlayingScreen.equals(NowPlayingScreen.FULL) || nowPlayingScreen.equals(NowPlayingScreen.CARD) || nowPlayingScreen.equals(NowPlayingScreen.PLAIN) || nowPlayingScreen.equals(NowPlayingScreen.BLUR) || @@ -97,7 +97,8 @@ public class NowPlayingScreenPreferenceDialog extends DialogFragment implements nowPlayingScreen.equals(NowPlayingScreen.TINY) || nowPlayingScreen.equals(NowPlayingScreen.BLUR_CARD)|| nowPlayingScreen.equals(NowPlayingScreen.ADAPTIVE)) - && !RetroApplication.isProVersion(); + && !RetroApplication.Companion.isProVersion();*/ + return !RetroApplication.Companion.isProVersion(); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/providers/BlacklistStore.java b/app/src/main/java/code/name/monkey/retromusic/providers/BlacklistStore.java index 66b4ea03..91fe2774 100644 --- a/app/src/main/java/code/name/monkey/retromusic/providers/BlacklistStore.java +++ b/app/src/main/java/code/name/monkey/retromusic/providers/BlacklistStore.java @@ -16,6 +16,8 @@ import code.name.monkey.retromusic.Constants; import code.name.monkey.retromusic.util.FileUtil; import code.name.monkey.retromusic.util.PreferenceUtil; +import static code.name.monkey.retromusic.Constants.MEDIA_STORE_CHANGED; + public class BlacklistStore extends SQLiteOpenHelper { public static final String DATABASE_NAME = "blacklist.db"; private static final int VERSION = 2; @@ -125,7 +127,7 @@ public class BlacklistStore extends SQLiteOpenHelper { } private void notifyMediaStoreChanged() { - context.sendBroadcast(new Intent(Constants.MEDIA_STORE_CHANGED)); + context.sendBroadcast(new Intent(MEDIA_STORE_CHANGED)); } @NonNull diff --git a/app/src/main/java/code/name/monkey/retromusic/providers/MusicPlaybackQueueStore.java b/app/src/main/java/code/name/monkey/retromusic/providers/MusicPlaybackQueueStore.java index dc9b61bd..ab8ce844 100644 --- a/app/src/main/java/code/name/monkey/retromusic/providers/MusicPlaybackQueueStore.java +++ b/app/src/main/java/code/name/monkey/retromusic/providers/MusicPlaybackQueueStore.java @@ -162,17 +162,17 @@ public class MusicPlaybackQueueStore extends SQLiteOpenHelper { Song song = queue.get(i); ContentValues values = new ContentValues(4); - values.put(BaseColumns._ID, song.id); - values.put(AudioColumns.TITLE, song.title); - values.put(AudioColumns.TRACK, song.trackNumber); - values.put(AudioColumns.YEAR, song.year); - values.put(AudioColumns.DURATION, song.duration); - values.put(AudioColumns.DATA, song.data); - values.put(AudioColumns.DATE_MODIFIED, song.dateModified); - values.put(AudioColumns.ALBUM_ID, song.albumId); - values.put(AudioColumns.ALBUM, song.albumName); - values.put(AudioColumns.ARTIST_ID, song.artistId); - values.put(AudioColumns.ARTIST, song.artistName); + values.put(BaseColumns._ID, song.getId()); + values.put(AudioColumns.TITLE, song.getTitle()); + values.put(AudioColumns.TRACK, song.getTrackNumber()); + values.put(AudioColumns.YEAR, song.getYear()); + values.put(AudioColumns.DURATION, song.getDuration()); + values.put(AudioColumns.DATA, song.getData()); + values.put(AudioColumns.DATE_MODIFIED, song.getDateModified()); + values.put(AudioColumns.ALBUM_ID, song.getAlbumId()); + values.put(AudioColumns.ALBUM, song.getAlbumName()); + values.put(AudioColumns.ARTIST_ID, song.getArtistId()); + values.put(AudioColumns.ARTIST, song.getArtistName()); database.insert(tableName, null, values); } @@ -198,6 +198,6 @@ public class MusicPlaybackQueueStore extends SQLiteOpenHelper { private Observable> getQueue(@NonNull final String tableName) { Cursor cursor = getReadableDatabase().query(tableName, null, null, null, null, null, null); - return SongLoader.Companion.getSongs(cursor); + return SongLoader.INSTANCE.getSongs(cursor); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/providers/RepositoryImpl.java b/app/src/main/java/code/name/monkey/retromusic/providers/RepositoryImpl.java index 42299eec..7deda91e 100644 --- a/app/src/main/java/code/name/monkey/retromusic/providers/RepositoryImpl.java +++ b/app/src/main/java/code/name/monkey/retromusic/providers/RepositoryImpl.java @@ -41,69 +41,69 @@ public class RepositoryImpl implements Repository { public static synchronized RepositoryImpl getInstance() { if (INSTANCE == null) { - INSTANCE = new RepositoryImpl(RetroApplication.getInstance()); + INSTANCE = new RepositoryImpl(RetroApplication.Companion.getInstance()); } return INSTANCE; } @Override public Observable> getAllSongs() { - return SongLoader.Companion.getAllSongs(context); + return SongLoader.INSTANCE.getAllSongs(context); } @Override public Observable> getSuggestionSongs() { - return SongLoader.Companion.suggestSongs(context); + return SongLoader.INSTANCE.suggestSongs(context); } @Override public Observable getSong(int id) { - return SongLoader.Companion.getSong(context, id); + return SongLoader.INSTANCE.getSong(context, id); } @Override public Observable> getAllAlbums() { - return AlbumLoader.getAllAlbums(context); + return AlbumLoader.Companion.getAllAlbums(context); } @Override public Observable> getRecentAlbums() { - return LastAddedSongsLoader.getLastAddedAlbums(context); + return LastAddedSongsLoader.INSTANCE.getLastAddedAlbums(context); } @Override public Observable> getTopAlbums() { - return TopAndRecentlyPlayedTracksLoader.getTopAlbums(context); + return TopAndRecentlyPlayedTracksLoader.INSTANCE.getTopAlbums(context); } @Override public Observable getAlbum(int albumId) { - return AlbumLoader.getAlbum(context, albumId); + return AlbumLoader.Companion.getAlbum(context, albumId); } @Override public Observable> getAllArtists() { - return ArtistLoader.getAllArtists(context); + return ArtistLoader.INSTANCE.getAllArtists(context); } @Override public Observable> getRecentArtists() { - return LastAddedSongsLoader.getLastAddedArtists(context); + return LastAddedSongsLoader.INSTANCE.getLastAddedArtists(context); } @Override public Observable> getTopArtists() { - return TopAndRecentlyPlayedTracksLoader.getTopArtists(context); + return TopAndRecentlyPlayedTracksLoader.INSTANCE.getTopArtists(context); } @Override public Observable getArtistById(long artistId) { - return ArtistLoader.getArtist(context, (int) artistId); + return ArtistLoader.INSTANCE.getArtist(context, (int) artistId); } @Override public Observable> getAllPlaylists() { - return PlaylistLoader.getAllPlaylists(context); + return PlaylistLoader.INSTANCE.getAllPlaylists(context); } @Override @@ -113,37 +113,37 @@ public class RepositoryImpl implements Repository { @Override public Observable> search(String query) { - return SearchLoader.searchAll(context, query); + return SearchLoader.INSTANCE.searchAll(context, query); } @Override public Observable> getPlaylistSongs(Playlist playlist) { - return PlaylistSongsLoader.getPlaylistSongList(context, playlist); + return PlaylistSongsLoader.INSTANCE.getPlaylistSongList(context, playlist); } @Override public Observable> getHomeList() { - return HomeLoader.getHomeLoader(context); + return HomeLoader.INSTANCE.getHomeLoader(context); } @Override public Observable> getAllThings() { - return HomeLoader.getRecentAndTopThings(context); + return HomeLoader.INSTANCE.getRecentAndTopThings(context); } @Override public Observable> getAllGenres() { - return GenreLoader.getAllGenres(context); + return GenreLoader.INSTANCE.getAllGenres(context); } @Override public Observable> getGenre(int genreId) { - return GenreLoader.getSongs(context, genreId); + return GenreLoader.INSTANCE.getSongs(context, genreId); } @Override public Observable downloadLrcFile(String title, String artist, long duration) { - KuGouApiService service = Injection.provideKuGouApiService(); + KuGouApiService service = Injection.INSTANCE.provideKuGouApiService(); return service.searchLyric(title, String.valueOf(duration)) .subscribeOn(Schedulers.io()) .flatMap(kuGouSearchLyricResult -> { diff --git a/app/src/main/java/code/name/monkey/retromusic/rest/KogouClient.java b/app/src/main/java/code/name/monkey/retromusic/rest/KogouClient.java index 23db6a19..fcf0c7cd 100644 --- a/app/src/main/java/code/name/monkey/retromusic/rest/KogouClient.java +++ b/app/src/main/java/code/name/monkey/retromusic/rest/KogouClient.java @@ -1,12 +1,13 @@ package code.name.monkey.retromusic.rest; import android.content.Context; + +import java.io.File; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import code.name.monkey.retromusic.Constants; import code.name.monkey.retromusic.RetroApplication; import code.name.monkey.retromusic.rest.service.KuGouApiService; -import java.io.File; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Interceptor; @@ -17,60 +18,62 @@ import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; +import static code.name.monkey.retromusic.Constants.BASE_API_URL_KUGOU; + /** * Created by hemanths on 23/08/17. */ public class KogouClient { - private static final String BASE_URL = Constants.BASE_API_URL_KUGOU; + private static final String BASE_URL = BASE_API_URL_KUGOU; - private KuGouApiService apiService; + private KuGouApiService apiService; - public KogouClient() { - this(createDefaultOkHttpClientBuilder().build()); - } - - private KogouClient(@NonNull Call.Factory client) { - Retrofit restAdapter = new Retrofit.Builder() - .baseUrl(BASE_URL) - .callFactory(client) - .addConverterFactory(GsonConverterFactory.create()) - .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) - .build(); - - apiService = restAdapter.create(KuGouApiService.class); - } - - @Nullable - private static Cache createDefaultCache(Context context) { - File cacheDir = new File(context.getCacheDir().getAbsolutePath(), "/okhttp-lastfm/"); - if (cacheDir.mkdirs() || cacheDir.isDirectory()) { - return new Cache(cacheDir, 1024 * 1024 * 10); + public KogouClient() { + this(createDefaultOkHttpClientBuilder().build()); } - return null; - } - private static Interceptor createCacheControlInterceptor() { - return chain -> { - Request modifiedRequest = chain.request().newBuilder() - .addHeader("Cache-Control", String.format("max-age=%d, max-stale=%d", 31536000, 31536000)) - .build(); - return chain.proceed(modifiedRequest); - }; - } + private KogouClient(@NonNull Call.Factory client) { + Retrofit restAdapter = new Retrofit.Builder() + .baseUrl(BASE_URL) + .callFactory(client) + .addConverterFactory(GsonConverterFactory.create()) + .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) + .build(); - private static OkHttpClient.Builder createDefaultOkHttpClientBuilder() { - HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); - interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); + apiService = restAdapter.create(KuGouApiService.class); + } - return new OkHttpClient.Builder() - .addInterceptor(interceptor) - .cache(createDefaultCache(RetroApplication.getInstance())) - .addInterceptor(createCacheControlInterceptor()); - } + @Nullable + private static Cache createDefaultCache(Context context) { + File cacheDir = new File(context.getCacheDir().getAbsolutePath(), "/okhttp-lastfm/"); + if (cacheDir.mkdirs() || cacheDir.isDirectory()) { + return new Cache(cacheDir, 1024 * 1024 * 10); + } + return null; + } - public KuGouApiService getApiService() { - return apiService; - } + private static Interceptor createCacheControlInterceptor() { + return chain -> { + Request modifiedRequest = chain.request().newBuilder() + .addHeader("Cache-Control", String.format("max-age=%d, max-stale=%d", 31536000, 31536000)) + .build(); + return chain.proceed(modifiedRequest); + }; + } + + private static OkHttpClient.Builder createDefaultOkHttpClientBuilder() { + HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); + interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); + + return new OkHttpClient.Builder() + .addInterceptor(interceptor) + .cache(createDefaultCache(RetroApplication.Companion.getInstance())) + .addInterceptor(createCacheControlInterceptor()); + } + + public KuGouApiService getApiService() { + return apiService; + } } diff --git a/app/src/main/java/code/name/monkey/retromusic/service/MediaButtonIntentReceiver.java b/app/src/main/java/code/name/monkey/retromusic/service/MediaButtonIntentReceiver.java deleted file mode 100644 index a728e7b4..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/MediaButtonIntentReceiver.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source 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. - */ - -// Modified for Phonograph by Karim Abou Zeid (kabouzeid). - -package code.name.monkey.retromusic.service; - -import android.annotation.SuppressLint; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.os.Build; -import android.os.Handler; -import android.os.Message; -import android.os.PowerManager; -import android.os.PowerManager.WakeLock; -import android.util.Log; -import android.view.KeyEvent; - -import code.name.monkey.retromusic.BuildConfig; - -import static code.name.monkey.retromusic.Constants.ACTION_PAUSE; -import static code.name.monkey.retromusic.Constants.ACTION_PLAY; -import static code.name.monkey.retromusic.Constants.ACTION_REWIND; -import static code.name.monkey.retromusic.Constants.ACTION_SKIP; -import static code.name.monkey.retromusic.Constants.ACTION_STOP; -import static code.name.monkey.retromusic.Constants.ACTION_TOGGLE_PAUSE; - -/** - * Used to control headset playback. - * Single press: pause/resume - * Double press: next track - * Triple press: previous track - */ -public class MediaButtonIntentReceiver extends BroadcastReceiver { - public static final String TAG = MediaButtonIntentReceiver.class.getSimpleName(); - private static final boolean DEBUG = BuildConfig.DEBUG; - private static final int MSG_HEADSET_DOUBLE_CLICK_TIMEOUT = 2; - - private static final int DOUBLE_CLICK = 400; - - private static WakeLock mWakeLock = null; - private static int mClickCounter = 0; - private static long mLastClickTime = 0; - - @SuppressLint("HandlerLeak") // false alarm, handler is already static - private static Handler mHandler = new Handler() { - - @Override - public void handleMessage(final Message msg) { - switch (msg.what) { - case MSG_HEADSET_DOUBLE_CLICK_TIMEOUT: - final int clickCount = msg.arg1; - final String command; - - if (DEBUG) Log.v(TAG, "Handling headset click, count = " + clickCount); - switch (clickCount) { - case 1: - command = ACTION_TOGGLE_PAUSE; - break; - case 2: - command = ACTION_SKIP; - break; - case 3: - command = ACTION_REWIND; - break; - default: - command = null; - break; - } - - if (command != null) { - final Context context = (Context) msg.obj; - startService(context, command); - } - break; - } - releaseWakeLockIfHandlerIdle(); - } - }; - - public static boolean handleIntent(final Context context, final Intent intent) { - final String intentAction = intent.getAction(); - if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) { - final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); - if (event == null) { - return false; - } - - final int keycode = event.getKeyCode(); - final int action = event.getAction(); - final long eventTime = event.getEventTime() != 0 ? - event.getEventTime() : System.currentTimeMillis(); - - String command = null; - switch (keycode) { - case KeyEvent.KEYCODE_MEDIA_STOP: - command = ACTION_STOP; - break; - case KeyEvent.KEYCODE_HEADSETHOOK: - case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: - command = ACTION_TOGGLE_PAUSE; - break; - case KeyEvent.KEYCODE_MEDIA_NEXT: - command = ACTION_SKIP; - break; - case KeyEvent.KEYCODE_MEDIA_PREVIOUS: - command = ACTION_REWIND; - break; - case KeyEvent.KEYCODE_MEDIA_PAUSE: - command = ACTION_PAUSE; - break; - case KeyEvent.KEYCODE_MEDIA_PLAY: - command = ACTION_PLAY; - break; - } - if (command != null) { - if (action == KeyEvent.ACTION_DOWN) { - if (event.getRepeatCount() == 0) { - // Only consider the first event in a sequence, not the repeat events, - // so that we don't trigger in cases where the first event went to - // a different app (e.g. when the user ends a phone call by - // long pressing the headset button) - - // The service may or may not be running, but we need to send it - // a command. - if (keycode == KeyEvent.KEYCODE_HEADSETHOOK || keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) { - if (eventTime - mLastClickTime >= DOUBLE_CLICK) { - mClickCounter = 0; - } - - mClickCounter++; - if (DEBUG) Log.v(TAG, "Got headset click, count = " + mClickCounter); - mHandler.removeMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT); - - Message msg = mHandler.obtainMessage( - MSG_HEADSET_DOUBLE_CLICK_TIMEOUT, mClickCounter, 0, context); - - long delay = mClickCounter < 3 ? DOUBLE_CLICK : 0; - if (mClickCounter >= 3) { - mClickCounter = 0; - } - mLastClickTime = eventTime; - acquireWakeLockAndSendMessage(context, msg, delay); - } else { - startService(context, command); - } - return true; - } - } - } - } - return false; - } - - private static void startService(Context context, String command) { - final Intent intent = new Intent(context, MusicService.class); - intent.setAction(command); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - context.startForegroundService(intent); - } else { - context.startService(intent); - } - } - - private static void acquireWakeLockAndSendMessage(Context context, Message msg, long delay) { - if (mWakeLock == null) { - Context appContext = context.getApplicationContext(); - PowerManager pm = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE); - if (pm != null) { - mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, - "RetroMusicApp:Wakelock headset button"); - } - mWakeLock.setReferenceCounted(false); - } - if (DEBUG) Log.v(TAG, "Acquiring wake lock and sending " + msg.what); - // Make sure we don't indefinitely hold the wake lock under any circumstances - mWakeLock.acquire(10000); - - mHandler.sendMessageDelayed(msg, delay); - } - - private static void releaseWakeLockIfHandlerIdle() { - if (mHandler.hasMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT)) { - if (DEBUG) Log.v(TAG, "Handler still has messages pending, not releasing wake lock"); - return; - } - - if (mWakeLock != null) { - if (DEBUG) Log.v(TAG, "Releasing wake lock"); - mWakeLock.release(); - mWakeLock = null; - } - } - - @Override - public void onReceive(final Context context, final Intent intent) { - if (DEBUG) Log.v(TAG, "Received intent: " + intent); - if (handleIntent(context, intent) && isOrderedBroadcast()) { - abortBroadcast(); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/MediaButtonIntentReceiver.kt b/app/src/main/java/code/name/monkey/retromusic/service/MediaButtonIntentReceiver.kt new file mode 100644 index 00000000..c4093384 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/MediaButtonIntentReceiver.kt @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2007 The Android Open Source 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 code.name.monkey.retromusic.service + +import android.annotation.SuppressLint +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Handler +import android.os.Message +import android.os.PowerManager +import android.os.PowerManager.WakeLock +import android.util.Log +import android.view.KeyEvent + +import code.name.monkey.retromusic.BuildConfig +import code.name.monkey.retromusic.Constants.ACTION_PAUSE +import code.name.monkey.retromusic.Constants.ACTION_PLAY +import code.name.monkey.retromusic.Constants.ACTION_REWIND +import code.name.monkey.retromusic.Constants.ACTION_SKIP +import code.name.monkey.retromusic.Constants.ACTION_STOP +import code.name.monkey.retromusic.Constants.ACTION_TOGGLE_PAUSE + +/** + * Used to control headset playback. + * Single press: pause/resume + * Double press: actionNext track + * Triple press: previous track + */ +class MediaButtonIntentReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + if (DEBUG) Log.v(TAG, "Received intent: $intent") + if (handleIntent(context, intent) && isOrderedBroadcast) { + abortBroadcast() + } + } + + companion object { + val TAG = MediaButtonIntentReceiver::class.java.simpleName + private val DEBUG = BuildConfig.DEBUG + private val MSG_HEADSET_DOUBLE_CLICK_TIMEOUT = 2 + + private val DOUBLE_CLICK = 400 + + private var wakeLock: WakeLock? = null + private var mClickCounter = 0 + private var mLastClickTime: Long = 0 + + @SuppressLint("HandlerLeak") // false alarm, handler is already static + private val mHandler = object : Handler() { + + override fun handleMessage(msg: Message) { + when (msg.what) { + MSG_HEADSET_DOUBLE_CLICK_TIMEOUT -> { + val clickCount = msg.arg1 + val command: String? + + if (DEBUG) Log.v(TAG, "Handling headset click, count = $clickCount") + when (clickCount) { + 1 -> command = ACTION_TOGGLE_PAUSE + 2 -> command = ACTION_SKIP + 3 -> command = ACTION_REWIND + else -> command = null + } + + if (command != null) { + val context = msg.obj as Context + startService(context, command) + } + } + } + releaseWakeLockIfHandlerIdle() + } + } + + fun handleIntent(context: Context, intent: Intent): Boolean { + val intentAction = intent.action + if (Intent.ACTION_MEDIA_BUTTON == intentAction) { + val event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT) + ?: return false + + val keycode = event.keyCode + val action = event.action + val eventTime = if (event.eventTime != 0L) + event.eventTime + else + System.currentTimeMillis() + + var command: String? = null + when (keycode) { + KeyEvent.KEYCODE_MEDIA_STOP -> command = ACTION_STOP + KeyEvent.KEYCODE_HEADSETHOOK, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> command = ACTION_TOGGLE_PAUSE + KeyEvent.KEYCODE_MEDIA_NEXT -> command = ACTION_SKIP + KeyEvent.KEYCODE_MEDIA_PREVIOUS -> command = ACTION_REWIND + KeyEvent.KEYCODE_MEDIA_PAUSE -> command = ACTION_PAUSE + KeyEvent.KEYCODE_MEDIA_PLAY -> command = ACTION_PLAY + } + if (command != null) { + if (action == KeyEvent.ACTION_DOWN) { + if (event.repeatCount == 0) { + // Only consider the first event in a sequence, not the repeat events, + // so that we don't trigger in cases where the first event went to + // a different app (e.g. when the user ends a phone call by + // long pressing the headset button) + + // The service may or may not be running, but we need to send it + // a command. + if (keycode == KeyEvent.KEYCODE_HEADSETHOOK || keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) { + if (eventTime - mLastClickTime >= DOUBLE_CLICK) { + mClickCounter = 0 + } + + mClickCounter++ + if (DEBUG) Log.v(TAG, "Got headset click, count = $mClickCounter") + mHandler.removeMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT) + + val msg = mHandler.obtainMessage( + MSG_HEADSET_DOUBLE_CLICK_TIMEOUT, mClickCounter, 0, context) + + val delay = (if (mClickCounter < 3) DOUBLE_CLICK else 0).toLong() + if (mClickCounter >= 3) { + mClickCounter = 0 + } + mLastClickTime = eventTime + acquireWakeLockAndSendMessage(context, msg, delay) + } else { + startService(context, command) + } + return true + } + } + } + } + return false + } + + private fun startService(context: Context, command: String?) { + val intent = Intent(context, MusicService::class.java) + intent.action = command + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + } + + private fun acquireWakeLockAndSendMessage(context: Context, msg: Message, delay: Long) { + if (wakeLock == null) { + val appContext = context.applicationContext + val pm = appContext.getSystemService(Context.POWER_SERVICE) as PowerManager + wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RetroMusicApp:Wakelock headset button") + wakeLock!!.setReferenceCounted(false) + } + if (DEBUG) Log.v(TAG, "Acquiring wake lock and sending " + msg.what) + // Make sure we don't indefinitely hold the wake lock under any circumstances + wakeLock!!.acquire(10000) + + mHandler.sendMessageDelayed(msg, delay) + } + + private fun releaseWakeLockIfHandlerIdle() { + if (mHandler.hasMessages(MSG_HEADSET_DOUBLE_CLICK_TIMEOUT)) { + if (DEBUG) Log.v(TAG, "Handler still has messages pending, not releasing wake lock") + return + } + + if (wakeLock != null) { + if (DEBUG) Log.v(TAG, "Releasing wake lock") + wakeLock!!.release() + wakeLock = null + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/MultiPlayer.java b/app/src/main/java/code/name/monkey/retromusic/service/MultiPlayer.java deleted file mode 100644 index d725f40b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/MultiPlayer.java +++ /dev/null @@ -1,334 +0,0 @@ -package code.name.monkey.retromusic.service; - -import android.content.Context; -import android.content.Intent; -import android.media.AudioManager; -import android.media.MediaPlayer; -import android.media.audiofx.AudioEffect; -import android.net.Uri; -import android.os.PowerManager; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import android.util.Log; -import android.widget.Toast; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.service.playback.Playback; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Andrew Neal, Karim Abou Zeid (kabouzeid) - */ -public class MultiPlayer implements Playback, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { - public static final String TAG = MultiPlayer.class.getSimpleName(); - - private MediaPlayer mCurrentMediaPlayer = new MediaPlayer(); - private MediaPlayer mNextMediaPlayer; - - private Context context; - @Nullable - private Playback.PlaybackCallbacks callbacks; - - private boolean mIsInitialized = false; - - /** - * Constructor of MultiPlayer - */ - MultiPlayer(final Context context) { - this.context = context; - mCurrentMediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); - } - - /** - * @param path The path of the file, or the http/rtsp URL of the stream - * you want to play - * @return True if the player has been prepared and is - * ready to play, false otherwise - */ - @Override - public boolean setDataSource(@NonNull final String path) { - mIsInitialized = false; - mIsInitialized = setDataSourceImpl(mCurrentMediaPlayer, path); - if (mIsInitialized) { - setNextDataSource(null); - } - return mIsInitialized; - } - - /** - * @param player The {@link MediaPlayer} to use - * @param path The path of the file, or the http/rtsp URL of the stream - * you want to play - * @return True if the player has been prepared and is - * ready to play, false otherwise - */ - private boolean setDataSourceImpl(@NonNull final MediaPlayer player, @NonNull final String path) { - if (context == null) { - return false; - } - try { - player.reset(); - player.setOnPreparedListener(null); - if (path.startsWith("content://")) { - player.setDataSource(context, Uri.parse(path)); - } else { - player.setDataSource(path); - } - player.setAudioStreamType(AudioManager.STREAM_MUSIC); - player.prepare(); - } catch (Exception e) { - return false; - } - player.setOnCompletionListener(this); - player.setOnErrorListener(this); - final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); - intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); - intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName()); - intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC); - context.sendBroadcast(intent); - return true; - } - - /** - * Set the MediaPlayer to start when this MediaPlayer finishes playback. - * - * @param path The path of the file, or the http/rtsp URL of the stream - * you want to play - */ - @Override - public void setNextDataSource(@Nullable final String path) { - if (context == null) { - return; - } - try { - mCurrentMediaPlayer.setNextMediaPlayer(null); - } catch (IllegalArgumentException e) { - Log.i(TAG, "Next media player is current one, continuing"); - } catch (IllegalStateException e) { - Log.e(TAG, "Media player not initialized!"); - return; - } - if (mNextMediaPlayer != null) { - mNextMediaPlayer.release(); - mNextMediaPlayer = null; - } - if (path == null) { - return; - } - if (PreferenceUtil.getInstance().gaplessPlayback()) { - mNextMediaPlayer = new MediaPlayer(); - mNextMediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); - mNextMediaPlayer.setAudioSessionId(getAudioSessionId()); - if (setDataSourceImpl(mNextMediaPlayer, path)) { - try { - mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer); - } catch (@NonNull IllegalArgumentException | IllegalStateException e) { - Log.e(TAG, "setNextDataSource: setNextMediaPlayer()", e); - if (mNextMediaPlayer != null) { - mNextMediaPlayer.release(); - mNextMediaPlayer = null; - } - } - } else { - if (mNextMediaPlayer != null) { - mNextMediaPlayer.release(); - mNextMediaPlayer = null; - } - } - } - } - - /** - * Sets the callbacks - * - * @param callbacks The callbacks to use - */ - @Override - public void setCallbacks(@Nullable final Playback.PlaybackCallbacks callbacks) { - this.callbacks = callbacks; - } - - /** - * @return True if the player is ready to go, false otherwise - */ - @Override - public boolean isInitialized() { - return mIsInitialized; - } - - /** - * Starts or resumes playback. - */ - @Override - public boolean start() { - try { - mCurrentMediaPlayer.start(); - return true; - } catch (IllegalStateException e) { - return false; - } - } - - /** - * Resets the MediaPlayer to its uninitialized state. - */ - @Override - public void stop() { - mCurrentMediaPlayer.reset(); - mIsInitialized = false; - } - - /** - * Releases resources associated with this MediaPlayer object. - */ - @Override - public void release() { - stop(); - mCurrentMediaPlayer.release(); - if (mNextMediaPlayer != null) { - mNextMediaPlayer.release(); - } - } - - /** - * Pauses playback. Call start() to resume. - */ - @Override - public boolean pause() { - try { - mCurrentMediaPlayer.pause(); - return true; - } catch (IllegalStateException e) { - return false; - } - } - - /** - * Checks whether the MultiPlayer is playing. - */ - @Override - public boolean isPlaying() { - return mIsInitialized && mCurrentMediaPlayer.isPlaying(); - } - - /** - * Gets the duration of the file. - * - * @return The duration in milliseconds - */ - @Override - public int duration() { - if (!mIsInitialized) { - return -1; - } - try { - return mCurrentMediaPlayer.getDuration(); - } catch (IllegalStateException e) { - return -1; - } - } - - /** - * Gets the current playback position. - * - * @return The current position in milliseconds - */ - @Override - public int position() { - if (!mIsInitialized) { - return -1; - } - try { - return mCurrentMediaPlayer.getCurrentPosition(); - } catch (IllegalStateException e) { - return -1; - } - } - - /** - * Gets the current playback position. - * - * @param whereto The offset in milliseconds from the start to seek to - * @return The offset in milliseconds from the start to seek to - */ - @Override - public int seek(final int whereto) { - try { - mCurrentMediaPlayer.seekTo(whereto); - return whereto; - } catch (IllegalStateException e) { - return -1; - } - } - - @Override - public boolean setVolume(final float vol) { - try { - mCurrentMediaPlayer.setVolume(vol, vol); - return true; - } catch (IllegalStateException e) { - return false; - } - } - - /** - * Sets the audio session ID. - * - * @param sessionId The audio session ID - */ - @Override - public boolean setAudioSessionId(final int sessionId) { - try { - mCurrentMediaPlayer.setAudioSessionId(sessionId); - return true; - } catch (@NonNull IllegalArgumentException | IllegalStateException e) { - return false; - } - } - - /** - * Returns the audio session ID. - * - * @return The current audio session ID. - */ - @Override - public int getAudioSessionId() { - return mCurrentMediaPlayer.getAudioSessionId(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean onError(final MediaPlayer mp, final int what, final int extra) { - mIsInitialized = false; - mCurrentMediaPlayer.release(); - mCurrentMediaPlayer = new MediaPlayer(); - mCurrentMediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); - if (context != null) { - Toast.makeText(context, context.getResources().getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show(); - } - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void onCompletion(final MediaPlayer mp) { - if (mp == mCurrentMediaPlayer && mNextMediaPlayer != null) { - mIsInitialized = false; - mCurrentMediaPlayer.release(); - mCurrentMediaPlayer = mNextMediaPlayer; - mIsInitialized = true; - mNextMediaPlayer = null; - if (callbacks != null) - callbacks.onTrackWentToNext(); - } else { - if (callbacks != null) - callbacks.onTrackEnded(); - } - } - - -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/MultiPlayer.kt b/app/src/main/java/code/name/monkey/retromusic/service/MultiPlayer.kt new file mode 100644 index 00000000..ba24b958 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/MultiPlayer.kt @@ -0,0 +1,333 @@ +package code.name.monkey.retromusic.service + +import android.content.Context +import android.content.Intent +import android.media.AudioManager +import android.media.MediaPlayer +import android.media.audiofx.AudioEffect +import android.net.Uri +import android.os.PowerManager +import android.util.Log +import android.widget.Toast + +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.service.playback.Playback +import code.name.monkey.retromusic.util.PreferenceUtil + +/** + * @author Andrew Neal, Karim Abou Zeid (kabouzeid) + */ +class MultiPlayer +/** + * Constructor of `MultiPlayer` + */ +internal constructor(private val context: Context?) : Playback, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { + + private var mCurrentMediaPlayer = MediaPlayer() + private var mNextMediaPlayer: MediaPlayer? = null + private var callbacks: Playback.PlaybackCallbacks? = null + + private var mIsInitialized = false + + init { + mCurrentMediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK) + } + + /** + * @param path The path of the file, or the http/rtsp URL of the stream + * you want to play + * @return True if the `player` has been prepared and is + * ready to play, false otherwise + */ + override fun setDataSource(path: String): Boolean { + mIsInitialized = false + mIsInitialized = setDataSourceImpl(mCurrentMediaPlayer, path) + if (mIsInitialized) { + setNextDataSource(null) + } + return mIsInitialized + } + + /** + * @param player The [MediaPlayer] to use + * @param path The path of the file, or the http/rtsp URL of the stream + * you want to play + * @return True if the `player` has been prepared and is + * ready to play, false otherwise + */ + private fun setDataSourceImpl(player: MediaPlayer, path: String): Boolean { + if (context == null) { + return false + } + try { + player.reset() + player.setOnPreparedListener(null) + if (path.startsWith("content://")) { + player.setDataSource(context, Uri.parse(path)) + } else { + player.setDataSource(path) + } + player.setAudioStreamType(AudioManager.STREAM_MUSIC) + player.prepare() + } catch (e: Exception) { + return false + } + + player.setOnCompletionListener(this) + player.setOnErrorListener(this) + val intent = Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION) + intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId) + intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.packageName) + intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC) + context.sendBroadcast(intent) + return true + } + + /** + * Set the MediaPlayer to start when this MediaPlayer finishes playback. + * + * @param path The path of the file, or the http/rtsp URL of the stream + * you want to play + */ + override fun setNextDataSource(path: String?) { + if (context == null) { + return + } + try { + mCurrentMediaPlayer.setNextMediaPlayer(null) + } catch (e: IllegalArgumentException) { + Log.i(TAG, "Next media player is current one, continuing") + } catch (e: IllegalStateException) { + Log.e(TAG, "Media player not initialized!") + return + } + + if (mNextMediaPlayer != null) { + mNextMediaPlayer!!.release() + mNextMediaPlayer = null + } + if (path == null) { + return + } + if (PreferenceUtil.getInstance().gaplessPlayback()) { + mNextMediaPlayer = MediaPlayer() + mNextMediaPlayer!!.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK) + mNextMediaPlayer!!.audioSessionId = audioSessionId + if (setDataSourceImpl(mNextMediaPlayer!!, path)) { + try { + mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer) + } catch (e: IllegalArgumentException) { + Log.e(TAG, "setNextDataSource: setNextMediaPlayer()", e) + if (mNextMediaPlayer != null) { + mNextMediaPlayer!!.release() + mNextMediaPlayer = null + } + } catch (e: IllegalStateException) { + Log.e(TAG, "setNextDataSource: setNextMediaPlayer()", e) + if (mNextMediaPlayer != null) { + mNextMediaPlayer!!.release() + mNextMediaPlayer = null + } + } + + } else { + if (mNextMediaPlayer != null) { + mNextMediaPlayer!!.release() + mNextMediaPlayer = null + } + } + } + } + + /** + * Sets the callbacks + * + * @param callbacks The callbacks to use + */ + override fun setCallbacks(callbacks: Playback.PlaybackCallbacks?) { + this.callbacks = callbacks + } + + /** + * @return True if the player is ready to go, false otherwise + */ + override fun isInitialized(): Boolean { + return mIsInitialized + } + + /** + * Starts or resumes playback. + */ + override fun start(): Boolean { + try { + mCurrentMediaPlayer.start() + return true + } catch (e: IllegalStateException) { + return false + } + + } + + /** + * Resets the MediaPlayer to its uninitialized state. + */ + override fun stop() { + mCurrentMediaPlayer.reset() + mIsInitialized = false + } + + /** + * Releases resources associated with this MediaPlayer object. + */ + override fun release() { + stop() + mCurrentMediaPlayer.release() + if (mNextMediaPlayer != null) { + mNextMediaPlayer!!.release() + } + } + + /** + * Pauses playback. Call start() to resume. + */ + override fun pause(): Boolean { + try { + mCurrentMediaPlayer.pause() + return true + } catch (e: IllegalStateException) { + return false + } + + } + + /** + * Checks whether the MultiPlayer is playing. + */ + override fun isPlaying(): Boolean { + return mIsInitialized && mCurrentMediaPlayer.isPlaying + } + + /** + * Gets the duration of the file. + * + * @return The duration in milliseconds + */ + override fun duration(): Int { + if (!mIsInitialized) { + return -1 + } + try { + return mCurrentMediaPlayer.duration + } catch (e: IllegalStateException) { + return -1 + } + + } + + /** + * Gets the current playback position. + * + * @return The current position in milliseconds + */ + override fun position(): Int { + if (!mIsInitialized) { + return -1 + } + try { + return mCurrentMediaPlayer.currentPosition + } catch (e: IllegalStateException) { + return -1 + } + + } + + /** + * Gets the current playback position. + * + * @param whereto The offset in milliseconds from the start to seek to + * @return The offset in milliseconds from the start to seek to + */ + override fun seek(whereto: Int): Int { + try { + mCurrentMediaPlayer.seekTo(whereto) + return whereto + } catch (e: IllegalStateException) { + return -1 + } + + } + + override fun setVolume(vol: Float): Boolean { + try { + mCurrentMediaPlayer.setVolume(vol, vol) + return true + } catch (e: IllegalStateException) { + return false + } + + } + + /** + * Sets the audio session ID. + * + * @param sessionId The audio session ID + */ + override fun setAudioSessionId(sessionId: Int): Boolean { + try { + mCurrentMediaPlayer.audioSessionId = sessionId + return true + } catch (e: IllegalArgumentException) { + return false + } catch (e: IllegalStateException) { + return false + } + + } + + /** + * Returns the audio session ID. + * + * @return The current audio session ID. + */ + override fun getAudioSessionId(): Int { + return mCurrentMediaPlayer.audioSessionId + } + + /** + * {@inheritDoc} + */ + override fun onError(mp: MediaPlayer, what: Int, extra: Int): Boolean { + mIsInitialized = false + mCurrentMediaPlayer.release() + mCurrentMediaPlayer = MediaPlayer() + mCurrentMediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK) + if (context != null) { + Toast.makeText(context, context.resources.getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show() + } + return false + } + + /** + * {@inheritDoc} + */ + override fun onCompletion(mp: MediaPlayer) { + if (mp === mCurrentMediaPlayer && mNextMediaPlayer != null) { + mIsInitialized = false + mCurrentMediaPlayer.release() + mCurrentMediaPlayer = mNextMediaPlayer as MediaPlayer + mIsInitialized = true + mNextMediaPlayer = null + if (callbacks != null) + callbacks!!.onTrackWentToNext() + } else { + if (callbacks != null) + callbacks!!.onTrackEnded() + } + } + + companion object { + val TAG: String = MultiPlayer::class.java.simpleName + } + + +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/MusicService.java b/app/src/main/java/code/name/monkey/retromusic/service/MusicService.java deleted file mode 100644 index 72326e0a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/MusicService.java +++ /dev/null @@ -1,1445 +0,0 @@ -package code.name.monkey.retromusic.service; - -import android.app.PendingIntent; -import android.app.Service; -import android.appwidget.AppWidgetManager; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.database.ContentObserver; -import android.graphics.Bitmap; -import android.graphics.Point; -import android.graphics.drawable.Drawable; -import android.media.AudioManager; -import android.media.audiofx.AudioEffect; -import android.media.session.MediaSession; -import android.os.Binder; -import android.os.Build; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.IBinder; -import android.os.Looper; -import android.os.Message; -import android.os.PowerManager; -import android.os.Process; -import android.preference.PreferenceManager; -import android.provider.MediaStore; -import android.support.v4.media.MediaMetadataCompat; -import android.support.v4.media.session.MediaSessionCompat; -import android.support.v4.media.session.PlaybackStateCompat; -import android.telephony.PhoneStateListener; -import android.telephony.TelephonyManager; -import android.util.Log; -import android.widget.Toast; - -import com.bumptech.glide.BitmapRequestBuilder; -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appwidgets.AppWidgetBig; -import code.name.monkey.retromusic.appwidgets.AppWidgetCard; -import code.name.monkey.retromusic.appwidgets.AppWidgetClassic; -import code.name.monkey.retromusic.appwidgets.AppWidgetSmall; -import code.name.monkey.retromusic.glide.BlurTransformation; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.ShuffleHelper; -import code.name.monkey.retromusic.helper.StopWatch; -import code.name.monkey.retromusic.loaders.PlaylistSongsLoader; -import code.name.monkey.retromusic.model.AbsCustomPlaylist; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.providers.HistoryStore; -import code.name.monkey.retromusic.providers.MusicPlaybackQueueStore; -import code.name.monkey.retromusic.providers.SongPlayCountStore; -import code.name.monkey.retromusic.service.notification.PlayingNotification; -import code.name.monkey.retromusic.service.notification.PlayingNotificationImpl24; -import code.name.monkey.retromusic.service.notification.PlayingNotificationOreo; -import code.name.monkey.retromusic.service.playback.Playback; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; - -import static code.name.monkey.retromusic.Constants.ACTION_PAUSE; -import static code.name.monkey.retromusic.Constants.ACTION_PLAY; -import static code.name.monkey.retromusic.Constants.ACTION_PLAY_PLAYLIST; -import static code.name.monkey.retromusic.Constants.ACTION_QUIT; -import static code.name.monkey.retromusic.Constants.ACTION_REWIND; -import static code.name.monkey.retromusic.Constants.ACTION_SKIP; -import static code.name.monkey.retromusic.Constants.ACTION_STOP; -import static code.name.monkey.retromusic.Constants.ACTION_TOGGLE_PAUSE; -import static code.name.monkey.retromusic.Constants.APP_WIDGET_UPDATE; -import static code.name.monkey.retromusic.Constants.EXTRA_APP_WIDGET_NAME; -import static code.name.monkey.retromusic.Constants.INTENT_EXTRA_PLAYLIST; -import static code.name.monkey.retromusic.Constants.INTENT_EXTRA_SHUFFLE_MODE; -import static code.name.monkey.retromusic.Constants.MEDIA_STORE_CHANGED; -import static code.name.monkey.retromusic.Constants.META_CHANGED; -import static code.name.monkey.retromusic.Constants.MUSIC_PACKAGE_NAME; -import static code.name.monkey.retromusic.Constants.PLAY_STATE_CHANGED; -import static code.name.monkey.retromusic.Constants.QUEUE_CHANGED; -import static code.name.monkey.retromusic.Constants.REPEAT_MODE_CHANGED; -import static code.name.monkey.retromusic.Constants.RETRO_MUSIC_PACKAGE_NAME; -import static code.name.monkey.retromusic.Constants.SHUFFLE_MODE_CHANGED; - -/** - * @author Karim Abou Zeid (kabouzeid), Andrew Neal - */ -public class MusicService extends Service implements SharedPreferences.OnSharedPreferenceChangeListener, Playback.PlaybackCallbacks { - public static final String TAG = MusicService.class.getSimpleName(); - - public static final String SAVED_POSITION = "POSITION"; - public static final String SAVED_POSITION_IN_TRACK = "POSITION_IN_TRACK"; - public static final String SAVED_SHUFFLE_MODE = "SHUFFLE_MODE"; - public static final String SAVED_REPEAT_MODE = "REPEAT_MODE"; - - public static final int RELEASE_WAKELOCK = 0; - public static final int TRACK_ENDED = 1; - public static final int TRACK_WENT_TO_NEXT = 2; - public static final int PLAY_SONG = 3; - public static final int PREPARE_NEXT = 4; - public static final int SET_POSITION = 5; - public static final int RESTORE_QUEUES = 9; - public static final int SHUFFLE_MODE_NONE = 0; - public static final int SHUFFLE_MODE_SHUFFLE = 1; - public static final int REPEAT_MODE_NONE = 0; - public static final int REPEAT_MODE_ALL = 1; - public static final int REPEAT_MODE_THIS = 2; - public static final int SAVE_QUEUES = 0; - private static final int FOCUS_CHANGE = 6; - private static final int DUCK = 7; - private static final int UNDUCK = 8; - private static final long MEDIA_SESSION_ACTIONS = PlaybackStateCompat.ACTION_PLAY - | PlaybackStateCompat.ACTION_PAUSE - | PlaybackStateCompat.ACTION_PLAY_PAUSE - | PlaybackStateCompat.ACTION_SKIP_TO_NEXT - | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS - | PlaybackStateCompat.ACTION_STOP - | PlaybackStateCompat.ACTION_SEEK_TO; - private final IBinder musicBind = new MusicBinder(); - private AppWidgetBig appWidgetBig = AppWidgetBig.getInstance(); - private AppWidgetClassic appWidgetClassic = AppWidgetClassic.getInstance(); - private AppWidgetSmall appWidgetSmall = AppWidgetSmall.getInstance(); - private AppWidgetCard appWidgetCard = AppWidgetCard.getInstance(); - private Playback playback; - private ArrayList playingQueue = new ArrayList<>(); - private ArrayList originalPlayingQueue = new ArrayList<>(); - private int position = -1; - private int nextPosition = -1; - private int shuffleMode; - private int repeatMode; - private boolean queuesRestored; - private boolean pausedByTransientLossOfFocus; - private final BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, @NonNull Intent intent) { - if (intent.getAction() != null && intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { - pause(); - } - } - }; - private PlayingNotification playingNotification; - private AudioManager audioManager; - @SuppressWarnings("deprecation") - private MediaSessionCompat mediaSession; - private PowerManager.WakeLock wakeLock; - private PlaybackHandler playerHandler; - private final AudioManager.OnAudioFocusChangeListener audioFocusListener = new AudioManager.OnAudioFocusChangeListener() { - @Override - public void onAudioFocusChange(final int focusChange) { - playerHandler.obtainMessage(FOCUS_CHANGE, focusChange, 0).sendToTarget(); - } - }; - private QueueSaveHandler queueSaveHandler; - private HandlerThread musicPlayerHandlerThread; - private HandlerThread queueSaveHandlerThread; - private SongPlayCountHelper songPlayCountHelper = new SongPlayCountHelper(); - private ThrottledSeekHandler throttledSeekHandler; - private boolean becomingNoisyReceiverRegistered; - private IntentFilter becomingNoisyReceiverIntentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); - private ContentObserver mediaStoreObserver; - private boolean notHandledMetaChangedForCurrentTrack; - private PhoneStateListener phoneStateListener = new PhoneStateListener() { - @Override - public void onCallStateChanged(int state, String incomingNumber) { - switch (state) { - case TelephonyManager.CALL_STATE_IDLE: - //Not in call: Play music - play(); - break; - case TelephonyManager.CALL_STATE_RINGING: - case TelephonyManager.CALL_STATE_OFFHOOK: - //A call is dialing, active or on hold - pause(); - break; - default: - } - super.onCallStateChanged(state, incomingNumber); - } - }; - private boolean isServiceBound; - private Handler uiThreadHandler; - private final BroadcastReceiver widgetIntentReceiver = new BroadcastReceiver() { - @Override - public void onReceive(final Context context, final Intent intent) { - final String command = intent.getStringExtra(EXTRA_APP_WIDGET_NAME); - - if (AppWidgetClassic.NAME.equals(command)) { - final int[] ids = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); - appWidgetClassic.performUpdate(MusicService.this, ids); - } else if (AppWidgetSmall.NAME.equals(command)) { - final int[] ids = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); - appWidgetSmall.performUpdate(MusicService.this, ids); - } else if (AppWidgetBig.NAME.equals(command)) { - final int[] ids = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); - appWidgetBig.performUpdate(MusicService.this, ids); - } else if (AppWidgetCard.NAME.equals(command)) { - final int[] ids = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); - appWidgetCard.performUpdate(MusicService.this, ids); - } - } - }; - private IntentFilter headsetReceiverIntentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); - private boolean headsetReceiverRegistered = false; - private BroadcastReceiver headsetReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (action != null) { - switch (action) { - case Intent.ACTION_HEADSET_PLUG: - int state = intent.getIntExtra("state", -1); - switch (state) { - case 0: - Log.d(TAG, "Headset unplugged"); - pause(); - break; - case 1: - Log.d(TAG, "Headset plugged"); - play(); - break; - } - break; - } - } - } - }; - - private static String getTrackUri(@NonNull Song song) { - return MusicUtil.getSongFileUri(song.id).toString(); - } - - private static Bitmap copy(Bitmap bitmap) { - Bitmap.Config config = bitmap.getConfig(); - if (config == null) { - config = Bitmap.Config.RGB_565; - } - try { - return bitmap.copy(config, false); - } catch (OutOfMemoryError e) { - e.printStackTrace(); - return null; - } - } - - - @Override - public void onCreate() { - super.onCreate(); - - final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if (telephonyManager != null) { - telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); - } - - final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); - if (powerManager != null) { - wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName()); - } - wakeLock.setReferenceCounted(false); - - musicPlayerHandlerThread = new HandlerThread("PlaybackHandler"); - musicPlayerHandlerThread.start(); - playerHandler = new PlaybackHandler(this, musicPlayerHandlerThread.getLooper()); - - playback = new MultiPlayer(this); - playback.setCallbacks(this); - - setupMediaSession(); - - // queue saving needs to run on a separate thread so that it doesn't block the playback handler events - queueSaveHandlerThread = new HandlerThread("QueueSaveHandler", Process.THREAD_PRIORITY_BACKGROUND); - queueSaveHandlerThread.start(); - queueSaveHandler = new QueueSaveHandler(this, queueSaveHandlerThread.getLooper()); - - uiThreadHandler = new Handler(); - - registerReceiver(widgetIntentReceiver, new IntentFilter(APP_WIDGET_UPDATE)); - - initNotification(); - - mediaStoreObserver = new MediaStoreObserver(playerHandler); - throttledSeekHandler = new ThrottledSeekHandler(playerHandler); - getContentResolver().registerContentObserver( - MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mediaStoreObserver); - getContentResolver().registerContentObserver( - MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mediaStoreObserver); - - PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this); - - restoreState(); - - mediaSession.setActive(true); - - sendBroadcast(new Intent("code.name.monkey.retromusic.RETRO_MUSIC_SERVICE_CREATED")); - - registerHeadsetEvents(); - - - } - - private AudioManager getAudioManager() { - if (audioManager == null) { - audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); - } - return audioManager; - } - - private void setupMediaSession() { - ComponentName mediaButtonReceiverComponentName = new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class); - - Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); - mediaButtonIntent.setComponent(mediaButtonReceiverComponentName); - - - PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0); - - mediaSession = new MediaSessionCompat(this, "RetroMusicPlayer", mediaButtonReceiverComponentName, mediaButtonReceiverPendingIntent); - mediaSession.setCallback(new MediaSessionCompat.Callback() { - @Override - public void onPlay() { - play(); - } - - @Override - public void onPause() { - pause(); - } - - @Override - public void onSkipToNext() { - playNextSong(true); - } - - @Override - public void onSkipToPrevious() { - back(true); - } - - @Override - public void onStop() { - quit(); - } - - @Override - public void onSeekTo(long pos) { - seek((int) pos); - } - - @Override - public boolean onMediaButtonEvent(Intent mediaButtonEvent) { - return MediaButtonIntentReceiver.handleIntent(MusicService.this, mediaButtonEvent); - } - }); - - mediaSession.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS - | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS); - - mediaSession.setMediaButtonReceiver(mediaButtonReceiverPendingIntent); - } - - @Override - public int onStartCommand(@Nullable Intent intent, int flags, int startId) { - if (intent != null) { - if (intent.getAction() != null) { - restoreQueuesAndPositionIfNecessary(); - String action = intent.getAction(); - switch (action) { - case ACTION_TOGGLE_PAUSE: - if (isPlaying()) { - pause(); - } else { - play(); - } - break; - case ACTION_PAUSE: - pause(); - break; - case ACTION_PLAY: - play(); - break; - case ACTION_PLAY_PLAYLIST: - Playlist playlist = intent.getParcelableExtra(INTENT_EXTRA_PLAYLIST); - int shuffleMode = intent.getIntExtra(INTENT_EXTRA_SHUFFLE_MODE, getShuffleMode()); - if (playlist != null) { - ArrayList playlistSongs; - if (playlist instanceof AbsCustomPlaylist) { - playlistSongs = ((AbsCustomPlaylist) playlist).getSongs(getApplicationContext()).blockingFirst(); - } else { - //noinspection unchecked - playlistSongs = PlaylistSongsLoader.getPlaylistSongList(getApplicationContext(), playlist.id).blockingFirst(); - } - if (!playlistSongs.isEmpty()) { - if (shuffleMode == SHUFFLE_MODE_SHUFFLE) { - int startPosition; - startPosition = new Random().nextInt(playlistSongs.size()); - openQueue(playlistSongs, startPosition, true); - setShuffleMode(shuffleMode); - } else { - openQueue(playlistSongs, 0, true); - } - } else { - Toast.makeText(getApplicationContext(), R.string.playlist_is_empty, Toast.LENGTH_LONG).show(); - } - } else { - Toast.makeText(getApplicationContext(), R.string.playlist_is_empty, Toast.LENGTH_LONG).show(); - } - break; - case ACTION_REWIND: - back(true); - break; - case ACTION_SKIP: - playNextSong(true); - break; - case ACTION_STOP: - case ACTION_QUIT: - return quit(); - } - } - } - - return START_STICKY; - } - - - @Override - public void onDestroy() { - unregisterReceiver(widgetIntentReceiver); - if (becomingNoisyReceiverRegistered) { - unregisterReceiver(becomingNoisyReceiver); - becomingNoisyReceiverRegistered = false; - } - if (headsetReceiverRegistered) { - unregisterReceiver(headsetReceiver); - headsetReceiverRegistered = false; - } - mediaSession.setActive(false); - quit(); - releaseResources(); - getContentResolver().unregisterContentObserver(mediaStoreObserver); - PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this); - wakeLock.release(); - - sendBroadcast(new Intent("code.name.monkey.retromusic.RETRO_MUSIC_MUSIC_SERVICE_DESTROYED")); - } - - @Override - public IBinder onBind(Intent intent) { - isServiceBound = true; - return musicBind; - } - - @Override - public void onRebind(Intent intent) { - isServiceBound = true; - } - - @Override - public boolean onUnbind(Intent intent) { - isServiceBound = false; - if (!isPlaying()) { - stopSelf(); - } - return true; - } - - private void saveQueuesImpl() { - MusicPlaybackQueueStore.getInstance(this).saveQueues(playingQueue, originalPlayingQueue); - } - - private void savePosition() { - PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(SAVED_POSITION, getPosition()).apply(); - } - - private void savePositionInTrack() { - PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(SAVED_POSITION_IN_TRACK, getSongProgressMillis()).apply(); - } - - public void saveState() { - saveQueues(); - savePosition(); - savePositionInTrack(); - } - - private void saveQueues() { - queueSaveHandler.removeMessages(SAVE_QUEUES); - queueSaveHandler.sendEmptyMessage(SAVE_QUEUES); - } - - private void restoreState() { - shuffleMode = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_SHUFFLE_MODE, 0); - repeatMode = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_REPEAT_MODE, 0); - handleAndSendChangeInternal(SHUFFLE_MODE_CHANGED); - handleAndSendChangeInternal(REPEAT_MODE_CHANGED); - - playerHandler.removeMessages(RESTORE_QUEUES); - playerHandler.sendEmptyMessage(RESTORE_QUEUES); - } - - private synchronized void restoreQueuesAndPositionIfNecessary() { - if (!queuesRestored && playingQueue.isEmpty()) { - ArrayList restoredQueue = MusicPlaybackQueueStore.getInstance(this).getSavedPlayingQueue() - .blockingFirst(); - - ArrayList restoredOriginalQueue = MusicPlaybackQueueStore.getInstance(this).getSavedOriginalPlayingQueue() - .blockingFirst(); - - int restoredPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_POSITION, -1); - int restoredPositionInTrack = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_POSITION_IN_TRACK, -1); - - if (restoredQueue.size() > 0 && restoredQueue.size() == restoredOriginalQueue.size() && restoredPosition != -1) { - this.originalPlayingQueue = restoredOriginalQueue; - this.playingQueue = restoredQueue; - - position = restoredPosition; - openCurrent(); - prepareNext(); - - if (restoredPositionInTrack > 0) seek(restoredPositionInTrack); - - notHandledMetaChangedForCurrentTrack = true; - sendChangeInternal(META_CHANGED); - sendChangeInternal(QUEUE_CHANGED); - } - } - queuesRestored = true; - } - - private int quit() { - pause(); - playingNotification.stop(); - - if (isServiceBound) { - return START_STICKY; - } else { - closeAudioEffectSession(); - getAudioManager().abandonAudioFocus(audioFocusListener); - stopSelf(); - return START_NOT_STICKY; - } - } - - private void releaseResources() { - playerHandler.removeCallbacksAndMessages(null); - musicPlayerHandlerThread.quitSafely(); - queueSaveHandler.removeCallbacksAndMessages(null); - queueSaveHandlerThread.quitSafely(); - playback.release(); - playback = null; - mediaSession.release(); - } - - public boolean isPlaying() { - return playback != null && playback.isPlaying(); - } - - public int getPosition() { - return position; - } - - public void setPosition(final int position) { - // handle this on the handlers thread to avoid blocking the ui thread - playerHandler.removeMessages(SET_POSITION); - playerHandler.obtainMessage(SET_POSITION, position, 0).sendToTarget(); - } - - public void playNextSong(boolean force) { - playSongAt(getNextPosition(force)); - } - - private boolean openTrackAndPrepareNextAt(int position) { - synchronized (this) { - this.position = position; - boolean prepared = openCurrent(); - if (prepared) prepareNextImpl(); - notifyChange(META_CHANGED); - notHandledMetaChangedForCurrentTrack = false; - return prepared; - } - } - - private boolean openCurrent() { - synchronized (this) { - try { - return playback.setDataSource(getTrackUri(getCurrentSong())); - } catch (Exception e) { - return false; - } - } - } - - private void prepareNext() { - playerHandler.removeMessages(PREPARE_NEXT); - playerHandler.obtainMessage(PREPARE_NEXT).sendToTarget(); - } - - private boolean prepareNextImpl() { - synchronized (this) { - try { - int nextPosition = getNextPosition(false); - playback.setNextDataSource(getTrackUri(getSongAt(nextPosition))); - this.nextPosition = nextPosition; - return true; - } catch (Exception e) { - return false; - } - } - } - - private void closeAudioEffectSession() { - final Intent audioEffectsIntent = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION); - audioEffectsIntent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, playback.getAudioSessionId()); - audioEffectsIntent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); - sendBroadcast(audioEffectsIntent); - } - - private boolean requestFocus() { - return (getAudioManager().requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED); - } - - public void initNotification() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !PreferenceUtil.getInstance().classicNotification()) { - playingNotification = new PlayingNotificationImpl24(); - } else { - playingNotification = new PlayingNotificationOreo(); - } - playingNotification.init(this); - } - - public void updateNotification() { - if (playingNotification != null && getCurrentSong().id != -1) { - playingNotification.update(); - } - } - - private void updateMediaSessionPlaybackState() { - mediaSession.setPlaybackState( - new PlaybackStateCompat.Builder() - .setActions(MEDIA_SESSION_ACTIONS) - .setState(isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED, - getPosition(), 1) - .build()); - } - - private void updateMediaSessionMetaData() { - final Song song = getCurrentSong(); - - if (song.id == -1) { - mediaSession.setMetadata(null); - return; - } - - final MediaMetadataCompat.Builder metaData = new MediaMetadataCompat.Builder() - .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artistName) - .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, song.artistName) - .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.albumName) - .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title) - .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.duration) - .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getPosition() + 1) - .putLong(MediaMetadataCompat.METADATA_KEY_YEAR, song.year) - .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - metaData.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getPlayingQueue().size()); - } - - if (PreferenceUtil.getInstance().albumArtOnLockscreen()) { - final Point screenSize = RetroUtil.getScreenSize(MusicService.this); - final BitmapRequestBuilder request = SongGlideRequest.Builder.from(Glide.with(MusicService.this), song) - .checkIgnoreMediaStore(MusicService.this) - .asBitmap().build(); - if (PreferenceUtil.getInstance().blurredAlbumArt()) { - request.transform(new BlurTransformation.Builder(MusicService.this).build()); - } - runOnUiThread(new Runnable() { - @Override - public void run() { - request.into(new SimpleTarget(screenSize.x, screenSize.y) { - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - mediaSession.setMetadata(metaData.build()); - } - - @Override - public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) { - metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, copy(resource)); - mediaSession.setMetadata(metaData.build()); - } - }); - } - }); - } else { - mediaSession.setMetadata(metaData.build()); - } - } - - public void runOnUiThread(Runnable runnable) { - uiThreadHandler.post(runnable); - } - - public Song getCurrentSong() { - return getSongAt(getPosition()); - } - - public Song getSongAt(int position) { - if (position >= 0 && position < getPlayingQueue().size()) { - return getPlayingQueue().get(position); - } else { - return Song.EMPTY_SONG; - } - } - - public int getNextPosition(boolean force) { - int position = getPosition() + 1; - switch (getRepeatMode()) { - case REPEAT_MODE_ALL: - if (isLastTrack()) { - position = 0; - } - break; - case REPEAT_MODE_THIS: - if (force) { - if (isLastTrack()) { - position = 0; - } - } else { - position -= 1; - } - break; - default: - case REPEAT_MODE_NONE: - if (isLastTrack()) { - position -= 1; - } - break; - } - return position; - } - - private boolean isLastTrack() { - return getPosition() == getPlayingQueue().size() - 1; - } - - public ArrayList getPlayingQueue() { - return playingQueue; - } - - public int getRepeatMode() { - return repeatMode; - } - - public void setRepeatMode(final int repeatMode) { - switch (repeatMode) { - case REPEAT_MODE_NONE: - case REPEAT_MODE_ALL: - case REPEAT_MODE_THIS: - this.repeatMode = repeatMode; - PreferenceManager.getDefaultSharedPreferences(this).edit() - .putInt(SAVED_REPEAT_MODE, repeatMode) - .apply(); - prepareNext(); - handleAndSendChangeInternal(REPEAT_MODE_CHANGED); - break; - } - } - - public void openQueue(@Nullable final ArrayList playingQueue, final int startPosition, final boolean startPlaying) { - if (playingQueue != null && !playingQueue.isEmpty() && startPosition >= 0 && startPosition < playingQueue.size()) { - // it is important to copy the playing queue here first as we might add/remove songs later - originalPlayingQueue = new ArrayList<>(playingQueue); - this.playingQueue = new ArrayList<>(originalPlayingQueue); - - int position = startPosition; - if (shuffleMode == SHUFFLE_MODE_SHUFFLE) { - ShuffleHelper.makeShuffleList(this.playingQueue, startPosition); - position = 0; - } - if (startPlaying) { - playSongAt(position); - } else { - setPosition(position); - } - notifyChange(QUEUE_CHANGED); - } - } - - public void addSong(int position, Song song) { - playingQueue.add(position, song); - originalPlayingQueue.add(position, song); - notifyChange(QUEUE_CHANGED); - } - - public void addSong(Song song) { - playingQueue.add(song); - originalPlayingQueue.add(song); - notifyChange(QUEUE_CHANGED); - } - - public void addSongs(int position, List songs) { - playingQueue.addAll(position, songs); - originalPlayingQueue.addAll(position, songs); - notifyChange(QUEUE_CHANGED); - } - - public void addSongs(List songs) { - playingQueue.addAll(songs); - originalPlayingQueue.addAll(songs); - notifyChange(QUEUE_CHANGED); - } - - public void removeSong(int position) { - if (getShuffleMode() == SHUFFLE_MODE_NONE) { - playingQueue.remove(position); - originalPlayingQueue.remove(position); - } else { - originalPlayingQueue.remove(playingQueue.remove(position)); - } - - rePosition(position); - - notifyChange(QUEUE_CHANGED); - } - - public void removeSong(@NonNull Song song) { - for (int i = 0; i < playingQueue.size(); i++) { - if (playingQueue.get(i).id == song.id) { - playingQueue.remove(i); - rePosition(i); - } - } - for (int i = 0; i < originalPlayingQueue.size(); i++) { - if (originalPlayingQueue.get(i).id == song.id) { - originalPlayingQueue.remove(i); - } - } - notifyChange(QUEUE_CHANGED); - } - - private void rePosition(int deletedPosition) { - int currentPosition = getPosition(); - if (deletedPosition < currentPosition) { - position = currentPosition - 1; - } else if (deletedPosition == currentPosition) { - if (playingQueue.size() > deletedPosition) { - setPosition(position); - } else { - setPosition(position - 1); - } - } - } - - public void moveSong(int from, int to) { - if (from == to) return; - final int currentPosition = getPosition(); - Song songToMove = playingQueue.remove(from); - playingQueue.add(to, songToMove); - if (getShuffleMode() == SHUFFLE_MODE_NONE) { - Song tmpSong = originalPlayingQueue.remove(from); - originalPlayingQueue.add(to, tmpSong); - } - if (from > currentPosition && to <= currentPosition) { - position = currentPosition + 1; - } else if (from < currentPosition && to >= currentPosition) { - position = currentPosition - 1; - } else if (from == currentPosition) { - position = to; - } - notifyChange(QUEUE_CHANGED); - } - - public void clearQueue() { - playingQueue.clear(); - originalPlayingQueue.clear(); - - setPosition(-1); - notifyChange(QUEUE_CHANGED); - } - - public void playSongAt(final int position) { - // handle this on the handlers thread to avoid blocking the ui thread - playerHandler.removeMessages(PLAY_SONG); - playerHandler.obtainMessage(PLAY_SONG, position, 0).sendToTarget(); - } - - private void playSongAtImpl(int position) { - if (openTrackAndPrepareNextAt(position)) { - play(); - } else { - Toast.makeText(this, getResources().getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show(); - } - } - - public void pause() { - pausedByTransientLossOfFocus = false; - if (playback.isPlaying()) { - playback.pause(); - notifyChange(PLAY_STATE_CHANGED); - } - } - - public void play() { - synchronized (this) { - if (requestFocus()) { - if (!playback.isPlaying()) { - if (!playback.isInitialized()) { - playSongAt(getPosition()); - } else { - playback.start(); - if (!becomingNoisyReceiverRegistered) { - registerReceiver(becomingNoisyReceiver, becomingNoisyReceiverIntentFilter); - becomingNoisyReceiverRegistered = true; - } - if (notHandledMetaChangedForCurrentTrack) { - handleChangeInternal(META_CHANGED); - notHandledMetaChangedForCurrentTrack = false; - } - notifyChange(PLAY_STATE_CHANGED); - - // fixes a bug where the volume would stay ducked because the AudioManager.AUDIOFOCUS_GAIN event is not sent - playerHandler.removeMessages(DUCK); - playerHandler.sendEmptyMessage(UNDUCK); - } - } - } else { - Toast.makeText(this, getResources().getString(R.string.audio_focus_denied), Toast.LENGTH_SHORT).show(); - } - } - } - - public void playSongs(ArrayList songs, int shuffleMode) { - if (songs != null && !songs.isEmpty()) { - if (shuffleMode == SHUFFLE_MODE_SHUFFLE) { - int startPosition = 0; - if (!songs.isEmpty()) { - startPosition = new Random().nextInt(songs.size()); - } - openQueue(songs, startPosition, false); - setShuffleMode(shuffleMode); - } else { - openQueue(songs, 0, false); - } - play(); - } else { - Toast.makeText(getApplicationContext(), R.string.playlist_is_empty, Toast.LENGTH_LONG).show(); - } - } - - public void playPreviousSong(boolean force) { - playSongAt(getPreviousPosition(force)); - } - - public void back(boolean force) { - if (getSongProgressMillis() > 2000) { - seek(0); - } else { - playPreviousSong(force); - } - } - - public int getPreviousPosition(boolean force) { - int newPosition = getPosition() - 1; - switch (repeatMode) { - case REPEAT_MODE_ALL: - if (newPosition < 0) { - newPosition = getPlayingQueue().size() - 1; - } - break; - case REPEAT_MODE_THIS: - if (force) { - if (newPosition < 0) { - newPosition = getPlayingQueue().size() - 1; - } - } else { - newPosition = getPosition(); - } - break; - default: - case REPEAT_MODE_NONE: - if (newPosition < 0) { - newPosition = 0; - } - break; - } - return newPosition; - } - - public int getSongProgressMillis() { - return playback.position(); - } - - public int getSongDurationMillis() { - return playback.duration(); - } - - public long getQueueDurationMillis(int position) { - long duration = 0; - for (int i = position + 1; i < playingQueue.size(); i++) - duration += playingQueue.get(i).duration; - return duration; - } - - public int seek(int millis) { - synchronized (this) { - try { - int newPosition = playback.seek(millis); - throttledSeekHandler.notifySeek(); - return newPosition; - } catch (Exception e) { - return -1; - } - } - } - - public void cycleRepeatMode() { - switch (getRepeatMode()) { - case REPEAT_MODE_NONE: - setRepeatMode(REPEAT_MODE_ALL); - break; - case REPEAT_MODE_ALL: - setRepeatMode(REPEAT_MODE_THIS); - break; - default: - setRepeatMode(REPEAT_MODE_NONE); - break; - } - } - - public void toggleShuffle() { - if (getShuffleMode() == SHUFFLE_MODE_NONE) { - setShuffleMode(SHUFFLE_MODE_SHUFFLE); - } else { - setShuffleMode(SHUFFLE_MODE_NONE); - } - } - - public int getShuffleMode() { - return shuffleMode; - } - - public void setShuffleMode(final int shuffleMode) { - PreferenceManager.getDefaultSharedPreferences(this).edit() - .putInt(SAVED_SHUFFLE_MODE, shuffleMode) - .apply(); - switch (shuffleMode) { - case SHUFFLE_MODE_SHUFFLE: - this.shuffleMode = shuffleMode; - ShuffleHelper.makeShuffleList(this.getPlayingQueue(), getPosition()); - position = 0; - break; - case SHUFFLE_MODE_NONE: - this.shuffleMode = shuffleMode; - int currentSongId = getCurrentSong().id; - playingQueue = new ArrayList<>(originalPlayingQueue); - int newPosition = 0; - for (Song song : getPlayingQueue()) { - if (song.id == currentSongId) { - newPosition = getPlayingQueue().indexOf(song); - } - } - position = newPosition; - break; - } - handleAndSendChangeInternal(SHUFFLE_MODE_CHANGED); - notifyChange(QUEUE_CHANGED); - } - - private void notifyChange(@NonNull final String what) { - handleAndSendChangeInternal(what); - sendPublicIntent(what); - } - - private void handleAndSendChangeInternal(@NonNull final String what) { - handleChangeInternal(what); - sendChangeInternal(what); - } - - // to let other apps know whats playing. i.E. last.fm (scrobbling) or musixmatch - private void sendPublicIntent(@NonNull final String what) { - final Intent intent = new Intent(what.replace(RETRO_MUSIC_PACKAGE_NAME, MUSIC_PACKAGE_NAME)); - - final Song song = getCurrentSong(); - - intent.putExtra("id", song.id); - intent.putExtra("artist", song.artistName); - intent.putExtra("album", song.albumName); - intent.putExtra("track", song.title); - intent.putExtra("duration", song.duration); - intent.putExtra("position", (long) getSongProgressMillis()); - intent.putExtra("playing", isPlaying()); - intent.putExtra("scrobbling_source", RETRO_MUSIC_PACKAGE_NAME); - - sendStickyBroadcast(intent); - - } - - private void sendChangeInternal(final String what) { - sendBroadcast(new Intent(what)); - appWidgetBig.notifyChange(this, what); - appWidgetClassic.notifyChange(this, what); - appWidgetSmall.notifyChange(this, what); - appWidgetCard.notifyChange(this, what); - } - - private void handleChangeInternal(@NonNull final String what) { - switch (what) { - case PLAY_STATE_CHANGED: - updateNotification(); - updateMediaSessionPlaybackState(); - final boolean isPlaying = isPlaying(); - if (!isPlaying && getSongProgressMillis() > 0) { - savePositionInTrack(); - } - songPlayCountHelper.notifyPlayStateChanged(isPlaying); - break; - case META_CHANGED: - updateNotification(); - updateMediaSessionMetaData(); - savePosition(); - savePositionInTrack(); - final Song currentSong = getCurrentSong(); - HistoryStore.getInstance(this).addSongId(currentSong.id); - if (songPlayCountHelper.shouldBumpPlayCount()) { - SongPlayCountStore.getInstance(this).bumpPlayCount(songPlayCountHelper.getSong().id); - } - songPlayCountHelper.notifySongChanged(currentSong); - break; - case QUEUE_CHANGED: - updateMediaSessionMetaData(); // because playing queue size might have changed - saveState(); - if (playingQueue.size() > 0) { - prepareNext(); - } else { - playingNotification.stop(); - } - break; - } - } - - public int getAudioSessionId() { - return playback.getAudioSessionId(); - } - - public MediaSessionCompat getMediaSession() { - return mediaSession; - } - - public void releaseWakeLock() { - if (wakeLock.isHeld()) { - wakeLock.release(); - } - } - - public void acquireWakeLock(long milli) { - wakeLock.acquire(milli); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - switch (key) { - case PreferenceUtil.GAPLESS_PLAYBACK: - if (sharedPreferences.getBoolean(key, false)) { - prepareNext(); - } else { - playback.setNextDataSource(null); - } - break; - case PreferenceUtil.ALBUM_ART_ON_LOCKSCREEN: - case PreferenceUtil.BLURRED_ALBUM_ART: - updateMediaSessionMetaData(); - break; - case PreferenceUtil.COLORED_NOTIFICATION: - case PreferenceUtil.DOMINANT_COLOR: - updateNotification(); - break; - case PreferenceUtil.CLASSIC_NOTIFICATION: - initNotification(); - updateNotification(); - break; - case PreferenceUtil.TOGGLE_HEADSET: - registerHeadsetEvents(); - break; - } - } - - private void registerHeadsetEvents() { - if (!headsetReceiverRegistered && PreferenceUtil.getInstance().getHeadsetPlugged()) { - registerReceiver(headsetReceiver, headsetReceiverIntentFilter); - headsetReceiverRegistered = true; - } - } - - @Override - public void onTrackWentToNext() { - playerHandler.sendEmptyMessage(TRACK_WENT_TO_NEXT); - } - - @Override - public void onTrackEnded() { - acquireWakeLock(30000); - playerHandler.sendEmptyMessage(TRACK_ENDED); - } - - - private static final class QueueSaveHandler extends Handler { - @NonNull - private final WeakReference mService; - - QueueSaveHandler(final MusicService service, @NonNull final Looper looper) { - super(looper); - mService = new WeakReference<>(service); - } - - @Override - public void handleMessage(@NonNull Message msg) { - final MusicService service = mService.get(); - switch (msg.what) { - case SAVE_QUEUES: - service.saveQueuesImpl(); - break; - } - } - } - - private static final class PlaybackHandler extends Handler { - @NonNull - private final WeakReference mService; - private float currentDuckVolume = 1.0f; - - PlaybackHandler(final MusicService service, @NonNull final Looper looper) { - super(looper); - mService = new WeakReference<>(service); - } - - @Override - public void handleMessage(@NonNull final Message msg) { - final MusicService service = mService.get(); - if (service == null) { - return; - } - - switch (msg.what) { - case DUCK: - if (PreferenceUtil.getInstance().audioDucking()) { - currentDuckVolume -= .05f; - if (currentDuckVolume > .2f) { - sendEmptyMessageDelayed(DUCK, 10); - } else { - currentDuckVolume = .2f; - } - } else { - currentDuckVolume = 1f; - } - service.playback.setVolume(currentDuckVolume); - break; - - case UNDUCK: - if (PreferenceUtil.getInstance().audioDucking()) { - currentDuckVolume += .03f; - if (currentDuckVolume < 1f) { - sendEmptyMessageDelayed(UNDUCK, 10); - } else { - currentDuckVolume = 1f; - } - } else { - currentDuckVolume = 1f; - } - service.playback.setVolume(currentDuckVolume); - break; - - case TRACK_WENT_TO_NEXT: - if (service.getRepeatMode() == REPEAT_MODE_NONE && service.isLastTrack()) { - service.pause(); - service.seek(0); - } else { - service.position = service.nextPosition; - service.prepareNextImpl(); - service.notifyChange(META_CHANGED); - } - break; - - case TRACK_ENDED: - if (service.getRepeatMode() == REPEAT_MODE_NONE && service.isLastTrack()) { - service.notifyChange(PLAY_STATE_CHANGED); - service.seek(0); - } else { - service.playNextSong(false); - } - sendEmptyMessage(RELEASE_WAKELOCK); - break; - - case RELEASE_WAKELOCK: - service.releaseWakeLock(); - break; - - case PLAY_SONG: - service.playSongAtImpl(msg.arg1); - break; - - case SET_POSITION: - service.openTrackAndPrepareNextAt(msg.arg1); - service.notifyChange(PLAY_STATE_CHANGED); - break; - - case PREPARE_NEXT: - service.prepareNextImpl(); - break; - - case RESTORE_QUEUES: - service.restoreQueuesAndPositionIfNecessary(); - break; - - case FOCUS_CHANGE: - switch (msg.arg1) { - case AudioManager.AUDIOFOCUS_GAIN: - if (!service.isPlaying() && service.pausedByTransientLossOfFocus) { - service.play(); - service.pausedByTransientLossOfFocus = false; - } - removeMessages(DUCK); - sendEmptyMessage(UNDUCK); - break; - - case AudioManager.AUDIOFOCUS_LOSS: - // Lost focus for an unbounded amount of time: stop playback and release media playback - service.pause(); - break; - - case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: - // Lost focus for a short time, but we have to stop - // playback. We don't release the media playback because playback - // is likely to resume - boolean wasPlaying = service.isPlaying(); - service.pause(); - service.pausedByTransientLossOfFocus = wasPlaying; - break; - - case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: - // Lost focus for a short time, but it's ok to keep playing - // at an attenuated level - removeMessages(UNDUCK); - sendEmptyMessage(DUCK); - break; - } - break; - } - } - } - - private static class SongPlayCountHelper { - public static final String TAG = SongPlayCountHelper.class.getSimpleName(); - - private StopWatch stopWatch = new StopWatch(); - private Song song = Song.EMPTY_SONG; - - public Song getSong() { - return song; - } - - boolean shouldBumpPlayCount() { - return song.duration * 0.5d < stopWatch.getElapsedTime(); - } - - void notifySongChanged(Song song) { - synchronized (this) { - stopWatch.reset(); - this.song = song; - } - } - - void notifyPlayStateChanged(boolean isPlaying) { - synchronized (this) { - if (isPlaying) { - stopWatch.start(); - } else { - stopWatch.pause(); - } - } - } - } - - public class MusicBinder extends Binder { - @NonNull - public MusicService getService() { - return MusicService.this; - } - } - - private class MediaStoreObserver extends ContentObserver implements Runnable { - // milliseconds to delay before calling refresh to aggregate events - private static final long REFRESH_DELAY = 500; - private Handler mHandler; - - MediaStoreObserver(Handler handler) { - super(handler); - mHandler = handler; - } - - @Override - public void onChange(boolean selfChange) { - // if a change is detected, remove any scheduled callback - // then post a new one. This is intended to prevent closely - // spaced events from generating multiple refresh calls - mHandler.removeCallbacks(this); - mHandler.postDelayed(this, REFRESH_DELAY); - } - - @Override - public void run() { - // actually call refresh when the delayed callback fires - // do not send a sticky broadcast here - handleAndSendChangeInternal(MEDIA_STORE_CHANGED); - } - } - - private class ThrottledSeekHandler implements Runnable { - // milliseconds to throttle before calling run() to aggregate events - private static final long THROTTLE = 500; - private Handler mHandler; - - ThrottledSeekHandler(Handler handler) { - mHandler = handler; - } - - void notifySeek() { - mHandler.removeCallbacks(this); - mHandler.postDelayed(this, THROTTLE); - } - - @Override - public void run() { - savePositionInTrack(); - sendPublicIntent(PLAY_STATE_CHANGED); // for musixmatch synced lyrics - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/MusicService.kt b/app/src/main/java/code/name/monkey/retromusic/service/MusicService.kt new file mode 100644 index 00000000..813385cf --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/MusicService.kt @@ -0,0 +1,1247 @@ +package code.name.monkey.retromusic.service + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.app.Service +import android.content.* +import android.database.ContentObserver +import android.graphics.Bitmap +import android.graphics.drawable.Drawable +import android.media.AudioManager +import android.media.audiofx.AudioEffect +import android.media.session.MediaSession +import android.os.* +import android.preference.PreferenceManager +import android.provider.MediaStore +import android.support.v4.media.MediaMetadataCompat +import android.support.v4.media.session.MediaSessionCompat +import android.support.v4.media.session.PlaybackStateCompat +import android.telephony.PhoneStateListener +import android.telephony.TelephonyManager +import android.util.Log +import android.widget.Toast +import code.name.monkey.retromusic.Constants.ACTION_PAUSE +import code.name.monkey.retromusic.Constants.ACTION_PLAY +import code.name.monkey.retromusic.Constants.ACTION_PLAY_PLAYLIST +import code.name.monkey.retromusic.Constants.ACTION_QUIT +import code.name.monkey.retromusic.Constants.ACTION_SKIP +import code.name.monkey.retromusic.Constants.ACTION_STOP +import code.name.monkey.retromusic.Constants.ACTION_TOGGLE_PAUSE +import code.name.monkey.retromusic.Constants.APP_WIDGET_UPDATE +import code.name.monkey.retromusic.Constants.EXTRA_APP_WIDGET_NAME +import code.name.monkey.retromusic.Constants.INTENT_EXTRA_PLAYLIST +import code.name.monkey.retromusic.Constants.INTENT_EXTRA_SHUFFLE_MODE +import code.name.monkey.retromusic.Constants.MEDIA_STORE_CHANGED +import code.name.monkey.retromusic.Constants.META_CHANGED +import code.name.monkey.retromusic.Constants.MUSIC_PACKAGE_NAME +import code.name.monkey.retromusic.Constants.PLAY_STATE_CHANGED +import code.name.monkey.retromusic.Constants.QUEUE_CHANGED +import code.name.monkey.retromusic.Constants.REPEAT_MODE_CHANGED +import code.name.monkey.retromusic.Constants.RETRO_MUSIC_PACKAGE_NAME +import code.name.monkey.retromusic.Constants.SHUFFLE_MODE_CHANGED +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.BlurTransformation +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote.setShuffleMode +import code.name.monkey.retromusic.helper.ShuffleHelper +import code.name.monkey.retromusic.helper.StopWatch +import code.name.monkey.retromusic.loaders.PlaylistSongsLoader +import code.name.monkey.retromusic.model.AbsCustomPlaylist +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.providers.HistoryStore +import code.name.monkey.retromusic.providers.MusicPlaybackQueueStore +import code.name.monkey.retromusic.providers.SongPlayCountStore +import code.name.monkey.retromusic.service.notification.PlayingNotification +import code.name.monkey.retromusic.service.notification.PlayingNotificationImpl24 +import code.name.monkey.retromusic.service.notification.PlayingNotificationOreo +import code.name.monkey.retromusic.service.playback.Playback +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import com.bumptech.glide.Glide +import com.bumptech.glide.request.animation.GlideAnimation +import com.bumptech.glide.request.target.SimpleTarget +import com.google.android.gms.cast.framework.media.MediaIntentReceiver.ACTION_REWIND +import java.lang.ref.WeakReference +import java.util.* + +/** + * @author Karim Abou Zeid (kabouzeid), Andrew Neal + */ +class MusicService : Service(), SharedPreferences.OnSharedPreferenceChangeListener, Playback.PlaybackCallbacks { + private val musicBind = MusicBinder() + private var playback: Playback? = null + var playingQueue = ArrayList() + private set + private var originalPlayingQueue = ArrayList() + var position = -1 + set(value) { + playerHandler!!.removeMessages(SET_POSITION) + playerHandler!!.obtainMessage(SET_POSITION, value, 0).sendToTarget() + } + private var nextPosition = -1 + var shuffleMode: Int = 0 + set(value) { + PreferenceManager.getDefaultSharedPreferences(this).edit() + .putInt(SAVED_SHUFFLE_MODE, value) + .apply() + when (value) { + SHUFFLE_MODE_SHUFFLE -> { + field = value + ShuffleHelper.makeShuffleList(this.playingQueue, position) + position = 0 + } + SHUFFLE_MODE_NONE -> { + field = value + val currentSongId = currentSong.id + playingQueue = ArrayList(originalPlayingQueue) + var newPosition = 0 + for (song in playingQueue) { + if (song.id == currentSongId) { + newPosition = playingQueue.indexOf(song) + } + } + position = newPosition + } + } + handleAndSendChangeInternal(SHUFFLE_MODE_CHANGED) + notifyChange(QUEUE_CHANGED) + } + var repeatMode: Int = 0 + set(value) { + when (value) { + REPEAT_MODE_NONE, REPEAT_MODE_ALL, REPEAT_MODE_THIS -> { + field = value + PreferenceManager.getDefaultSharedPreferences(this).edit() + .putInt(SAVED_REPEAT_MODE, repeatMode) + .apply() + prepareNext() + handleAndSendChangeInternal(REPEAT_MODE_CHANGED) + } + } + } + private var queuesRestored: Boolean = false + private var pausedByTransientLossOfFocus: Boolean = false + private val becomingNoisyReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != null && intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) { + pause() + } + } + } + private var playingNotification: PlayingNotification? = null + private var audioManager: AudioManager? = null + var mediaSession: MediaSessionCompat? = null + private set + private var wakeLock: PowerManager.WakeLock? = null + private var playerHandler: PlaybackHandler? = null + private val audioFocusListener = AudioManager.OnAudioFocusChangeListener { focusChange -> playerHandler!!.obtainMessage(FOCUS_CHANGE, focusChange, 0).sendToTarget() } + private var queueSaveHandler: QueueSaveHandler? = null + private var musicPlayerHandlerThread: HandlerThread? = null + private var queueSaveHandlerThread: HandlerThread? = null + private val songPlayCountHelper = SongPlayCountHelper() + private var throttledSeekHandler: ThrottledSeekHandler? = null + private var becomingNoisyReceiverRegistered: Boolean = false + private val becomingNoisyReceiverIntentFilter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY) + private var mediaStoreObserver: ContentObserver? = null + private var notHandledMetaChangedForCurrentTrack: Boolean = false + private val phoneStateListener = object : PhoneStateListener() { + override fun onCallStateChanged(state: Int, incomingNumber: String) { + when (state) { + TelephonyManager.CALL_STATE_IDLE -> + //Not in call: Play music + play() + TelephonyManager.CALL_STATE_RINGING, TelephonyManager.CALL_STATE_OFFHOOK -> + //A call is dialing, active or on hold + pause() + } + super.onCallStateChanged(state, incomingNumber) + } + } + private var isServiceBound: Boolean = false + private var uiThreadHandler: Handler? = null + private val widgetIntentReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val command = intent.getStringExtra(EXTRA_APP_WIDGET_NAME) + } + } + private val headsetReceiverIntentFilter = IntentFilter(Intent.ACTION_HEADSET_PLUG) + private var headsetReceiverRegistered = false + private val headsetReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val action = intent.action + if (action != null) { + when (action) { + Intent.ACTION_HEADSET_PLUG -> { + val state = intent.getIntExtra("state", -1) + when (state) { + 0 -> { + Log.d(TAG, "Headset unplugged") + pause() + } + 1 -> { + Log.d(TAG, "Headset plugged") + play() + } + } + } + } + } + } + } + + val isPlaying: Boolean + get() = playback != null && playback!!.isPlaying + + val currentSong: Song + get() = getSongAt(position) + + private val isLastTrack: Boolean + get() = position == playingQueue.size - 1 + + val songProgressMillis: Int + get() = playback!!.position() + + val songDurationMillis: Int + get() = playback!!.duration() + + val audioSessionId: Int + get() = playback!!.audioSessionId + + + override fun onCreate() { + super.onCreate() + + val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE) + + val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager + wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, javaClass.name) + wakeLock!!.setReferenceCounted(false) + + musicPlayerHandlerThread = HandlerThread("PlaybackHandler") + musicPlayerHandlerThread!!.start() + playerHandler = PlaybackHandler(this, musicPlayerHandlerThread!!.looper) + + playback = MultiPlayer(this) + playback!!.setCallbacks(this) + + setupMediaSession() + + // queue saving needs to run on a separate thread so that it doesn't block the playback handler events + queueSaveHandlerThread = HandlerThread("QueueSaveHandler", Process.THREAD_PRIORITY_BACKGROUND) + queueSaveHandlerThread!!.start() + queueSaveHandler = QueueSaveHandler(this, queueSaveHandlerThread!!.looper) + + uiThreadHandler = Handler() + + registerReceiver(widgetIntentReceiver, IntentFilter(APP_WIDGET_UPDATE)) + + initNotification() + + mediaStoreObserver = MediaStoreObserver(playerHandler!!) + throttledSeekHandler = ThrottledSeekHandler(playerHandler!!) + contentResolver.registerContentObserver( + MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mediaStoreObserver!!) + contentResolver.registerContentObserver( + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mediaStoreObserver!!) + + PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this) + + restoreState() + + mediaSession!!.isActive = true + + sendBroadcast(Intent("code.name.monkey.retromusic.RETRO_MUSIC_SERVICE_CREATED")) + + registerHeadsetEvents() + + + } + + private fun getAudioManager(): AudioManager? { + if (audioManager == null) { + audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager + } + return audioManager + } + + @SuppressLint("WrongConstant") + private fun setupMediaSession() { + val mediaButtonReceiverComponentName = ComponentName(applicationContext, MediaButtonIntentReceiver::class.java) + + val mediaButtonIntent = Intent(Intent.ACTION_MEDIA_BUTTON) + mediaButtonIntent.component = mediaButtonReceiverComponentName + + + val mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(applicationContext, 0, mediaButtonIntent, 0) + + mediaSession = MediaSessionCompat(this, "RetroMusicPlayer", mediaButtonReceiverComponentName, mediaButtonReceiverPendingIntent) + mediaSession!!.setCallback(object : MediaSessionCompat.Callback() { + override fun onPlay() { + play() + } + + override fun onPause() { + pause() + } + + override fun onSkipToNext() { + playNextSong(true) + } + + override fun onSkipToPrevious() { + back(true) + } + + override fun onStop() { + quit() + } + + override fun onSeekTo(pos: Long) { + seek(pos.toInt()) + } + + override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean { + return MediaButtonIntentReceiver.handleIntent(this@MusicService, mediaButtonEvent) + } + }) + + mediaSession!!.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS or MediaSession.FLAG_HANDLES_MEDIA_BUTTONS) + + mediaSession!!.setMediaButtonReceiver(mediaButtonReceiverPendingIntent) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent != null) { + if (intent.action != null) { + restoreQueuesAndPositionIfNecessary() + val action = intent.action + when (action) { + ACTION_TOGGLE_PAUSE -> if (isPlaying) { + pause() + } else { + play() + } + ACTION_PAUSE -> pause() + ACTION_PLAY -> play() + ACTION_PLAY_PLAYLIST -> { + val playlist = intent.getParcelableExtra(INTENT_EXTRA_PLAYLIST) + val shuffleMode = intent.getIntExtra(INTENT_EXTRA_SHUFFLE_MODE, shuffleMode) + if (playlist != null) { + val playlistSongs: ArrayList + if (playlist is AbsCustomPlaylist) { + playlistSongs = playlist.getSongs(applicationContext).blockingFirst() + } else { + + playlistSongs = PlaylistSongsLoader.getPlaylistSongList(applicationContext, playlist.id).blockingFirst() + } + if (!playlistSongs.isEmpty()) { + if (shuffleMode == SHUFFLE_MODE_SHUFFLE) { + val startPosition: Int = Random().nextInt(playlistSongs.size) + openQueue(playlistSongs, startPosition, true) + setShuffleMode(shuffleMode) + } else { + openQueue(playlistSongs, 0, true) + } + } else { + Toast.makeText(applicationContext, R.string.playlist_is_empty, Toast.LENGTH_LONG).show() + } + } else { + Toast.makeText(applicationContext, R.string.playlist_is_empty, Toast.LENGTH_LONG).show() + } + } + ACTION_REWIND -> back(true) + ACTION_SKIP -> playNextSong(true) + ACTION_STOP, ACTION_QUIT -> return quit() + } + } + } + + return Service.START_STICKY + } + + + override fun onDestroy() { + unregisterReceiver(widgetIntentReceiver) + if (becomingNoisyReceiverRegistered) { + unregisterReceiver(becomingNoisyReceiver) + becomingNoisyReceiverRegistered = false + } + if (headsetReceiverRegistered) { + unregisterReceiver(headsetReceiver) + headsetReceiverRegistered = false + } + mediaSession!!.isActive = false + quit() + releaseResources() + contentResolver.unregisterContentObserver(mediaStoreObserver!!) + PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this) + wakeLock!!.release() + + sendBroadcast(Intent("code.name.monkey.retromusic.RETRO_MUSIC_MUSIC_SERVICE_DESTROYED")) + } + + override fun onBind(intent: Intent): IBinder? { + isServiceBound = true + return musicBind + } + + override fun onRebind(intent: Intent) { + isServiceBound = true + } + + override fun onUnbind(intent: Intent): Boolean { + isServiceBound = false + if (!isPlaying) { + stopSelf() + } + return true + } + + private fun saveQueuesImpl() { + MusicPlaybackQueueStore.getInstance(this).saveQueues(playingQueue, originalPlayingQueue) + } + + private fun savePosition() { + PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(SAVED_POSITION, position).apply() + } + + private fun savePositionInTrack() { + PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(SAVED_POSITION_IN_TRACK, songProgressMillis).apply() + } + + private fun saveState() { + saveQueues() + savePosition() + savePositionInTrack() + } + + private fun saveQueues() { + queueSaveHandler!!.removeMessages(SAVE_QUEUES) + queueSaveHandler!!.sendEmptyMessage(SAVE_QUEUES) + } + + private fun restoreState() { + shuffleMode = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_SHUFFLE_MODE, 0) + repeatMode = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_REPEAT_MODE, 0) + handleAndSendChangeInternal(SHUFFLE_MODE_CHANGED) + handleAndSendChangeInternal(REPEAT_MODE_CHANGED) + + playerHandler!!.removeMessages(RESTORE_QUEUES) + playerHandler!!.sendEmptyMessage(RESTORE_QUEUES) + } + + @Synchronized + private fun restoreQueuesAndPositionIfNecessary() { + if (!queuesRestored && playingQueue.isEmpty()) { + val restoredQueue = MusicPlaybackQueueStore.getInstance(this).savedPlayingQueue + .blockingFirst() + + val restoredOriginalQueue = MusicPlaybackQueueStore.getInstance(this).savedOriginalPlayingQueue + .blockingFirst() + + val restoredPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_POSITION, -1) + val restoredPositionInTrack = PreferenceManager.getDefaultSharedPreferences(this).getInt(SAVED_POSITION_IN_TRACK, -1) + + if (restoredQueue.size > 0 && restoredQueue.size == restoredOriginalQueue.size && restoredPosition != -1) { + this.originalPlayingQueue = restoredOriginalQueue + this.playingQueue = restoredQueue + + position = restoredPosition + openCurrent() + prepareNext() + + if (restoredPositionInTrack > 0) seek(restoredPositionInTrack) + + notHandledMetaChangedForCurrentTrack = true + sendChangeInternal(META_CHANGED) + sendChangeInternal(QUEUE_CHANGED) + } + } + queuesRestored = true + } + + @SuppressLint("WrongConstant") + private fun quit(): Int { + pause() + playingNotification!!.stop() + + if (isServiceBound) { + return Service.START_STICKY + } else { + closeAudioEffectSession() + getAudioManager()!!.abandonAudioFocus(audioFocusListener) + stopSelf() + return Service.START_NOT_STICKY + } + } + + private fun releaseResources() { + playerHandler!!.removeCallbacksAndMessages(null) + musicPlayerHandlerThread!!.quitSafely() + queueSaveHandler!!.removeCallbacksAndMessages(null) + queueSaveHandlerThread!!.quitSafely() + playback!!.release() + playback = null + mediaSession!!.release() + } + + fun playNextSong(force: Boolean) { + playSongAt(getNextPosition(force)) + } + + private fun openTrackAndPrepareNextAt(position: Int): Boolean { + synchronized(this) { + this.position = position + val prepared = openCurrent() + if (prepared) prepareNextImpl() + notifyChange(META_CHANGED) + notHandledMetaChangedForCurrentTrack = false + return prepared + } + } + + private fun openCurrent(): Boolean { + synchronized(this) { + try { + return playback!!.setDataSource(getTrackUri(currentSong)) + } catch (e: Exception) { + return false + } + + } + } + + private fun prepareNext() { + playerHandler!!.removeMessages(PREPARE_NEXT) + playerHandler!!.obtainMessage(PREPARE_NEXT).sendToTarget() + } + + private fun prepareNextImpl(): Boolean { + synchronized(this) { + return try { + val nextPosition = getNextPosition(false) + playback!!.setNextDataSource(getTrackUri(getSongAt(nextPosition))) + this.nextPosition = nextPosition + true + } catch (e: Exception) { + false + } + + } + } + + private fun closeAudioEffectSession() { + val audioEffectsIntent = Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION) + audioEffectsIntent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, playback!!.audioSessionId) + audioEffectsIntent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, packageName) + sendBroadcast(audioEffectsIntent) + } + + private fun requestFocus(): Boolean { + return getAudioManager()!!.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED + } + + fun initNotification() { + playingNotification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && !PreferenceUtil.getInstance().classicNotification()) { + PlayingNotificationImpl24() + } else { + PlayingNotificationOreo() + } + playingNotification!!.init(this) + } + + fun updateNotification() { + if (playingNotification != null && currentSong.id != -1) { + playingNotification!!.update() + } + } + + private fun updateMediaSessionPlaybackState() { + mediaSession!!.setPlaybackState( + PlaybackStateCompat.Builder() + .setActions(MEDIA_SESSION_ACTIONS) + .setState(if (isPlaying) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED, + position.toLong(), 1f) + .build()) + } + + private fun updateMediaSessionMetaData() { + val song = currentSong + + if (song.id == -1) { + mediaSession!!.setMetadata(null) + return + } + + val metaData = MediaMetadataCompat.Builder() + .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artistName) + .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, song.artistName) + .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.albumName) + .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title) + .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.duration) + .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, (position + 1).toLong()) + .putLong(MediaMetadataCompat.METADATA_KEY_YEAR, song.year.toLong()) + .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + metaData.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, playingQueue.size.toLong()) + } + + if (PreferenceUtil.getInstance().albumArtOnLockscreen()) { + val screenSize = RetroUtil.getScreenSize(this@MusicService) + val request = SongGlideRequest.Builder.from(Glide.with(this@MusicService), song) + .checkIgnoreMediaStore(this@MusicService) + .asBitmap().build() + if (PreferenceUtil.getInstance().blurredAlbumArt()) { + request.transform(BlurTransformation.Builder(this@MusicService).build()) + } + runOnUiThread(Runnable { + request.into(object : SimpleTarget(screenSize.x, screenSize.y) { + override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) { + super.onLoadFailed(e, errorDrawable) + mediaSession!!.setMetadata(metaData.build()) + } + + override fun onResourceReady(resource: Bitmap, glideAnimation: GlideAnimation) { + metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, copy(resource)) + mediaSession!!.setMetadata(metaData.build()) + } + }) + }) + } else { + mediaSession!!.setMetadata(metaData.build()) + } + } + + fun runOnUiThread(runnable: Runnable) { + uiThreadHandler!!.post(runnable) + } + + private fun getSongAt(position: Int): Song { + return if (position >= 0 && position < playingQueue.size) { + playingQueue[position] + } else { + Song.EMPTY_SONG + } + } + + private fun getNextPosition(force: Boolean): Int { + var position = position + 1 + when (repeatMode) { + REPEAT_MODE_ALL -> if (isLastTrack) { + position = 0 + } + REPEAT_MODE_THIS -> if (force) { + if (isLastTrack) { + position = 0 + } + } else { + position -= 1 + } + REPEAT_MODE_NONE -> if (isLastTrack) { + position -= 1 + } + else -> if (isLastTrack) { + position -= 1 + } + } + return position + } + + + fun openQueue(playingQueue: ArrayList?, startPosition: Int, startPlaying: Boolean) { + if (playingQueue != null && !playingQueue.isEmpty() && startPosition >= 0 && startPosition < playingQueue.size) { + // it is important to copy the playing queue here first as we might add/remove songs later + originalPlayingQueue = ArrayList(playingQueue) + this.playingQueue = ArrayList(originalPlayingQueue) + + var position = startPosition + if (shuffleMode == SHUFFLE_MODE_SHUFFLE) { + ShuffleHelper.makeShuffleList(this.playingQueue, startPosition) + position = 0 + } + if (startPlaying) { + playSongAt(position) + } else { + this.position = position + } + notifyChange(QUEUE_CHANGED) + } + } + + fun addSong(position: Int, song: Song) { + playingQueue.add(position, song) + originalPlayingQueue.add(position, song) + notifyChange(QUEUE_CHANGED) + } + + fun addSong(song: Song) { + playingQueue.add(song) + originalPlayingQueue.add(song) + notifyChange(QUEUE_CHANGED) + } + + fun addSongs(position: Int, songs: List) { + playingQueue.addAll(position, songs) + originalPlayingQueue.addAll(position, songs) + notifyChange(QUEUE_CHANGED) + } + + fun addSongs(songs: List) { + playingQueue.addAll(songs) + originalPlayingQueue.addAll(songs) + notifyChange(QUEUE_CHANGED) + } + + fun removeSong(position: Int) { + if (shuffleMode == SHUFFLE_MODE_NONE) { + playingQueue.removeAt(position) + originalPlayingQueue.removeAt(position) + } else { + originalPlayingQueue.remove(playingQueue.removeAt(position)) + } + + rePosition(position) + + notifyChange(QUEUE_CHANGED) + } + + fun removeSong(song: Song) { + for (i in playingQueue.indices) { + if (playingQueue[i].id == song.id) { + playingQueue.removeAt(i) + rePosition(i) + } + } + for (i in originalPlayingQueue.indices) { + if (originalPlayingQueue[i].id == song.id) { + originalPlayingQueue.removeAt(i) + } + } + notifyChange(QUEUE_CHANGED) + } + + private fun rePosition(deletedPosition: Int) { + val currentPosition = position + if (deletedPosition < currentPosition) { + position = currentPosition - 1 + } else if (deletedPosition == currentPosition) { + if (playingQueue.size > deletedPosition) { + this.position = position + } else { + this.position = position - 1 + } + } + } + + fun moveSong(from: Int, to: Int) { + if (from == to) return + val currentPosition = position + val songToMove = playingQueue.removeAt(from) + playingQueue.add(to, songToMove) + if (shuffleMode == SHUFFLE_MODE_NONE) { + val tmpSong = originalPlayingQueue.removeAt(from) + originalPlayingQueue.add(to, tmpSong) + } + if (currentPosition in to..(from - 1)) { + position = currentPosition + 1 + } else if (currentPosition in (from + 1)..to) { + position = currentPosition - 1 + } else if (from == currentPosition) { + position = to + } + notifyChange(QUEUE_CHANGED) + } + + fun clearQueue() { + playingQueue.clear() + originalPlayingQueue.clear() + + position = -1 + notifyChange(QUEUE_CHANGED) + } + + fun playSongAt(position: Int) { + // handle this on the handlers thread to avoid blocking the ui thread + playerHandler!!.removeMessages(PLAY_SONG) + playerHandler!!.obtainMessage(PLAY_SONG, position, 0).sendToTarget() + } + + private fun playSongAtImpl(position: Int) { + if (openTrackAndPrepareNextAt(position)) { + play() + } else { + Toast.makeText(this, resources.getString(R.string.unplayable_file), Toast.LENGTH_SHORT).show() + } + } + + fun pause() { + pausedByTransientLossOfFocus = false + if (playback!!.isPlaying) { + playback!!.pause() + notifyChange(PLAY_STATE_CHANGED) + } + } + + fun play() { + synchronized(this) { + if (requestFocus()) { + if (!playback!!.isPlaying) { + if (!playback!!.isInitialized) { + playSongAt(position) + } else { + playback!!.start() + if (!becomingNoisyReceiverRegistered) { + registerReceiver(becomingNoisyReceiver, becomingNoisyReceiverIntentFilter) + becomingNoisyReceiverRegistered = true + } + if (notHandledMetaChangedForCurrentTrack) { + handleChangeInternal(META_CHANGED) + notHandledMetaChangedForCurrentTrack = false + } + notifyChange(PLAY_STATE_CHANGED) + + // fixes a bug where the volume would stay ducked because the AudioManager.AUDIOFOCUS_GAIN event is not sent + playerHandler!!.removeMessages(DUCK) + playerHandler!!.sendEmptyMessage(UN_DUCK) + } + } + } else { + Toast.makeText(this, resources.getString(R.string.audio_focus_denied), Toast.LENGTH_SHORT).show() + } + } + } + + fun playSongs(songs: ArrayList?, shuffleMode: Int) { + if (songs != null && !songs.isEmpty()) { + if (shuffleMode == SHUFFLE_MODE_SHUFFLE) { + var startPosition = 0 + if (!songs.isEmpty()) { + startPosition = Random().nextInt(songs.size) + } + openQueue(songs, startPosition, false) + setShuffleMode(shuffleMode) + } else { + openQueue(songs, 0, false) + } + play() + } else { + Toast.makeText(applicationContext, R.string.playlist_is_empty, Toast.LENGTH_LONG).show() + } + } + + fun playPreviousSong(force: Boolean) { + playSongAt(getPreviousPosition(force)) + } + + fun back(force: Boolean) { + if (songProgressMillis > 2000) { + seek(0) + } else { + playPreviousSong(force) + } + } + + private fun getPreviousPosition(force: Boolean): Int { + var newPosition = position - 1 + when (repeatMode) { + REPEAT_MODE_ALL -> if (newPosition < 0) { + newPosition = playingQueue.size - 1 + } + REPEAT_MODE_THIS -> if (force) { + if (newPosition < 0) { + newPosition = playingQueue.size - 1 + } + } else { + newPosition = position + } + REPEAT_MODE_NONE -> if (newPosition < 0) { + newPosition = 0 + } + else -> if (newPosition < 0) { + newPosition = 0 + } + } + return newPosition + } + + fun getQueueDurationMillis(position: Int): Long { + var duration: Long = 0 + for (i in position + 1 until playingQueue.size) + duration += playingQueue[i].duration + return duration + } + + fun seek(millis: Int): Int { + synchronized(this) { + try { + val newPosition = playback!!.seek(millis) + throttledSeekHandler!!.notifySeek() + return newPosition + } catch (e: Exception) { + return -1 + } + + } + } + + fun cycleRepeatMode() { + repeatMode = when (repeatMode) { + REPEAT_MODE_NONE -> REPEAT_MODE_ALL + REPEAT_MODE_ALL -> REPEAT_MODE_THIS + else -> REPEAT_MODE_NONE + } + } + + fun toggleShuffle() { + if (shuffleMode == SHUFFLE_MODE_NONE) { + setShuffleMode(SHUFFLE_MODE_SHUFFLE) + } else { + setShuffleMode(SHUFFLE_MODE_NONE) + } + } + + + private fun notifyChange(what: String) { + handleAndSendChangeInternal(what) + sendPublicIntent(what) + } + + private fun handleAndSendChangeInternal(what: String) { + handleChangeInternal(what) + sendChangeInternal(what) + } + + // to let other apps know whats playing. i.E. last.fm (scrobbling) or musixmatch + @SuppressLint("WrongConstant") + private fun sendPublicIntent(what: String) { + val intent = Intent(what.replace(RETRO_MUSIC_PACKAGE_NAME, MUSIC_PACKAGE_NAME)) + + val song = currentSong + + intent.putExtra("id", song.id) + intent.putExtra("artist", song.artistName) + intent.putExtra("album", song.albumName) + intent.putExtra("track", song.title) + intent.putExtra("duration", song.duration) + intent.putExtra("position", songProgressMillis.toLong()) + intent.putExtra("playing", isPlaying) + intent.putExtra("scrobbling_source", RETRO_MUSIC_PACKAGE_NAME) + + sendStickyBroadcast(intent) + + } + + private fun sendChangeInternal(what: String) { + sendBroadcast(Intent(what)) + } + + private fun handleChangeInternal(what: String) { + when (what) { + PLAY_STATE_CHANGED -> { + updateNotification() + updateMediaSessionPlaybackState() + val isPlaying = isPlaying + if (!isPlaying && songProgressMillis > 0) { + savePositionInTrack() + } + songPlayCountHelper.notifyPlayStateChanged(isPlaying) + } + META_CHANGED -> { + updateNotification() + updateMediaSessionMetaData() + savePosition() + savePositionInTrack() + val currentSong = currentSong + HistoryStore.getInstance(this).addSongId(currentSong.id.toLong()) + if (songPlayCountHelper.shouldBumpPlayCount()) { + SongPlayCountStore.getInstance(this).bumpPlayCount(songPlayCountHelper.song.id.toLong()) + } + songPlayCountHelper.notifySongChanged(currentSong) + } + QUEUE_CHANGED -> { + updateMediaSessionMetaData() // because playing queue size might have changed + saveState() + if (playingQueue.size > 0) { + prepareNext() + } else { + playingNotification!!.stop() + } + } + } + } + + fun releaseWakeLock() { + if (wakeLock!!.isHeld) { + wakeLock!!.release() + } + } + + private fun acquireWakeLock(milli: Long) { + wakeLock!!.acquire(milli) + } + + override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { + when (key) { + PreferenceUtil.GAPLESS_PLAYBACK -> if (sharedPreferences.getBoolean(key, false)) { + prepareNext() + } else { + playback!!.setNextDataSource(null) + } + PreferenceUtil.ALBUM_ART_ON_LOCKSCREEN, PreferenceUtil.BLURRED_ALBUM_ART -> updateMediaSessionMetaData() + PreferenceUtil.COLORED_NOTIFICATION, PreferenceUtil.DOMINANT_COLOR -> updateNotification() + PreferenceUtil.CLASSIC_NOTIFICATION -> { + initNotification() + updateNotification() + } + PreferenceUtil.TOGGLE_HEADSET -> registerHeadsetEvents() + } + } + + private fun registerHeadsetEvents() { + if (!headsetReceiverRegistered && PreferenceUtil.getInstance().headsetPlugged) { + registerReceiver(headsetReceiver, headsetReceiverIntentFilter) + headsetReceiverRegistered = true + } + } + + override fun onTrackWentToNext() { + playerHandler!!.sendEmptyMessage(TRACK_WENT_TO_NEXT) + } + + override fun onTrackEnded() { + acquireWakeLock(30000) + playerHandler!!.sendEmptyMessage(TRACK_ENDED) + } + + + inner class QueueSaveHandler internal constructor(service: MusicService, looper: Looper) : Handler(looper) { + val mService: WeakReference = WeakReference(service) + + override fun handleMessage(msg: Message) { + val service = mService.get() + when (msg.what) { + SAVE_QUEUES -> service!!.saveQueuesImpl() + } + } + } + + inner class PlaybackHandler internal constructor(service: MusicService, looper: Looper) : Handler(looper) { + val mService: WeakReference = WeakReference(service) + var currentDuckVolume = 1.0f + + override fun handleMessage(msg: Message) { + val service = mService.get() ?: return + + when (msg.what) { + DUCK -> { + if (PreferenceUtil.getInstance().audioDucking()) { + currentDuckVolume -= .05f + if (currentDuckVolume > .2f) { + sendEmptyMessageDelayed(DUCK, 10) + } else { + currentDuckVolume = .2f + } + } else { + currentDuckVolume = 1f + } + service.playback!!.setVolume(currentDuckVolume) + } + + UN_DUCK -> { + if (PreferenceUtil.getInstance().audioDucking()) { + currentDuckVolume += .03f + if (currentDuckVolume < 1f) { + sendEmptyMessageDelayed(UN_DUCK, 10) + } else { + currentDuckVolume = 1f + } + } else { + currentDuckVolume = 1f + } + service.playback!!.setVolume(currentDuckVolume) + } + + TRACK_WENT_TO_NEXT -> if (service.repeatMode == REPEAT_MODE_NONE && service.isLastTrack) { + service.pause() + service.seek(0) + } else { + service.position = service.nextPosition + service.prepareNextImpl() + service.notifyChange(META_CHANGED) + } + + TRACK_ENDED -> { + if (service.repeatMode == REPEAT_MODE_NONE && service.isLastTrack) { + service.notifyChange(PLAY_STATE_CHANGED) + service.seek(0) + } else { + service.playNextSong(false) + } + sendEmptyMessage(RELEASE_WAKELOCK) + } + + RELEASE_WAKELOCK -> service.releaseWakeLock() + + PLAY_SONG -> service.playSongAtImpl(msg.arg1) + + SET_POSITION -> { + service.openTrackAndPrepareNextAt(msg.arg1) + service.notifyChange(PLAY_STATE_CHANGED) + } + + PREPARE_NEXT -> service.prepareNextImpl() + + RESTORE_QUEUES -> service.restoreQueuesAndPositionIfNecessary() + + FOCUS_CHANGE -> when (msg.arg1) { + AudioManager.AUDIOFOCUS_GAIN -> { + if (!service.isPlaying && service.pausedByTransientLossOfFocus) { + service.play() + service.pausedByTransientLossOfFocus = false + } + removeMessages(DUCK) + sendEmptyMessage(UN_DUCK) + } + + AudioManager.AUDIOFOCUS_LOSS -> + // Lost focus for an unbounded amount of time: stop playback and release media playback + service.pause() + + AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { + // Lost focus for a short time, but we have to stop + // playback. We don't release the media playback because playback + // is likely to resume + val wasPlaying = service.isPlaying + service.pause() + service.pausedByTransientLossOfFocus = wasPlaying + } + + AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { + // Lost focus for a short time, but it's ok to keep playing + // at an attenuated level + removeMessages(UN_DUCK) + sendEmptyMessage(DUCK) + } + } + } + } + } + + inner class SongPlayCountHelper { + + private val stopWatch = StopWatch() + var song = Song.EMPTY_SONG + private set + + internal fun shouldBumpPlayCount(): Boolean { + return song.duration * 0.5 < stopWatch.elapsedTime + } + + internal fun notifySongChanged(song: Song) { + synchronized(this) { + stopWatch.reset() + this.song = song + } + } + + internal fun notifyPlayStateChanged(isPlaying: Boolean) { + synchronized(this) { + if (isPlaying) { + stopWatch.start() + } else { + stopWatch.pause() + } + } + } + } + + inner class MusicBinder : Binder() { + val service: MusicService + get() = this@MusicService + } + + inner class MediaStoreObserver internal constructor(private val mHandler: Handler) : ContentObserver(mHandler), Runnable { + + override fun onChange(selfChange: Boolean) { + // if a change is detected, remove any scheduled callback + // then post a new one. This is intended to prevent closely + // spaced events from generating multiple refresh calls + mHandler.removeCallbacks(this) + mHandler.postDelayed(this, 500) + } + + override fun run() { + // actually call refresh when the delayed callback fires + // do not send a sticky broadcast here + handleAndSendChangeInternal(MEDIA_STORE_CHANGED) + } + } + + inner class ThrottledSeekHandler internal constructor(private val mHandler: Handler) : Runnable { + + internal fun notifySeek() { + mHandler.removeCallbacks(this) + mHandler.postDelayed(this, 500) + } + + override fun run() { + savePositionInTrack() + sendPublicIntent(PLAY_STATE_CHANGED) // for musixmatch synced lyrics + } + } + + companion object { + val TAG: String = MusicService::class.java.simpleName + + const val SAVED_POSITION = "POSITION" + const val SAVED_POSITION_IN_TRACK = "POSITION_IN_TRACK" + const val SAVED_SHUFFLE_MODE = "SHUFFLE_MODE" + const val SAVED_REPEAT_MODE = "REPEAT_MODE" + + const val RELEASE_WAKELOCK = 0 + const val TRACK_ENDED = 1 + const val TRACK_WENT_TO_NEXT = 2 + const val PLAY_SONG = 3 + const val PREPARE_NEXT = 4 + const val SET_POSITION = 5 + const val RESTORE_QUEUES = 9 + const val SHUFFLE_MODE_NONE = 0 + const val SHUFFLE_MODE_SHUFFLE = 1 + const val REPEAT_MODE_NONE = 0 + const val REPEAT_MODE_ALL = 1 + const val REPEAT_MODE_THIS = 2 + const val SAVE_QUEUES = 0 + const val FOCUS_CHANGE = 6 + const val DUCK = 7 + const val UN_DUCK = 8 + const val MEDIA_SESSION_ACTIONS = (PlaybackStateCompat.ACTION_PLAY + or PlaybackStateCompat.ACTION_PAUSE + or PlaybackStateCompat.ACTION_PLAY_PAUSE + or PlaybackStateCompat.ACTION_SKIP_TO_NEXT + or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS + or PlaybackStateCompat.ACTION_STOP + or PlaybackStateCompat.ACTION_SEEK_TO) + + private fun getTrackUri(song: Song): String { + return MusicUtil.getSongFileUri(song.id).toString() + } + + private fun copy(bitmap: Bitmap): Bitmap? { + var config: Bitmap.Config? = bitmap.config + if (config == null) { + config = Bitmap.Config.RGB_565 + } + try { + return bitmap.copy(config, false) + } catch (e: OutOfMemoryError) { + e.printStackTrace() + return null + } + + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/WearBrowserService.java b/app/src/main/java/code/name/monkey/retromusic/service/WearBrowserService.java index 27072584..00c5ff7e 100644 --- a/app/src/main/java/code/name/monkey/retromusic/service/WearBrowserService.java +++ b/app/src/main/java/code/name/monkey/retromusic/service/WearBrowserService.java @@ -194,9 +194,9 @@ public class WearBrowserService extends MediaBrowserService { } else { switch (Integer.parseInt(Character.toString(parentId.charAt(0)))) { case TYPE_ARTIST: - List artistList = ArtistLoader.getAllArtists(mContext).blockingFirst(); + List artistList = ArtistLoader.INSTANCE.getAllArtists(mContext).blockingFirst(); for (Artist artist : artistList) { - String albumNmber = String.format("%d %s", artist.albums.size(), artist.albums.size() > 1 ? "Albums" : "Album"); + String albumNmber = String.format("%d %s", artist.getAlbums().size(), artist.getAlbums().size() > 1 ? "Albums" : "Album"); String songCount = String.format("%d %s", artist.getSongs().size(), artist.getSongs().size() > 1 ? "Songs" : "Song"); fillMediaItems(mediaItems, Integer.toString(TYPE_ARTIST_SONG_ALBUMS) + Long.toString(artist.getId()), @@ -215,9 +215,9 @@ public class WearBrowserService extends MediaBrowserService { Uri.parse("android.resource://code.name.monkey.retromusic/drawable/default_artist_art"), MediaBrowser.MediaItem.FLAG_BROWSABLE); - List artistAlbums = ArtistLoader.getArtist(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst().albums; //ArtistAlbumLoader.getAlbumsForArtist(mContext, Long.parseLong(parentId.substring(1))); + List artistAlbums = ArtistLoader.INSTANCE.getArtist(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst().getAlbums(); //ArtistAlbumLoader.getAlbumsForArtist(mContext, Long.parseLong(parentId.substring(1))); for (Album album : artistAlbums) { - String songCount = String.format("%d %s", album.songs.size(), album.songs.size() > 1 ? "Songs" : "Song"); + String songCount = String.format("%d %s", album.getSongs().size(), album.getSongs().size() > 1 ? "Songs" : "Song"); fillMediaItems(mediaItems, Integer.toString(TYPE_ALBUM_SONGS) + Long.toString(album.getId()), album.getTitle(), @@ -227,7 +227,7 @@ public class WearBrowserService extends MediaBrowserService { } break; case TYPE_ALBUM: - List albumList = AlbumLoader.getAllAlbums(mContext).blockingFirst(); + List albumList = AlbumLoader.Companion.getAllAlbums(mContext).blockingFirst(); for (Album album : albumList) { fillMediaItems(mediaItems, Integer.toString(TYPE_ALBUM_SONGS) + Long.toString(album.getId()), @@ -238,43 +238,43 @@ public class WearBrowserService extends MediaBrowserService { } break; case TYPE_SONG: - List songList = SongLoader.Companion.getAllSongs(mContext).blockingFirst(); + List songList = SongLoader.INSTANCE.getAllSongs(mContext).blockingFirst(); for (Song song : songList) { fillMediaItems(mediaItems, - String.valueOf(song.id), - song.title, - song.artistName, + String.valueOf(song.getId()), + song.getTitle(), + song.getArtistName(), Uri.parse("android.resource://code.name.monkey.retromusic/drawable/default_album_art"), MediaBrowser.MediaItem.FLAG_PLAYABLE); } break; case TYPE_ALBUM_SONGS: - List albumSongList = AlbumLoader.getAlbum(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst().songs; + List albumSongList = AlbumLoader.Companion.getAlbum(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst().getSongs(); for (Song song : albumSongList) { fillMediaItems(mediaItems, - String.valueOf(song.id), - song.title, - song.artistName, + String.valueOf(song.getId()), + song.getTitle(), + song.getArtistName(), Uri.parse("android.resource://code.name.monkey.retromusic/drawable/default_album_art"), MediaBrowser.MediaItem.FLAG_PLAYABLE); } break; case TYPE_ARTIST_ALL_SONGS: - List artistSongs = ArtistLoader.getArtist(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst().getSongs(); + List artistSongs = ArtistLoader.INSTANCE.getArtist(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst().getSongs(); for (Song song : artistSongs) { fillMediaItems(mediaItems, - String.valueOf(song.id), - song.title, - song.albumName, + String.valueOf(song.getId()), + song.getTitle(), + song.getAlbumName(), Uri.parse("android.resource://code.name.monkey.retromusic/drawable/default_album_art"), MediaBrowser.MediaItem.FLAG_PLAYABLE); } break; case TYPE_PLAYLIST: - List playlistList = PlaylistLoader.getAllPlaylists(mContext).blockingFirst(); + List playlistList = PlaylistLoader.INSTANCE.getAllPlaylists(mContext).blockingFirst(); for (Playlist playlist : playlistList) { - int size = PlaylistSongsLoader.getPlaylistSongList(mContext, playlist).blockingFirst().size(); + int size = PlaylistSongsLoader.INSTANCE.getPlaylistSongList(mContext, playlist).blockingFirst().size(); String songCount = String.format("%d %s", size, size > 1 ? "Songs" : "Song"); fillMediaItems(mediaItems, Integer.toString(TYPE_PLAYLIST_ALL_SONGS) + Long.toString(playlist.id), @@ -285,12 +285,12 @@ public class WearBrowserService extends MediaBrowserService { } break; case TYPE_PLAYLIST_ALL_SONGS: - List playlistSongs = PlaylistSongsLoader.getPlaylistSongList(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst(); + List playlistSongs = PlaylistSongsLoader.INSTANCE.getPlaylistSongList(mContext, Integer.parseInt(parentId.substring(1))).blockingFirst(); for (Song song : playlistSongs) { fillMediaItems(mediaItems, - String.valueOf(song.id), - song.title, - song.albumName, + String.valueOf(song.getId()), + song.getTitle(), + song.getAlbumName(), Uri.parse("android.resource://code.name.monkey.retromusic/drawable/default_album_art"), MediaBrowser.MediaItem.FLAG_PLAYABLE); } @@ -326,8 +326,8 @@ public class WearBrowserService extends MediaBrowserService { long songId = Long.parseLong(mediaId); setSessionActive(); ArrayList songs = new ArrayList<>(); - songs.add(SongLoader.Companion.getSong(mContext, Integer.parseInt(mediaId)).blockingFirst()); - MusicPlayerRemote.openQueue(songs, 0, true); + songs.add(SongLoader.INSTANCE.getSong(mContext, Integer.parseInt(mediaId)).blockingFirst()); + MusicPlayerRemote.INSTANCE.openQueue(songs, 0, true); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.java b/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.java deleted file mode 100644 index 134cd7e2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.java +++ /dev/null @@ -1,186 +0,0 @@ -package code.name.monkey.retromusic.service.daydream; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.service.dreams.DreamService; -import androidx.transition.TransitionManager; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.bumptech.glide.Glide; -import code.name.monkey.retromusic.loaders.SongLoader; -import code.name.monkey.retromusic.model.Song; - -import java.util.ArrayList; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import io.reactivex.Observable; -import io.reactivex.ObservableSource; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.Function; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by hemanths on 25/09/17. - */ - -public class RetroMusicAlbums extends DreamService { - @BindView(R.id.recycler_view) - RecyclerView mRecyclerView; - @BindView(R.id.title) - TextView mTitle; - @BindView(R.id.text) - TextView mText; - @BindView(R.id.title_container) - ViewGroup mViewGroup; - - private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - if (intent == null) { - return; - } - String artist = intent.getStringExtra("artist"); - String track = intent.getStringExtra("track"); - if (mViewGroup != null) { - mViewGroup.setVisibility(View.VISIBLE); - TransitionManager.beginDelayedTransition(mViewGroup); - if (mTitle != null) { - mTitle.setText(track); - } - if (mText != null) { - mText.setText(artist); - } - } - - } - }; - private Unbinder unbinder; - private CompositeDisposable mDisposable; - - @Override - public void onAttachedToWindow() { - super.onAttachedToWindow(); - - View view = LayoutInflater.from(this).inflate(R.layout.dream_service, null); - setContentView(view); - unbinder = ButterKnife.bind(this, view); - - mRecyclerView.setItemAnimator(new DefaultItemAnimator()); - GridLayoutManager layoutManager = new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false); - mRecyclerView.setLayoutManager(layoutManager); - - - mDisposable.add(getPlayingQueue() - .subscribeOn(Schedulers.computation()) - .observeOn(AndroidSchedulers.mainThread()) - .flatMap((Function, ObservableSource>>) songs -> Observable.create(e -> { - if (songs.isEmpty()) { - e.onNext(SongLoader.Companion.getAllSongs(RetroMusicAlbums.this).blockingFirst()); - } else { - e.onNext(songs); - } - e.onComplete(); - })) - .subscribe(songs -> { - if (songs.size() > 0) { - ImagesAdapter imagesAdapter = new ImagesAdapter(songs); - mRecyclerView.setAdapter(imagesAdapter); - } - })); - - } - - @Override - public void onCreate() { - super.onCreate(); - setInteractive(true); - setFullscreen(true); - - mDisposable = new CompositeDisposable(); - - IntentFilter iF = new IntentFilter(); - iF.addAction("com.android.music.musicservicecommand"); - iF.addAction("com.android.music.metachanged"); - registerReceiver(mBroadcastReceiver, iF); - - } - - @Override - public void onDestroy() { - super.onDestroy(); - unbinder.unbind(); - mDisposable.clear(); - unregisterReceiver(mBroadcastReceiver); - } - - private Observable> getPlayingQueue() { - return Observable.just(MusicPlayerRemote.getPlayingQueue()); - } - - class ImagesAdapter extends RecyclerView.Adapter { - - private final ArrayList list; - - public ImagesAdapter(ArrayList songs) { - this.list = songs; - } - - @Override - public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { - return new ViewHolder(LayoutInflater.from(getApplicationContext()) - .inflate(R.layout.image, viewGroup, false)); - } - - @Override - public void onBindViewHolder(ViewHolder holder, int i) { - Song song = list.get(i); - SongGlideRequest.Builder.from(Glide.with(getApplicationContext()), song) - .checkIgnoreMediaStore(getApplicationContext()) - .generatePalette(getApplicationContext()).build() - .override(400, 400) - .into(new RetroMusicColoredTarget(holder.image) { - - @Override - public void onColorReady(int color) { - - } - }); - - } - - @Override - public int getItemCount() { - return list.size(); - } - - class ViewHolder extends MediaEntryViewHolder { - - public ViewHolder(View itemView) { - super(itemView); - } - - @Override - public void onClick(View v) { - super.onClick(v); - MusicPlayerRemote.openQueue(list, getAdapterPosition(), true); - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.kt b/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.kt new file mode 100644 index 00000000..b8404c3c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.kt @@ -0,0 +1,161 @@ +package code.name.monkey.retromusic.service.daydream + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.service.dreams.DreamService +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.DefaultItemAnimator +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.transition.TransitionManager +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.Unbinder +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.loaders.SongLoader +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import com.bumptech.glide.Glide +import io.reactivex.Observable +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import java.util.* + +/** + * Created by hemanths on 25/09/17. + */ + +class RetroMusicAlbums : DreamService() { + @BindView(R.id.recycler_view) + internal var mRecyclerView: RecyclerView? = null + @BindView(R.id.title) + internal var mTitle: TextView? = null + @BindView(R.id.text) + internal var mText: TextView? = null + @BindView(R.id.title_container) + internal var mViewGroup: ViewGroup? = null + + private val mBroadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent?) { + if (intent == null) { + return + } + val artist = intent.getStringExtra("artist") + val track = intent.getStringExtra("track") + if (mViewGroup != null) { + mViewGroup!!.visibility = View.VISIBLE + TransitionManager.beginDelayedTransition(mViewGroup!!) + if (mTitle != null) { + mTitle!!.text = track + } + if (mText != null) { + mText!!.text = artist + } + } + + } + } + private var unbinder: Unbinder? = null + private var mDisposable: CompositeDisposable? = null + + private val playingQueue: Observable> + get() = Observable.just(MusicPlayerRemote.playingQueue) + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + + val view = LayoutInflater.from(this).inflate(R.layout.dream_service, null) + setContentView(view) + unbinder = ButterKnife.bind(this, view) + + mRecyclerView!!.itemAnimator = DefaultItemAnimator() + val layoutManager = GridLayoutManager(this, 4, RecyclerView.VERTICAL, false) + mRecyclerView!!.layoutManager = layoutManager + + + mDisposable!!.add(playingQueue + .subscribeOn(Schedulers.computation()) + .observeOn(AndroidSchedulers.mainThread()) + .flatMap { + return@flatMap Observable.create> { e -> + if (it.isEmpty()) { + e.onNext(SongLoader.getAllSongs(this@RetroMusicAlbums).blockingFirst()) + } else { + e.onNext(it) + } + e.onComplete() + } + } + .subscribe { songs -> + if (songs.size > 0) { + val imagesAdapter = ImagesAdapter(songs) + mRecyclerView!!.adapter = imagesAdapter + } + }) + + } + + override fun onCreate() { + super.onCreate() + isInteractive = true + isFullscreen = true + + mDisposable = CompositeDisposable() + + val iF = IntentFilter() + iF.addAction("com.android.music.musicservicecommand") + iF.addAction("com.android.music.metachanged") + registerReceiver(mBroadcastReceiver, iF) + + } + + override fun onDestroy() { + super.onDestroy() + unbinder!!.unbind() + mDisposable!!.clear() + unregisterReceiver(mBroadcastReceiver) + } + + internal inner class ImagesAdapter(private val list: ArrayList) : RecyclerView.Adapter() { + + override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { + return ViewHolder(LayoutInflater.from(applicationContext) + .inflate(R.layout.image, viewGroup, false)) + } + + override fun onBindViewHolder(holder: ViewHolder, i: Int) { + val song = list[i] + SongGlideRequest.Builder.from(Glide.with(applicationContext), song) + .checkIgnoreMediaStore(applicationContext) + .generatePalette(applicationContext).build() + .override(400, 400) + .into(object : RetroMusicColoredTarget(holder.image!!) { + override fun onColorReady(color: Int) { + + } + }) + + } + + override fun getItemCount(): Int { + return list.size + } + + internal inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + override fun onClick(v: View?) { + super.onClick(v) + MusicPlayerRemote.openQueue(list, adapterPosition, true) + } + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.java b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.java index 772029db..8cffe5f2 100644 --- a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.java +++ b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.java @@ -28,7 +28,6 @@ import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; import code.name.monkey.retromusic.model.Song; import code.name.monkey.retromusic.service.MusicService; import code.name.monkey.retromusic.ui.activities.MainActivity; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; import code.name.monkey.retromusic.util.PreferenceUtil; import code.name.monkey.retromusic.util.RetroColorUtil; import code.name.monkey.retromusic.util.RetroUtil; @@ -57,27 +56,27 @@ public class PlayingNotificationImpl extends PlayingNotification { final RemoteViews notificationLayoutBig = new RemoteViews(service.getPackageName(), R.layout.notification_big); - if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName)) { + if (TextUtils.isEmpty(song.getTitle()) && TextUtils.isEmpty(song.getArtistName())) { notificationLayout.setViewVisibility(R.id.media_titles, View.INVISIBLE); } else { notificationLayout.setViewVisibility(R.id.media_titles, View.VISIBLE); - notificationLayout.setTextViewText(R.id.title, song.title); - notificationLayout.setTextViewText(R.id.text, song.artistName); + notificationLayout.setTextViewText(R.id.title, song.getTitle()); + notificationLayout.setTextViewText(R.id.text, song.getArtistName()); } - if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName) && TextUtils - .isEmpty(song.albumName)) { + if (TextUtils.isEmpty(song.getTitle()) && TextUtils.isEmpty(song.getArtistName()) && TextUtils + .isEmpty(song.getAlbumName())) { notificationLayoutBig.setViewVisibility(R.id.media_titles, View.INVISIBLE); } else { notificationLayoutBig.setViewVisibility(R.id.media_titles, View.VISIBLE); - notificationLayoutBig.setTextViewText(R.id.title, song.title); - notificationLayoutBig.setTextViewText(R.id.text, song.artistName); - notificationLayoutBig.setTextViewText(R.id.text2, song.albumName); + notificationLayoutBig.setTextViewText(R.id.title, song.getTitle()); + notificationLayoutBig.setTextViewText(R.id.text, song.getArtistName()); + notificationLayoutBig.setTextViewText(R.id.text2, song.getAlbumName()); } linkButtons(notificationLayout, notificationLayoutBig); - Intent action = new Intent(service, NowPayingActivity.class); + Intent action = new Intent(service, MainActivity.class); action.putExtra("expand", true); action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.java b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.java index a361d23a..2efe0fbf 100644 --- a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.java +++ b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.java @@ -16,13 +16,12 @@ import com.bumptech.glide.request.target.SimpleTarget; import androidx.core.app.NotificationCompat; import androidx.media.app.NotificationCompat.MediaStyle; -import code.name.monkey.retromusic.Constants; import code.name.monkey.retromusic.R; import code.name.monkey.retromusic.glide.SongGlideRequest; import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; import code.name.monkey.retromusic.model.Song; import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; +import code.name.monkey.retromusic.ui.activities.MainActivity; import code.name.monkey.retromusic.util.PreferenceUtil; import code.name.monkey.retromusic.util.RetroColorUtil; @@ -43,14 +42,14 @@ public class PlayingNotificationImpl24 extends PlayingNotification { final int playButtonResId = isPlaying ? R.drawable.ic_pause_white_24dp : R.drawable.ic_play_arrow_white_24dp; - Intent action = new Intent(service, NowPayingActivity.class); + Intent action = new Intent(service, MainActivity.class); action.putExtra("expand", true); action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); final PendingIntent clickIntent = PendingIntent .getActivity(service, 0, action, PendingIntent.FLAG_UPDATE_CURRENT); final ComponentName serviceName = new ComponentName(service, MusicService.class); - Intent intent = new Intent(Constants.ACTION_QUIT); + Intent intent = new Intent(ACTION_QUIT); intent.setComponent(serviceName); final PendingIntent deleteIntent = PendingIntent.getService(service, 0, intent, 0); @@ -106,9 +105,9 @@ public class PlayingNotificationImpl24 extends PlayingNotification { .setLargeIcon(bitmap) .setContentIntent(clickIntent) .setDeleteIntent(deleteIntent) - .setContentTitle(Html.fromHtml("" + song.title + "")) - .setContentText(song.artistName) - .setSubText(Html.fromHtml("" + song.albumName + "")) + .setContentTitle(Html.fromHtml("" + song.getTitle() + "")) + .setContentText(song.getArtistName()) + .setSubText(Html.fromHtml("" + song.getAlbumName() + "")) .setOngoing(isPlaying) .setShowWhen(false) .addAction(previousAction) diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationOreo.java b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationOreo.java deleted file mode 100644 index fdbf1a3c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationOreo.java +++ /dev/null @@ -1,248 +0,0 @@ -package code.name.monkey.retromusic.service.notification; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.res.TypedArray; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.widget.RemoteViews; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; -import com.bumptech.glide.request.target.Target; - -import androidx.annotation.Nullable; -import androidx.core.app.NotificationCompat; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.util.color.MediaNotificationProcessor; - -import static code.name.monkey.retromusic.Constants.ACTION_QUIT; -import static code.name.monkey.retromusic.Constants.ACTION_REWIND; -import static code.name.monkey.retromusic.Constants.ACTION_SKIP; -import static code.name.monkey.retromusic.Constants.ACTION_TOGGLE_PAUSE; -import static code.name.monkey.retromusic.util.RetroUtil.createBitmap; - -/** - * @author Hemanth S (h4h13). - */ -public class PlayingNotificationOreo extends PlayingNotification { - - private Target target; - - private RemoteViews getCombinedRemoteViews(boolean collapsed, Song song) { - RemoteViews remoteViews = new RemoteViews(service.getPackageName(), - collapsed ? R.layout.layout_notification_collapsed : R.layout.layout_notification_expanded); - - remoteViews.setTextViewText(R.id.appName, - service.getString(R.string.app_name) + " • " + song.albumName); - remoteViews.setTextViewText(R.id.title, song.title); - remoteViews.setTextViewText(R.id.subtitle, song.artistName); - - TypedArray typedArray = service - .obtainStyledAttributes(new int[]{android.R.attr.selectableItemBackground}); - int selectableItemBackground = typedArray.getResourceId(0, 0); - typedArray.recycle(); - - remoteViews.setInt(R.id.content, "setBackgroundResource", selectableItemBackground); - - linkButtons(remoteViews); - - //setNotificationContent(remoteViews, ColorUtil.isColorLight(backgroundColor)); - return remoteViews; - } - - @Override - public void update() { - stopped = false; - final Song song = service.getCurrentSong(); - final boolean isPlaying = service.isPlaying(); - - final RemoteViews notificationLayout = getCombinedRemoteViews(true, song); - final RemoteViews notificationLayoutBig = getCombinedRemoteViews(false, song); - - Intent action = new Intent(service, NowPayingActivity.class); - action.putExtra("expand", true); - action.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - - final PendingIntent clickIntent = PendingIntent - .getActivity(service, 0, action, PendingIntent.FLAG_UPDATE_CURRENT); - final PendingIntent deleteIntent = buildPendingIntent(service, ACTION_QUIT, null); - - final NotificationCompat.Builder builder = new NotificationCompat.Builder(service, - NOTIFICATION_CHANNEL_ID) - .setSmallIcon(R.drawable.ic_notification) - .setContentIntent(clickIntent) - .setDeleteIntent(deleteIntent) - .setCategory(NotificationCompat.CATEGORY_SERVICE) - .setPriority(NotificationCompat.PRIORITY_MAX) - .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) - .setCustomContentView(notificationLayout) - .setCustomBigContentView(notificationLayoutBig) - .setOngoing(isPlaying); - - final int bigNotificationImageSize = service.getResources() - .getDimensionPixelSize(R.dimen.notification_big_image_size); - service.runOnUiThread(new Runnable() { - @Override - public void run() { - if (target != null) { - Glide.clear(target); - } - target = SongGlideRequest.Builder.from(Glide.with(service), song) - .checkIgnoreMediaStore(service) - .generatePalette(service).build() - .into(new SimpleTarget(bigNotificationImageSize, - bigNotificationImageSize) { - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - - MediaNotificationProcessor mediaNotificationProcessor = new MediaNotificationProcessor( - service, service, (i, i2) -> update(resource.getBitmap(), i, i2)); - mediaNotificationProcessor.processNotification(resource.getBitmap()); - - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - update(null, Color.WHITE, Color.BLACK); - } - - private void update(@Nullable Bitmap bitmap, int bgColor, int textColor) { - if (bitmap != null) { - notificationLayout.setImageViewBitmap(R.id.largeIcon, bitmap); - notificationLayoutBig.setImageViewBitmap(R.id.largeIcon, bitmap); - } else { - notificationLayout - .setImageViewResource(R.id.largeIcon, R.drawable.default_album_art); - notificationLayoutBig - .setImageViewResource(R.id.largeIcon, R.drawable.default_album_art); - } - - if (!PreferenceUtil.getInstance().coloredNotification()) { - bgColor = Color.WHITE; - } - setBackgroundColor(bgColor); - setNotificationContent(ColorUtil.isColorLight(bgColor)); - - if (stopped) { - return; // notification has been stopped before loading was finished - } - updateNotifyModeAndPostNotification(builder.build()); - } - - private void setBackgroundColor(int color) { - - notificationLayout.setInt(R.id.image, "setBackgroundColor", color); - notificationLayoutBig.setInt(R.id.image, "setBackgroundColor", color); - - notificationLayout.setInt(R.id.foregroundImage, "setColorFilter", color); - notificationLayoutBig.setInt(R.id.foregroundImage, "setColorFilter", color); - } - - private void setNotificationContent(boolean dark) { - int primary = MaterialValueHelper.getPrimaryTextColor(service, dark); - int secondary = MaterialValueHelper.getSecondaryTextColor(service, dark); - - Bitmap close = createBitmap( - RetroUtil - .getTintedVectorDrawable(service, R.drawable.ic_close_white_24dp, primary), - NOTIFICATION_CONTROLS_SIZE_MULTIPLIER); - Bitmap prev = createBitmap( - RetroUtil - .getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - primary), NOTIFICATION_CONTROLS_SIZE_MULTIPLIER); - Bitmap next = createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - primary), NOTIFICATION_CONTROLS_SIZE_MULTIPLIER); - Bitmap playPause = createBitmap(RetroUtil.getTintedVectorDrawable(service, - isPlaying ? R.drawable.ic_pause_white_24dp - : R.drawable.ic_play_arrow_white_24dp, primary), - NOTIFICATION_CONTROLS_SIZE_MULTIPLIER); - - notificationLayout.setTextColor(R.id.title, primary); - notificationLayout.setTextColor(R.id.subtitle, secondary); - notificationLayout.setTextColor(R.id.appName, secondary); - - notificationLayout.setImageViewBitmap(R.id.action_prev, prev); - notificationLayout.setImageViewBitmap(R.id.action_next, next); - notificationLayout.setImageViewBitmap(R.id.action_play_pause, playPause); - - notificationLayoutBig.setTextColor(R.id.title, primary); - notificationLayoutBig.setTextColor(R.id.subtitle, secondary); - notificationLayoutBig.setTextColor(R.id.appName, secondary); - - notificationLayoutBig.setImageViewBitmap(R.id.action_quit, close); - notificationLayoutBig.setImageViewBitmap(R.id.action_prev, prev); - notificationLayoutBig.setImageViewBitmap(R.id.action_next, next); - notificationLayoutBig.setImageViewBitmap(R.id.action_play_pause, playPause); - - notificationLayout.setImageViewBitmap(R.id.smallIcon, - createBitmap(RetroUtil - .getTintedVectorDrawable(service, R.drawable.ic_notification, secondary), - 0.6f)); - notificationLayoutBig.setImageViewBitmap(R.id.smallIcon, - createBitmap(RetroUtil - .getTintedVectorDrawable(service, R.drawable.ic_notification, secondary), - 0.6f)); - - notificationLayout.setInt(R.id.arrow, "setColorFilter", secondary); - notificationLayoutBig.setInt(R.id.arrow, "setColorFilter", secondary); - - } - }); - } - }); - - if (stopped) { - return; // notification has been stopped before loading was finished - } - updateNotifyModeAndPostNotification(builder.build()); - } - - - private PendingIntent buildPendingIntent(Context context, final String action, - final ComponentName serviceName) { - Intent intent = new Intent(action); - intent.setComponent(serviceName); - return PendingIntent.getService(context, 0, intent, 0); - } - - - private void linkButtons(final RemoteViews notificationLayout) { - PendingIntent pendingIntent; - - final ComponentName serviceName = new ComponentName(service, MusicService.class); - - // Previous track - pendingIntent = buildPendingIntent(service, ACTION_REWIND, serviceName); - notificationLayout.setOnClickPendingIntent(R.id.action_prev, pendingIntent); - - // Play and pause - pendingIntent = buildPendingIntent(service, ACTION_TOGGLE_PAUSE, serviceName); - notificationLayout.setOnClickPendingIntent(R.id.action_play_pause, pendingIntent); - - // Next track - pendingIntent = buildPendingIntent(service, ACTION_SKIP, serviceName); - notificationLayout.setOnClickPendingIntent(R.id.action_next, pendingIntent); - - // Close - pendingIntent = buildPendingIntent(service, ACTION_QUIT, serviceName); - notificationLayout.setOnClickPendingIntent(R.id.action_quit, pendingIntent); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationOreo.kt b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationOreo.kt new file mode 100644 index 00000000..85b5aa40 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationOreo.kt @@ -0,0 +1,221 @@ +package code.name.monkey.retromusic.service.notification + +import android.app.PendingIntent +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.Color +import android.graphics.drawable.Drawable +import android.widget.RemoteViews +import androidx.core.app.NotificationCompat +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.MaterialValueHelper +import code.name.monkey.retromusic.Constants.ACTION_QUIT +import code.name.monkey.retromusic.Constants.ACTION_REWIND +import code.name.monkey.retromusic.Constants.ACTION_SKIP +import code.name.monkey.retromusic.Constants.ACTION_TOGGLE_PAUSE +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.service.MusicService +import code.name.monkey.retromusic.ui.activities.MainActivity +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import code.name.monkey.retromusic.util.RetroUtil.createBitmap +import code.name.monkey.retromusic.util.color.MediaNotificationProcessor +import com.bumptech.glide.Glide +import com.bumptech.glide.request.animation.GlideAnimation +import com.bumptech.glide.request.target.SimpleTarget +import com.bumptech.glide.request.target.Target + +/** + * @author Hemanth S (h4h13). + */ +class PlayingNotificationOreo : PlayingNotification() { + + private var target: Target? = null + + private fun getCombinedRemoteViews(collapsed: Boolean, song: Song): RemoteViews { + val remoteViews = RemoteViews(service.packageName, + if (collapsed) R.layout.layout_notification_collapsed else R.layout.layout_notification_expanded) + + remoteViews.setTextViewText(R.id.appName, service.getString(R.string.app_name) + " • " + song.albumName) + remoteViews.setTextViewText(R.id.title, song.title) + remoteViews.setTextViewText(R.id.subtitle, song.artistName) + + val typedArray = service.obtainStyledAttributes(intArrayOf(android.R.attr.selectableItemBackground)) + val selectableItemBackground = typedArray.getResourceId(0, 0) + typedArray.recycle() + + remoteViews.setInt(R.id.content, "setBackgroundResource", selectableItemBackground) + + linkButtons(remoteViews) + + //setNotificationContent(remoteViews, ColorUtil.isColorLight(backgroundColor)); + return remoteViews + } + + override fun update() { + stopped = false + val song = service.currentSong + val isPlaying = service.isPlaying + + val notificationLayout = getCombinedRemoteViews(true, song) + val notificationLayoutBig = getCombinedRemoteViews(false, song) + + val action = Intent(service, MainActivity::class.java) + action.putExtra("expand", true) + action.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP + + val clickIntent = PendingIntent + .getActivity(service, 0, action, PendingIntent.FLAG_UPDATE_CURRENT) + val deleteIntent = buildPendingIntent(service, ACTION_QUIT, null) + + val builder = NotificationCompat.Builder(service, + PlayingNotification.NOTIFICATION_CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentIntent(clickIntent) + .setDeleteIntent(deleteIntent) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .setPriority(NotificationCompat.PRIORITY_MAX) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setCustomContentView(notificationLayout) + .setCustomBigContentView(notificationLayoutBig) + .setOngoing(isPlaying) + + val bigNotificationImageSize = service.resources + .getDimensionPixelSize(R.dimen.notification_big_image_size) + service.runOnUiThread(Runnable { + if (target != null) { + Glide.clear(target!!) + } + target = SongGlideRequest.Builder.from(Glide.with(service), song) + .checkIgnoreMediaStore(service) + .generatePalette(service).build() + .into(object : SimpleTarget(bigNotificationImageSize, + bigNotificationImageSize) { + override fun onResourceReady(resource: BitmapPaletteWrapper, + glideAnimation: GlideAnimation) { + + val mediaNotificationProcessor = MediaNotificationProcessor( + service, service) { i, _ -> update(resource.bitmap, i) } + mediaNotificationProcessor.processNotification(resource.bitmap) + + } + + override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) { + super.onLoadFailed(e, errorDrawable) + update(null, Color.WHITE) + } + + private fun update(bitmap: Bitmap?, bgColor: Int) { + var bgColorFinal = bgColor + if (bitmap != null) { + notificationLayout.setImageViewBitmap(R.id.largeIcon, bitmap) + notificationLayoutBig.setImageViewBitmap(R.id.largeIcon, bitmap) + } else { + notificationLayout.setImageViewResource(R.id.largeIcon, R.drawable.default_album_art) + notificationLayoutBig.setImageViewResource(R.id.largeIcon, R.drawable.default_album_art) + } + + if (!PreferenceUtil.getInstance().coloredNotification()) { + bgColorFinal = Color.WHITE + } + setBackgroundColor(bgColorFinal) + setNotificationContent(ColorUtil.isColorLight(bgColorFinal)) + + if (stopped) { + return // notification has been stopped before loading was finished + } + updateNotifyModeAndPostNotification(builder.build()) + } + + private fun setBackgroundColor(color: Int) { + + notificationLayout.setInt(R.id.image, "setBackgroundColor", color) + notificationLayoutBig.setInt(R.id.image, "setBackgroundColor", color) + + notificationLayout.setInt(R.id.foregroundImage, "setColorFilter", color) + notificationLayoutBig.setInt(R.id.foregroundImage, "setColorFilter", color) + } + + private fun setNotificationContent(dark: Boolean) { + val primary = MaterialValueHelper.getPrimaryTextColor(service, dark) + val secondary = MaterialValueHelper.getSecondaryTextColor(service, dark) + + val close = createBitmap(RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_close_white_24dp, primary)!!, PlayingNotification.NOTIFICATION_CONTROLS_SIZE_MULTIPLIER) + val prev = createBitmap(RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, primary)!!, PlayingNotification.NOTIFICATION_CONTROLS_SIZE_MULTIPLIER) + val next = createBitmap(RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, primary)!!, PlayingNotification.NOTIFICATION_CONTROLS_SIZE_MULTIPLIER) + val playPause = createBitmap(RetroUtil.getTintedVectorDrawable(service, + if (isPlaying) + R.drawable.ic_pause_white_24dp + else + R.drawable.ic_play_arrow_white_24dp, primary)!!, PlayingNotification.NOTIFICATION_CONTROLS_SIZE_MULTIPLIER) + + notificationLayout.setTextColor(R.id.title, primary) + notificationLayout.setTextColor(R.id.subtitle, secondary) + notificationLayout.setTextColor(R.id.appName, secondary) + + notificationLayout.setImageViewBitmap(R.id.action_prev, prev) + notificationLayout.setImageViewBitmap(R.id.action_next, next) + notificationLayout.setImageViewBitmap(R.id.action_play_pause, playPause) + + notificationLayoutBig.setTextColor(R.id.title, primary) + notificationLayoutBig.setTextColor(R.id.subtitle, secondary) + notificationLayoutBig.setTextColor(R.id.appName, secondary) + + notificationLayoutBig.setImageViewBitmap(R.id.action_quit, close) + notificationLayoutBig.setImageViewBitmap(R.id.action_prev, prev) + notificationLayoutBig.setImageViewBitmap(R.id.action_next, next) + notificationLayoutBig.setImageViewBitmap(R.id.action_play_pause, playPause) + + notificationLayout.setImageViewBitmap(R.id.smallIcon, createBitmap(RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_notification, secondary)!!, 0.6f)) + notificationLayoutBig.setImageViewBitmap(R.id.smallIcon, createBitmap(RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_notification, secondary)!!, 0.6f)) + + notificationLayout.setInt(R.id.arrow, "setColorFilter", secondary) + notificationLayoutBig.setInt(R.id.arrow, "setColorFilter", secondary) + + } + }) + }) + + if (stopped) { + return // notification has been stopped before loading was finished + } + updateNotifyModeAndPostNotification(builder.build()) + } + + + private fun buildPendingIntent(context: Context, action: String, + serviceName: ComponentName?): PendingIntent { + val intent = Intent(action) + intent.component = serviceName + return PendingIntent.getService(context, 0, intent, 0) + } + + + private fun linkButtons(notificationLayout: RemoteViews) { + var pendingIntent: PendingIntent + + val serviceName = ComponentName(service, MusicService::class.java) + + // Previous track + pendingIntent = buildPendingIntent(service, ACTION_REWIND, serviceName) + notificationLayout.setOnClickPendingIntent(R.id.action_prev, pendingIntent) + + // Play and pause + pendingIntent = buildPendingIntent(service, ACTION_TOGGLE_PAUSE, serviceName) + notificationLayout.setOnClickPendingIntent(R.id.action_play_pause, pendingIntent) + + // Next track + pendingIntent = buildPendingIntent(service, ACTION_SKIP, serviceName) + notificationLayout.setOnClickPendingIntent(R.id.action_next, pendingIntent) + + // Close + pendingIntent = buildPendingIntent(service, ACTION_QUIT, serviceName) + notificationLayout.setOnClickPendingIntent(R.id.action_quit, pendingIntent) + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.java index fab16387..4d94c2d3 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; import androidx.appcompat.widget.Toolbar; @@ -30,7 +31,6 @@ import butterknife.ButterKnife; import butterknife.OnClick; import code.name.monkey.appthemehelper.ThemeStore; import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.Constants; import code.name.monkey.retromusic.R; import code.name.monkey.retromusic.model.Contributor; import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; @@ -38,7 +38,10 @@ import code.name.monkey.retromusic.ui.adapter.ContributorAdapter; import code.name.monkey.retromusic.util.NavigationUtil; import static code.name.monkey.retromusic.Constants.APP_INSTAGRAM_LINK; +import static code.name.monkey.retromusic.Constants.APP_TELEGRAM_LINK; import static code.name.monkey.retromusic.Constants.APP_TWITTER_LINK; +import static code.name.monkey.retromusic.Constants.DISCORD_LINK; +import static code.name.monkey.retromusic.Constants.FAQ_LINK; import static code.name.monkey.retromusic.Constants.GITHUB_PROJECT; import static code.name.monkey.retromusic.Constants.GOOGLE_PLUS_COMMUNITY; import static code.name.monkey.retromusic.Constants.RATE_ON_GOOGLE_PLAY; @@ -115,13 +118,13 @@ public class AboutActivity extends AbsBaseActivity { public void onViewClicked(View view) { switch (view.getId()) { case R.id.faq_link: - openUrl(Constants.FAQ_LINK); + openUrl(FAQ_LINK); break; case R.id.telegram_link: - openUrl(Constants.APP_TELEGRAM_LINK); + openUrl(APP_TELEGRAM_LINK); break; case R.id.discord_link: - openUrl(Constants.DISCORD_LINK); + openUrl(DISCORD_LINK); break; case R.id.app_github: openUrl(GITHUB_PROJECT); @@ -200,7 +203,7 @@ public class AboutActivity extends AbsBaseActivity { }.getType(); List contributors = new Gson().fromJson(data, type); - ContributorAdapter contributorAdapter = new ContributorAdapter(contributors); + ContributorAdapter contributorAdapter = new ContributorAdapter((ArrayList) contributors); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(contributorAdapter); diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AlbumDetailsActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AlbumDetailsActivity.java deleted file mode 100644 index 2c7c868e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AlbumDetailsActivity.java +++ /dev/null @@ -1,426 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.Intent; -import android.graphics.Color; -import android.os.Bundle; -import android.transition.Slide; -import android.view.Gravity; -import android.view.Menu; -import android.view.MenuItem; -import android.view.SubMenu; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AnimationUtils; -import android.widget.ImageView; -import android.widget.TextView; - -import com.bumptech.glide.Glide; -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.appbar.CollapsingToolbarLayout; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatTextView; -import androidx.appcompat.widget.Toolbar; -import androidx.core.app.ActivityCompat; -import androidx.core.util.Pair; -import androidx.core.widget.NestedScrollView; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog; -import code.name.monkey.retromusic.dialogs.DeleteSongsDialog; -import code.name.monkey.retromusic.glide.ArtistGlideRequest; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.SortOrder.AlbumSongSortOrder; -import code.name.monkey.retromusic.loaders.ArtistLoader; -import code.name.monkey.retromusic.misc.AppBarStateChangeListener; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.contract.AlbumDetailsContract; -import code.name.monkey.retromusic.mvp.presenter.AlbumDetailsPresenter; -import code.name.monkey.retromusic.ui.activities.base.AbsSlidingMusicPanelActivity; -import code.name.monkey.retromusic.ui.activities.tageditor.AbsTagEditorActivity; -import code.name.monkey.retromusic.ui.activities.tageditor.AlbumTagEditorActivity; -import code.name.monkey.retromusic.ui.adapter.album.AlbumAdapter; -import code.name.monkey.retromusic.ui.adapter.album.HorizontalAlbumAdapter; -import code.name.monkey.retromusic.ui.adapter.song.SimpleSongAdapter; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.views.CollapsingFAB; - -public class AlbumDetailsActivity extends AbsSlidingMusicPanelActivity implements - AlbumDetailsContract.AlbumDetailsView { - - public static final String EXTRA_ALBUM_ID = "extra_album_id"; - private static final int TAG_EDITOR_REQUEST = 2001; - - @BindView(R.id.image) - ImageView image; - - @BindView(R.id.recycler_view) - RecyclerView recyclerView; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.song_title) - AppCompatTextView songTitle; - - @BindView(R.id.action_shuffle_all) - CollapsingFAB shuffleButton; - - @BindView(R.id.collapsing_toolbar) - @Nullable - CollapsingToolbarLayout collapsingToolbarLayout; - - @BindView(R.id.app_bar) - @Nullable - AppBarLayout appBarLayout; - - @BindView(R.id.content) - NestedScrollView contentContainer; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.more_recycler_view) - RecyclerView moreRecyclerView; - - @BindView(R.id.more_title) - TextView moreTitle; - - @BindView(R.id.artist_image) - @Nullable - ImageView artistImage; - - private AlbumDetailsPresenter albumDetailsPresenter; - - private SimpleSongAdapter adapter; - private Album album; - - @Override - protected View createContentView() { - return wrapSlidingMusicPanel(R.layout.activity_album); - } - - void setupWindowTransition() { - Slide slide = new Slide(Gravity.BOTTOM); - slide.setInterpolator( - AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in)); - getWindow().setEnterTransition(slide); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - setDrawUnderStatusBar(); - setupWindowTransition(); - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - - toggleBottomNavigationView(true); - setLightNavigationBar(true); - setNavigationbarColorAuto(); - - ActivityCompat.postponeEnterTransition(this); - - int albumId = getIntent().getIntExtra(EXTRA_ALBUM_ID, -1); - albumDetailsPresenter = new AlbumDetailsPresenter(this, albumId); - albumDetailsPresenter.subscribe(); - - setupRecyclerView(); - setupToolbarMarginHeight(); - - contentContainer.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> { - if (scrollY > oldScrollY) { - shuffleButton.setShowTitle(false); - } - if (scrollY < oldScrollY) { - shuffleButton.setShowTitle(true); - } - }); - - - } - - private void setupRecyclerView() { - adapter = new SimpleSongAdapter(this, new ArrayList<>(), R.layout.item_song); - recyclerView.setLayoutManager(new LinearLayoutManager(this)); - recyclerView.setItemAnimator(new DefaultItemAnimator()); - recyclerView.setNestedScrollingEnabled(false); - recyclerView.setAdapter(adapter); - - } - - private void setupToolbarMarginHeight() { - int primaryColor = ThemeStore.primaryColor(this); - TintHelper.setTintAuto(contentContainer, primaryColor, true); - if (collapsingToolbarLayout != null) { - collapsingToolbarLayout.setContentScrimColor(primaryColor); - collapsingToolbarLayout.setStatusBarScrimColor(ColorUtil.darkenColor(primaryColor)); - } - - toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp); - setSupportActionBar(toolbar); - //noinspection ConstantConditions - getSupportActionBar().setTitle(null); - - - if (toolbar != null && !PreferenceUtil.getInstance().getFullScreenMode()) { - ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams(); - params.topMargin = RetroUtil.getStatusBarHeight( ); - toolbar.setLayoutParams(params); - } - - if (appBarLayout != null) { - appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() { - @Override - public void onStateChanged(AppBarLayout appBarLayout, State state) { - int color; - switch (state) { - case COLLAPSED: - setLightStatusbar(ColorUtil.isColorLight(ThemeStore.primaryColor(AlbumDetailsActivity.this))); - color = ThemeStore.primaryColor(AlbumDetailsActivity.this); - break; - default: - case EXPANDED: - case IDLE: - setLightStatusbar(false); - color = Color.TRANSPARENT; - break; - } - ToolbarContentTintHelper.setToolbarContentColorBasedOnToolbarColor(AlbumDetailsActivity.this, toolbar, color); - } - }); - } - } - - @OnClick({R.id.action_shuffle_all, R.id.artist_image}) - public void onViewClicked(View view) { - switch (view.getId()) { - case R.id.artist_image: - Pair[] artistPairs = new Pair[]{Pair.create(image, - getResources().getString(R.string.transition_artist_image))}; - NavigationUtil.goToArtist(this, getAlbum().getArtistId(), - artistPairs); - break; - case R.id.action_shuffle_all: - if (getAlbum().songs != null) { - MusicPlayerRemote.openAndShuffleQueue(getAlbum().songs, true); - } - break; - } - } - - @Override - protected void onPause() { - super.onPause(); - albumDetailsPresenter.unsubscribe(); - } - - @Override - public void loading() { - - } - - @Override - public void showEmptyView() { - - } - - @Override - public void completed() { - ActivityCompat.startPostponedEnterTransition(this); - } - - @Override - public void showData(Album album) { - if (album.songs.isEmpty()) { - finish(); - return; - } - this.album = album; - - title.setText(album.getTitle()); - text.setText(String.format("%s%s • %s", album.getArtistName(), - " • " + MusicUtil.getYearString(album.getYear()), - MusicUtil.getReadableDurationString(MusicUtil.getTotalDuration(this, album.songs)))); - - loadAlbumCover(); - loadMoreFrom(album); - adapter.swapDataSet(album.songs); - } - - private void loadMoreFrom(Album album) { - if (artistImage != null) { - ArtistGlideRequest.Builder.from(Glide.with(this), - ArtistLoader.getArtist(this, album.getArtistId()).blockingFirst()) - .forceDownload(false) - .generatePalette(this).build() - .dontAnimate() - .into(new RetroMusicColoredTarget(artistImage) { - @Override - public void onColorReady(int color) { - //setColors(color); - } - }); - } - - ArrayList albums = ArtistLoader.getArtist(this, album.getArtistId()) - .blockingFirst().albums; - albums.remove(album); - if (!albums.isEmpty()) { - moreTitle.setVisibility(View.VISIBLE); - moreRecyclerView.setVisibility(View.VISIBLE); - } else { - return; - } - moreTitle.setText(String.format("More from %s", album.getArtistName())); - - AlbumAdapter albumAdapter = new HorizontalAlbumAdapter(this, albums, false, null); - moreRecyclerView.setLayoutManager(new GridLayoutManager(this, 1, GridLayoutManager.HORIZONTAL, false)); - moreRecyclerView.setAdapter(albumAdapter); - } - - public Album getAlbum() { - return album; - } - - private void loadAlbumCover() { - SongGlideRequest.Builder.from(Glide.with(this), getAlbum().safeGetFirstSong()) - .checkIgnoreMediaStore(this) - .generatePalette(this).build() - .dontAnimate() - .into(new RetroMusicColoredTarget(image) { - @Override - public void onColorReady(int color) { - setColors(color); - } - }); - } - - private void setColors(int color) { - int themeColor = - PreferenceUtil.getInstance().getAdaptiveColor() ? color : ThemeStore.accentColor(this); - songTitle.setTextColor(themeColor); - moreTitle.setTextColor(themeColor); - - shuffleButton.setColor(themeColor); - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.menu_album_detail, menu); - MenuItem sortOrder = menu.findItem(R.id.action_sort_order); - setUpSortOrderMenu(sortOrder.getSubMenu()); - return super.onCreateOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - return handleSortOrderMenuItem(item); - } - - private boolean handleSortOrderMenuItem(@NonNull MenuItem item) { - String sortOrder = null; - final ArrayList songs = adapter.getDataSet(); - switch (item.getItemId()) { - case R.id.action_play_next: - MusicPlayerRemote.playNext(songs); - return true; - case R.id.action_add_to_current_playing: - MusicPlayerRemote.enqueue(songs); - return true; - case R.id.action_add_to_playlist: - AddToPlaylistDialog.create(songs).show(getSupportFragmentManager(), "ADD_PLAYLIST"); - return true; - case R.id.action_delete_from_device: - DeleteSongsDialog.create(songs).show(getSupportFragmentManager(), "DELETE_SONGS"); - return true; - case android.R.id.home: - super.onBackPressed(); - return true; - case R.id.action_tag_editor: - Intent intent = new Intent(this, AlbumTagEditorActivity.class); - intent.putExtra(AbsTagEditorActivity.EXTRA_ID, getAlbum().getId()); - startActivityForResult(intent, TAG_EDITOR_REQUEST); - return true; - case R.id.action_go_to_artist: - NavigationUtil.goToArtist(this, getAlbum().getArtistId()); - return true; - /*Sort*/ - case R.id.action_sort_order_title: - sortOrder = AlbumSongSortOrder.SONG_A_Z; - break; - case R.id.action_sort_order_title_desc: - sortOrder = AlbumSongSortOrder.SONG_Z_A; - break; - case R.id.action_sort_order_track_list: - sortOrder = AlbumSongSortOrder.SONG_TRACK_LIST; - break; - case R.id.action_sort_order_artist_song_duration: - sortOrder = AlbumSongSortOrder.SONG_DURATION; - break; - } - if (sortOrder != null) { - item.setChecked(true); - setSaveSortOrder(sortOrder); - } - return true; - } - - private String getSavedSortOrder() { - return PreferenceUtil.getInstance().getAlbumDetailSongSortOrder(); - } - - private void setUpSortOrderMenu(@NonNull SubMenu sortOrder) { - switch (getSavedSortOrder()) { - case AlbumSongSortOrder.SONG_A_Z: - sortOrder.findItem(R.id.action_sort_order_title).setChecked(true); - break; - case AlbumSongSortOrder.SONG_Z_A: - sortOrder.findItem(R.id.action_sort_order_title_desc).setChecked(true); - break; - case AlbumSongSortOrder.SONG_TRACK_LIST: - sortOrder.findItem(R.id.action_sort_order_track_list).setChecked(true); - break; - case AlbumSongSortOrder.SONG_DURATION: - sortOrder.findItem(R.id.action_sort_order_artist_song_duration).setChecked(true); - break; - } - } - - private void setSaveSortOrder(String sortOrder) { - PreferenceUtil.getInstance().setAlbumDetailSongSortOrder(sortOrder); - reload(); - } - - @Override - public void onMediaStoreChanged() { - super.onMediaStoreChanged(); - reload(); - } - - private void reload() { - albumDetailsPresenter.subscribe(); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AlbumDetailsActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AlbumDetailsActivity.kt new file mode 100644 index 00000000..af628a2c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AlbumDetailsActivity.kt @@ -0,0 +1,338 @@ +package code.name.monkey.retromusic.ui.activities + +import android.content.Intent +import android.graphics.Color +import android.os.Bundle +import android.transition.Slide +import android.view.* +import android.view.animation.AnimationUtils +import androidx.core.app.ActivityCompat +import androidx.core.util.Pair +import androidx.core.widget.NestedScrollView +import androidx.recyclerview.widget.DefaultItemAnimator +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.LinearLayoutManager +import butterknife.ButterKnife +import butterknife.OnClick +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog +import code.name.monkey.retromusic.dialogs.DeleteSongsDialog +import code.name.monkey.retromusic.glide.ArtistGlideRequest +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.SortOrder.AlbumSongSortOrder +import code.name.monkey.retromusic.loaders.ArtistLoader +import code.name.monkey.retromusic.misc.AppBarStateChangeListener +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.mvp.contract.AlbumDetailsContract +import code.name.monkey.retromusic.mvp.presenter.AlbumDetailsPresenter +import code.name.monkey.retromusic.ui.activities.base.AbsSlidingMusicPanelActivity +import code.name.monkey.retromusic.ui.activities.tageditor.AbsTagEditorActivity +import code.name.monkey.retromusic.ui.activities.tageditor.AlbumTagEditorActivity +import code.name.monkey.retromusic.ui.adapter.album.HorizontalAlbumAdapter +import code.name.monkey.retromusic.ui.adapter.song.SimpleSongAdapter +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import code.name.monkey.retromusic.views.CircularImageView +import com.bumptech.glide.Glide +import com.google.android.material.appbar.AppBarLayout +import kotlinx.android.synthetic.main.activity_album.* +import kotlinx.android.synthetic.main.activity_album_content.* +import java.util.* + +class AlbumDetailsActivity : AbsSlidingMusicPanelActivity(), AlbumDetailsContract.AlbumDetailsView { + + private var albumDetailsPresenter: AlbumDetailsPresenter? = null + + private var adapter: SimpleSongAdapter? = null + var album: Album? = null + private set + + private val savedSortOrder: String + get() = PreferenceUtil.getInstance().albumDetailSongSortOrder + + override fun createContentView(): View { + return wrapSlidingMusicPanel(R.layout.activity_album) + } + + private fun setupWindowTransition() { + val slide = Slide(Gravity.BOTTOM) + slide.interpolator = AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in) + window.enterTransition = slide + } + + override fun onCreate(savedInstanceState: Bundle?) { + setDrawUnderStatusBar() + setupWindowTransition() + super.onCreate(savedInstanceState) + ButterKnife.bind(this) + + toggleBottomNavigationView(true) + setLightNavigationBar(true) + setNavigationbarColorAuto() + + ActivityCompat.postponeEnterTransition(this) + + val albumId = intent.getIntExtra(EXTRA_ALBUM_ID, -1) + albumDetailsPresenter = AlbumDetailsPresenter(this, albumId) + albumDetailsPresenter!!.subscribe() + + setupRecyclerView() + setupToolbarMarginHeight() + + + contentContainer.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int -> + run { + if (scrollY > oldScrollY) { + actionShuffleAll!!.setShowTitle(false) + } + if (scrollY < oldScrollY) { + actionShuffleAll!!.setShowTitle(true) + } + } + } + } + + private fun setupRecyclerView() { + adapter = SimpleSongAdapter(this, ArrayList(), R.layout.item_song) + recyclerView.apply { + layoutManager = LinearLayoutManager(this@AlbumDetailsActivity) + itemAnimator = DefaultItemAnimator() + isNestedScrollingEnabled = false + adapter = adapter + } + } + + private fun setupToolbarMarginHeight() { + val primaryColor = ThemeStore.primaryColor(this) + TintHelper.setTintAuto(contentContainer!!, primaryColor, true) + if (collapsingToolbarLayout != null) { + collapsingToolbarLayout!!.setContentScrimColor(primaryColor) + collapsingToolbarLayout!!.setStatusBarScrimColor(ColorUtil.darkenColor(primaryColor)) + } + + toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp) + setSupportActionBar(toolbar) + + supportActionBar!!.title = null + + + if (toolbar != null && !PreferenceUtil.getInstance().fullScreenMode) { + val params = toolbar!!.layoutParams as ViewGroup.MarginLayoutParams + params.topMargin = RetroUtil.getStatusBarHeight() + toolbar!!.layoutParams = params + } + + if (appBarLayout != null) { + appBarLayout!!.addOnOffsetChangedListener(object : AppBarStateChangeListener() { + override fun onStateChanged(appBarLayout: AppBarLayout, state: AppBarStateChangeListener.State) { + val color: Int + when (state) { + AppBarStateChangeListener.State.COLLAPSED -> { + setLightStatusbar(ColorUtil.isColorLight(ThemeStore.primaryColor(this@AlbumDetailsActivity))) + color = ThemeStore.primaryColor(this@AlbumDetailsActivity) + } + AppBarStateChangeListener.State.EXPANDED, AppBarStateChangeListener.State.IDLE -> { + setLightStatusbar(false) + color = Color.TRANSPARENT + } + else -> { + setLightStatusbar(false) + color = Color.TRANSPARENT + } + } + ToolbarContentTintHelper.setToolbarContentColorBasedOnToolbarColor(this@AlbumDetailsActivity, toolbar, color) + } + }) + } + } + + @OnClick(R.id.action_shuffle_all, R.id.artist_image) + fun onViewClicked(view: View) { + when (view.id) { + R.id.artist_image -> { + val artistPairs = arrayOf>(Pair.create(image, resources.getString(R.string.transition_artist_image))) + NavigationUtil.goToArtist(this, album!!.artistId, *artistPairs) + } + R.id.action_shuffle_all -> if (album!!.songs != null) { + MusicPlayerRemote.openAndShuffleQueue(album!!.songs!!, true) + } + } + } + + override fun onPause() { + super.onPause() + albumDetailsPresenter!!.unsubscribe() + } + + override fun loading() { + + } + + override fun showEmptyView() { + + } + + override fun completed() { + ActivityCompat.startPostponedEnterTransition(this) + } + + override fun showData(album: Album) { + if (album.songs!!.isEmpty()) { + finish() + return + } + this.album = album + + albumTitle.text = album.title + albumText.text = String.format("%s • %s • %s", album.artistName, MusicUtil.getYearString(album.year), MusicUtil.getReadableDurationString(MusicUtil.getTotalDuration(this, album.songs))) + + loadAlbumCover() + loadMoreFrom(album) + adapter!!.swapDataSet(album.songs) + } + + private fun loadMoreFrom(album: Album) { + if (artistImage != null) { + ArtistGlideRequest.Builder.from(Glide.with(this), + ArtistLoader.getArtist(this, album.artistId).blockingFirst()) + .forceDownload(false) + .generatePalette(this).build() + .dontAnimate() + .into(object : RetroMusicColoredTarget(artistImage as CircularImageView) { + override fun onColorReady(color: Int) { + //setColors(color); + } + }) + } + + val albums = ArtistLoader.getArtist(this, album.artistId) + .blockingFirst().albums + albums!!.remove(album) + if (!albums.isEmpty()) { + moreTitle.visibility = View.VISIBLE + moreRecyclerView!!.visibility = View.VISIBLE + } else { + return + } + moreTitle.text = String.format("More from %s", album.artistName) + + val albumAdapter = HorizontalAlbumAdapter(this, albums, false, null) + moreRecyclerView!!.layoutManager = GridLayoutManager(this, 1, GridLayoutManager.HORIZONTAL, false) + moreRecyclerView!!.adapter = albumAdapter + } + + private fun loadAlbumCover() { + SongGlideRequest.Builder.from(Glide.with(this), album!!.safeGetFirstSong()) + .checkIgnoreMediaStore(this) + .generatePalette(this).build() + .dontAnimate() + .into(object : RetroMusicColoredTarget(image) { + override fun onColorReady(color: Int) { + setColors(color) + } + }) + } + + private fun setColors(color: Int) { + val themeColor = if (PreferenceUtil.getInstance().adaptiveColor) color else ThemeStore.accentColor(this) + songTitle.setTextColor(themeColor) + moreTitle.setTextColor(themeColor) + actionShuffleAll.setColor(themeColor) + } + + + override fun onCreateOptionsMenu(menu: Menu): Boolean { + menuInflater.inflate(R.menu.menu_album_detail, menu) + val sortOrder = menu.findItem(R.id.action_sort_order) + setUpSortOrderMenu(sortOrder.subMenu) + return super.onCreateOptionsMenu(menu) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + return handleSortOrderMenuItem(item) + } + + private fun handleSortOrderMenuItem(item: MenuItem): Boolean { + var sortOrder: String? = null + val songs = adapter!!.dataSet + when (item.itemId) { + R.id.action_play_next -> { + MusicPlayerRemote.playNext(songs) + return true + } + R.id.action_add_to_current_playing -> { + MusicPlayerRemote.enqueue(songs) + return true + } + R.id.action_add_to_playlist -> { + AddToPlaylistDialog.create(songs).show(supportFragmentManager, "ADD_PLAYLIST") + return true + } + R.id.action_delete_from_device -> { + DeleteSongsDialog.create(songs).show(supportFragmentManager, "DELETE_SONGS") + return true + } + android.R.id.home -> { + super.onBackPressed() + return true + } + R.id.action_tag_editor -> { + val intent = Intent(this, AlbumTagEditorActivity::class.java) + intent.putExtra(AbsTagEditorActivity.EXTRA_ID, album!!.id) + startActivityForResult(intent, TAG_EDITOR_REQUEST) + return true + } + R.id.action_go_to_artist -> { + NavigationUtil.goToArtist(this, album!!.artistId) + return true + } + /*Sort*/ + R.id.action_sort_order_title -> sortOrder = AlbumSongSortOrder.SONG_A_Z + R.id.action_sort_order_title_desc -> sortOrder = AlbumSongSortOrder.SONG_Z_A + R.id.action_sort_order_track_list -> sortOrder = AlbumSongSortOrder.SONG_TRACK_LIST + R.id.action_sort_order_artist_song_duration -> sortOrder = AlbumSongSortOrder.SONG_DURATION + } + if (sortOrder != null) { + item.isChecked = true + setSaveSortOrder(sortOrder) + } + return true + } + + private fun setUpSortOrderMenu(sortOrder: SubMenu) { + when (savedSortOrder) { + AlbumSongSortOrder.SONG_A_Z -> sortOrder.findItem(R.id.action_sort_order_title).isChecked = true + AlbumSongSortOrder.SONG_Z_A -> sortOrder.findItem(R.id.action_sort_order_title_desc).isChecked = true + AlbumSongSortOrder.SONG_TRACK_LIST -> sortOrder.findItem(R.id.action_sort_order_track_list).isChecked = true + AlbumSongSortOrder.SONG_DURATION -> sortOrder.findItem(R.id.action_sort_order_artist_song_duration).isChecked = true + } + } + + private fun setSaveSortOrder(sortOrder: String?) { + PreferenceUtil.getInstance().albumDetailSongSortOrder = sortOrder + reload() + } + + override fun onMediaStoreChanged() { + super.onMediaStoreChanged() + reload() + } + + private fun reload() { + albumDetailsPresenter!!.subscribe() + } + + companion object { + + const val EXTRA_ALBUM_ID = "extra_album_id" + private const val TAG_EDITOR_REQUEST = 2001 + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.java index 62694222..6bf6346e 100755 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.java @@ -238,8 +238,7 @@ public class ArtistDetailActivity extends AbsSlidingMusicPanelActivity implement private void setupRecyclerView() { albumAdapter = new HorizontalAlbumAdapter(this, new ArrayList<>(), false, null); albumRecyclerView.setItemAnimator(new DefaultItemAnimator()); - albumRecyclerView - .setLayoutManager(new GridLayoutManager(this, 1, GridLayoutManager.HORIZONTAL, false)); + albumRecyclerView.setLayoutManager(new GridLayoutManager(this, 1, GridLayoutManager.HORIZONTAL, false)); albumRecyclerView.setAdapter(albumAdapter); songAdapter = new SimpleSongAdapter(this, new ArrayList<>(), R.layout.item_song); @@ -313,7 +312,7 @@ public class ArtistDetailActivity extends AbsSlidingMusicPanelActivity implement .getReadableDurationString(MusicUtil.getTotalDuration(this, artist.getSongs())))); songAdapter.swapDataSet(artist.getSongs()); - albumAdapter.swapDataSet(artist.albums); + albumAdapter.swapDataSet(artist.getAlbums()); } private void loadBiography() { @@ -398,7 +397,7 @@ public class ArtistDetailActivity extends AbsSlidingMusicPanelActivity implement public void onViewClicked(View view) { switch (view.getId()) { case R.id.action_shuffle_all: - MusicPlayerRemote.openAndShuffleQueue(getArtist().getSongs(), true); + MusicPlayerRemote.INSTANCE.openAndShuffleQueue(getArtist().getSongs(), true); break; } } @@ -415,10 +414,10 @@ public class ArtistDetailActivity extends AbsSlidingMusicPanelActivity implement super.onBackPressed(); return true; case R.id.action_play_next: - MusicPlayerRemote.playNext(songs); + MusicPlayerRemote.INSTANCE.playNext(songs); return true; case R.id.action_add_to_current_playing: - MusicPlayerRemote.enqueue(songs); + MusicPlayerRemote.INSTANCE.enqueue(songs); return true; case R.id.action_add_to_playlist: AddToPlaylistDialog.create(songs).show(getSupportFragmentManager(), "ADD_PLAYLIST"); diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.java index 9040d2f1..65095ed2 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.java @@ -66,7 +66,7 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements private CompoundButton.OnCheckedChangeListener mListener = (buttonView, isChecked) -> { switch (buttonView.getId()) { case R.id.equalizer: - EqualizerHelper.getInstance().getEqualizer().setEnabled(isChecked); + EqualizerHelper.Companion.getInstance().getEqualizer().setEnabled(isChecked); TransitionManager.beginDelayedTransition(mContent); mContent.setVisibility(isChecked ? View.VISIBLE : View.GONE); break; @@ -78,12 +78,12 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements if (fromUser) { if (seekBar == mBassBoostStrength) { mBassBoost.setEnabled(progress > 0); - EqualizerHelper.getInstance().setBassBoostStrength(progress); - EqualizerHelper.getInstance().setBassBoostEnabled(progress > 0); + EqualizerHelper.Companion.getInstance().setBassBoostStrength(progress); + EqualizerHelper.Companion.getInstance().setBassBoostEnabled(progress > 0); } else if (seekBar == mVirtualizerStrength) { mVirtualizer.setEnabled(progress > 0); - EqualizerHelper.getInstance().setVirtualizerEnabled(progress > 0); - EqualizerHelper.getInstance().setVirtualizerStrength(progress); + EqualizerHelper.Companion.getInstance().setVirtualizerEnabled(progress > 0); + EqualizerHelper.Companion.getInstance().setVirtualizerStrength(progress); } } } @@ -113,17 +113,17 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements setupToolbar(); - mEnable.setChecked(EqualizerHelper.getInstance().getEqualizer().getEnabled()); + mEnable.setChecked(EqualizerHelper.Companion.getInstance().getEqualizer().getEnabled()); mEnable.setOnCheckedChangeListener(mListener); mPresetsNamesAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1); mPresets.setAdapter(mPresetsNamesAdapter); mPresets.setOnItemSelectedListener(this); - mBassBoostStrength.setProgress(EqualizerHelper.getInstance().getBassBoostStrength()); + mBassBoostStrength.setProgress(EqualizerHelper.Companion.getInstance().getBassBoostStrength()); mBassBoostStrength.setOnSeekBarChangeListener(mSeekBarChangeListener); - mVirtualizerStrength.setProgress(EqualizerHelper.getInstance().getVirtualizerStrength()); + mVirtualizerStrength.setProgress(EqualizerHelper.Companion.getInstance().getVirtualizerStrength()); mVirtualizerStrength.setOnSeekBarChangeListener(mSeekBarChangeListener); setupUI(); @@ -153,13 +153,13 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements private void addPresets() { mPresetsNamesAdapter.clear(); mPresetsNamesAdapter.add("Custom"); - for (int j = 0; j < EqualizerHelper.getInstance().getEqualizer().getNumberOfPresets(); j++) { + for (int j = 0; j < EqualizerHelper.Companion.getInstance().getEqualizer().getNumberOfPresets(); j++) { mPresetsNamesAdapter - .add(EqualizerHelper.getInstance().getEqualizer().getPresetName((short) j)); + .add(EqualizerHelper.Companion.getInstance().getEqualizer().getPresetName((short) j)); mPresetsNamesAdapter.notifyDataSetChanged(); } mPresets - .setSelection((int) EqualizerHelper.getInstance().getEqualizer().getCurrentPreset() + 1); + .setSelection((int) EqualizerHelper.Companion.getInstance().getEqualizer().getCurrentPreset() + 1); } private void setupUI() { @@ -167,7 +167,7 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements short bands; try { // get number of supported bands - bands = (short) EqualizerHelper.getInstance().getNumberOfBands(); + bands = (short) EqualizerHelper.Companion.getInstance().getNumberOfBands(); // for each of the supported bands, we will set up a slider from -10dB to 10dB boost/attenuation, // as well as text labels to assist the user @@ -177,26 +177,26 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements View view = LayoutInflater.from(this).inflate(R.layout.retro_seekbar, mLinearLayout, false); TextView freqTextView = view.findViewById(R.id.hurtz); freqTextView.setText( - String.format("%d Hz", EqualizerHelper.getInstance().getCenterFreq((int) band) / 1000)); + String.format("%d Hz", EqualizerHelper.Companion.getInstance().getCenterFreq((int) band) / 1000)); TextView minDbTextView = view.findViewById(R.id.minus_db); minDbTextView - .setText(String.format("%d dB", EqualizerHelper.getInstance().getBandLevelLow() / 100)); + .setText(String.format("%d dB", EqualizerHelper.Companion.getInstance().getBandLevelLow() / 100)); TextView maxDbTextView = view.findViewById(R.id.plus_db); maxDbTextView.setText( - String.format("%d dB", EqualizerHelper.getInstance().getBandLevelHigh() / 100)); + String.format("%d dB", EqualizerHelper.Companion.getInstance().getBandLevelHigh() / 100)); SeekBar bar = view.findViewById(R.id.seekbar); - bar.setMax(EqualizerHelper.getInstance().getBandLevelHigh() - EqualizerHelper.getInstance() + bar.setMax(EqualizerHelper.Companion.getInstance().getBandLevelHigh() - EqualizerHelper.Companion.getInstance() .getBandLevelLow()); bar.setProgress( - EqualizerHelper.getInstance().getBandLevel((int) band) - EqualizerHelper.getInstance() + EqualizerHelper.Companion.getInstance().getBandLevel((int) band) - EqualizerHelper.Companion.getInstance() .getBandLevelLow()); bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - EqualizerHelper.getInstance().setBandLevel((int) band, - (int) (progress + EqualizerHelper.getInstance().getBandLevelLow())); + EqualizerHelper.Companion.getInstance().setBandLevel((int) band, + (int) (progress + EqualizerHelper.Companion.getInstance().getBandLevelLow())); if (fromUser) { mPresets.setSelection(0); } @@ -221,7 +221,7 @@ public class EqualizerActivity extends AbsMusicServiceActivity implements if (position == 0) { return; } - EqualizerHelper.getInstance().getEqualizer().usePreset((short) (position - 1)); + EqualizerHelper.Companion.getInstance().getEqualizer().usePreset((short) (position - 1)); setupUI(); } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ErrorHandlerActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ErrorHandlerActivity.java index 6f0de686..5a0ecd4c 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ErrorHandlerActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ErrorHandlerActivity.java @@ -1 +1 @@ -package code.name.monkey.retromusic.ui.activities; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import butterknife.OnClick; import code.name.monkey.retromusic.R; import code.name.monkey.retromusic.RetroApplication; public class ErrorHandlerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_error_handler); } @OnClick(R.id.clear_app_data) void clearAppDate(View view) { RetroApplication.deleteAppData(); } } \ No newline at end of file +package code.name.monkey.retromusic.ui.activities; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import butterknife.OnClick; import code.name.monkey.retromusic.R; import code.name.monkey.retromusic.RetroApplication; public class ErrorHandlerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_error_handler); } @OnClick(R.id.clear_app_data) void clearAppDate(View view) { RetroApplication.Companion.deleteAppData(); } } \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.java index 4e92f90f..f7130704 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.java @@ -89,7 +89,7 @@ public class GenreDetailsActivity extends AbsSlidingMusicPanelActivity implement genre = getIntent().getParcelableExtra(EXTRA_GENRE_ID); - presenter = new GenreDetailsPresenter(this, genre.id); + presenter = new GenreDetailsPresenter(this, genre.getId()); setUpToolBar(); setupRecyclerView(); @@ -99,13 +99,13 @@ public class GenreDetailsActivity extends AbsSlidingMusicPanelActivity implement public void onViewClicked(View view) { switch (view.getId()) { case R.id.action_shuffle: - MusicPlayerRemote.openAndShuffleQueue(songAdapter.getDataSet(), true); + MusicPlayerRemote.INSTANCE.openAndShuffleQueue(songAdapter.getDataSet(), true); break; } } private void setUpToolBar() { - title.setText(genre.name); + title.setText(genre.getName()); title.setTextColor(ThemeStore.textColorPrimary(this)); int primaryColor = ThemeStore.primaryColor(this); @@ -162,7 +162,7 @@ public class GenreDetailsActivity extends AbsSlidingMusicPanelActivity implement if (item.getItemId() == android.R.id.home) { onBackPressed(); } - return GenreMenuHelper.handleMenuClick(this, genre, item); + return GenreMenuHelper.INSTANCE.handleMenuClick(this, genre, item); } private void setupRecyclerView() { diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LockScreenActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LockScreenActivity.java deleted file mode 100644 index 5aa1a30c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LockScreenActivity.java +++ /dev/null @@ -1,86 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.os.Bundle; -import androidx.core.view.ViewCompat; -import android.view.WindowManager; - -import com.bumptech.glide.Glide; -import com.r0adkll.slidr.Slidr; -import com.r0adkll.slidr.model.SlidrConfig; -import com.r0adkll.slidr.model.SlidrPosition; - -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity; -import code.name.monkey.retromusic.ui.fragments.player.lockscreen.LockScreenPlayerControlsFragment; - -public class LockScreenActivity extends AbsMusicServiceActivity { - private LockScreenPlayerControlsFragment mFragment; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD - | WindowManager.LayoutParams.FLAG_FULLSCREEN - | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS - | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); - - setDrawUnderStatusBar(); - setContentView(R.layout.activity_lock_screen_old_style); - - hideStatusBar(); - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - SlidrConfig config = new SlidrConfig.Builder() - .position(SlidrPosition.BOTTOM) - .build(); - - Slidr.attach(this, config); - - ButterKnife.bind(this); - mFragment = (LockScreenPlayerControlsFragment) getSupportFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - findViewById(R.id.slide).setTranslationY(100f); - findViewById(R.id.slide).setAlpha(0f); - ViewCompat.animate(findViewById(R.id.slide)) - .translationY(0f) - .alpha(1f) - .setDuration(1500) - .start(); - - findViewById(R.id.root_layout).setBackgroundColor(ThemeStore.primaryColor(this)); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSongs(); - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - updateSongs(); - } - - private void updateSongs() { - Song song = MusicPlayerRemote.getCurrentSong(); - SongGlideRequest.Builder.from(Glide.with(this), song) - .checkIgnoreMediaStore(this) - .generatePalette(this) - .build().into(new RetroMusicColoredTarget(findViewById(R.id.image)) { - @Override - public void onColorReady(int color) { - mFragment.setDark(color); - } - }); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.java index f4be3c82..8f69927e 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.java @@ -137,8 +137,8 @@ public class LyricsActivity extends AbsMusicServiceActivity implements } private void loadLRCLyrics() { - if (LyricUtil.isLrcFileExist(song.title, song.artistName)) { - showLyricsLocal(LyricUtil.getLocalLyricFile(song.title, song.artistName)); + if (LyricUtil.isLrcFileExist(song.getTitle(), song.getArtistName())) { + showLyricsLocal(LyricUtil.getLocalLyricFile(song.getTitle(), song.getArtistName())); } } @@ -150,7 +150,7 @@ public class LyricsActivity extends AbsMusicServiceActivity implements disposable = new CompositeDisposable(); lyricView - .setOnPlayerClickListener((progress, content) -> MusicPlayerRemote.seekTo((int) progress)); + .setOnPlayerClickListener((progress, content) -> MusicPlayerRemote.INSTANCE.seekTo((int) progress)); //lyricView.setHighLightTextColor(ThemeStore.accentColor(this)); lyricView.setDefaultColor(ContextCompat.getColor(this, R.color.md_grey_400)); //lyricView.setTouchable(false); @@ -205,9 +205,9 @@ public class LyricsActivity extends AbsMusicServiceActivity implements } private void loadLrcFile() { - song = MusicPlayerRemote.getCurrentSong(); - bottomAppBar.setTitle(song.title); - bottomAppBar.setSubtitle(song.artistName); + song = MusicPlayerRemote.INSTANCE.getCurrentSong(); + bottomAppBar.setTitle(song.getTitle()); + bottomAppBar.setSubtitle(song.getArtistName()); SongGlideRequest.Builder.from(Glide.with(this), song) .checkIgnoreMediaStore(this) .generatePalette(this) @@ -254,7 +254,7 @@ public class LyricsActivity extends AbsMusicServiceActivity implements if (updateLyricsAsyncTask != null) { updateLyricsAsyncTask.cancel(false); } - final Song song = MusicPlayerRemote.getCurrentSong(); + final Song song = MusicPlayerRemote.INSTANCE.getCurrentSong(); updateLyricsAsyncTask = new AsyncTask() { @Override protected Lyrics doInBackground(Void... params) { @@ -292,7 +292,7 @@ public class LyricsActivity extends AbsMusicServiceActivity implements private void showSyncedLyrics() { String content = ""; try { - content = LyricUtil.getStringFromFile(song.title, song.artistName); + content = LyricUtil.getStringFromFile(song.getTitle(), song.getArtistName()); } catch (Exception e) { e.printStackTrace(); } @@ -302,21 +302,21 @@ public class LyricsActivity extends AbsMusicServiceActivity implements .content("Add time frame lyrics") .negativeText("Delete") .onNegative((dialog, which) -> { - LyricUtil.deleteLrcFile(song.title, song.artistName); + LyricUtil.deleteLrcFile(song.getTitle(), song.getArtistName()); loadLrcFile(); }) .onNeutral( (dialog, which) -> RetroUtil.openUrl(LyricsActivity.this, getGoogleSearchLrcUrl())) .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE) .input("Paste lyrics here", content, (dialog, input) -> { - LyricUtil.writeLrcToLoc(song.title, song.artistName, input.toString()); + LyricUtil.writeLrcToLoc(song.getTitle(), song.getArtistName(), input.toString()); loadLrcFile(); }).show(); } private String getGoogleSearchLrcUrl() { String baseUrl = "http://www.google.com/search?"; - String query = song.title + "+" + song.artistName; + String query = song.getTitle() + "+" + song.getArtistName(); query = "q=" + query.replace(" ", "+") + " .lrc"; baseUrl += query; return baseUrl; @@ -335,7 +335,7 @@ public class LyricsActivity extends AbsMusicServiceActivity implements .onNeutral(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - RetroUtil.openUrl(LyricsActivity.this, getGoogleSearchUrl(song.title, song.artistName)); + RetroUtil.openUrl(LyricsActivity.this, getGoogleSearchUrl(song.getTitle(), song.getArtistName())); } }) .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE) @@ -353,7 +353,7 @@ public class LyricsActivity extends AbsMusicServiceActivity implements private ArrayList getSongPaths(Song song) { ArrayList paths = new ArrayList<>(1); - paths.add(song.data); + paths.add(song.getData()); return paths; } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/MainActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/MainActivity.java deleted file mode 100644 index cc80ea55..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/MainActivity.java +++ /dev/null @@ -1,341 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.annotation.SuppressLint; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.provider.MediaStore; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.google.android.material.bottomnavigation.BottomNavigationView; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.ActivityCompat; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentTransaction; -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.RetroApplication; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.SearchQueryHelper; -import code.name.monkey.retromusic.interfaces.MainActivityFragmentCallbacks; -import code.name.monkey.retromusic.loaders.AlbumLoader; -import code.name.monkey.retromusic.loaders.ArtistLoader; -import code.name.monkey.retromusic.loaders.PlaylistSongsLoader; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.activities.base.AbsSlidingMusicPanelActivity; -import code.name.monkey.retromusic.ui.fragments.mainactivity.LibraryFragment; -import code.name.monkey.retromusic.ui.fragments.mainactivity.home.BannerHomeFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; -import io.reactivex.disposables.CompositeDisposable; - -public class MainActivity extends AbsSlidingMusicPanelActivity implements SharedPreferences.OnSharedPreferenceChangeListener, BottomNavigationView.OnNavigationItemSelectedListener { - public static final int APP_INTRO_REQUEST = 2323; - public static final int LIBRARY = 1; - public static final int FOLDERS = 3; - public static final int HOME = 0; - private static final String TAG = "MainActivity"; - private static final int APP_USER_INFO_REQUEST = 9003; - private static final int REQUEST_CODE_THEME = 9002; - - @Nullable - MainActivityFragmentCallbacks currentFragment; - - @BindView(R.id.parent_container) - FrameLayout drawerLayout; - - - private boolean blockRequestPermissions; - private CompositeDisposable disposable = new CompositeDisposable(); - private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (action != null && action.equals(Intent.ACTION_SCREEN_OFF)) { - if (PreferenceUtil.getInstance().getLockScreen() && MusicPlayerRemote.isPlaying()) { - Intent activity = new Intent(context, LockScreenActivity.class); - activity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - activity.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); - ActivityCompat.startActivity(context, activity, null); - } - } - } - }; - - @Override - protected View createContentView() { - @SuppressLint("InflateParams") - View contentView = getLayoutInflater().inflate(R.layout.activity_main_drawer_layout, null); - ViewGroup drawerContent = contentView.findViewById(R.id.drawer_content_container); - drawerContent.addView(wrapSlidingMusicPanel(R.layout.activity_main_content)); - return contentView; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - setDrawUnderStatusBar(); - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - - getBottomNavigationView().setOnNavigationItemSelectedListener(this); - - if (savedInstanceState == null) { - selectedFragment(PreferenceUtil.getInstance().getLastPage()); - } else { - restoreCurrentFragment(); - } - checkShowChangelog(); - - if (!RetroApplication.isProVersion() && !PreferenceManager.getDefaultSharedPreferences(this).getBoolean("shown", false)) { - showPromotionalOffer(); - } - } - - private void checkShowChangelog() { - try { - PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); - int currentVersion = pInfo.versionCode; - if (currentVersion != PreferenceUtil.getInstance().getLastChangelogVersion()) { - startActivity(new Intent(this, WhatsNewActivity.class)); - } - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - } - - @Override - protected void onResume() { - super.onResume(); - IntentFilter screenOnOff = new IntentFilter(); - screenOnOff.addAction(Intent.ACTION_SCREEN_OFF); - registerReceiver(broadcastReceiver, screenOnOff); - - PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this); - - if (getIntent().hasExtra("expand")) { - if (getIntent().getBooleanExtra("expand", false)) { - //expandPanel(); - getIntent().putExtra("expand", false); - } - } - - } - - @Override - public void onDestroy() { - super.onDestroy(); - disposable.clear(); - if (broadcastReceiver == null) { - return; - } - unregisterReceiver(broadcastReceiver); - PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this); - } - - public void setCurrentFragment(@NonNull Fragment fragment, boolean isStackAdd, String tag) { - - FragmentManager fragmentManager = getSupportFragmentManager(); - FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); - fragmentTransaction.replace(R.id.fragment_container, fragment, tag); - if (isStackAdd) { - fragmentTransaction.addToBackStack(tag); - } - fragmentTransaction.commit(); - - currentFragment = (MainActivityFragmentCallbacks) fragment; - } - - private void restoreCurrentFragment() { - currentFragment = (MainActivityFragmentCallbacks) getSupportFragmentManager().findFragmentById(R.id.fragment_container); - } - - private void handlePlaybackIntent(@Nullable Intent intent) { - if (intent == null) { - return; - } - - Uri uri = intent.getData(); - String mimeType = intent.getType(); - boolean handled = false; - - if (intent.getAction() != null && intent.getAction().equals(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH)) { - final ArrayList songs = SearchQueryHelper.getSongs(this, intent.getExtras()); - - if (MusicPlayerRemote.getShuffleMode() == MusicService.SHUFFLE_MODE_SHUFFLE) { - MusicPlayerRemote.openAndShuffleQueue(songs, true); - } else { - MusicPlayerRemote.openQueue(songs, 0, true); - } - handled = true; - } - - if (uri != null && uri.toString().length() > 0) { - MusicPlayerRemote.playFromUri(uri); - handled = true; - } else if (MediaStore.Audio.Playlists.CONTENT_TYPE.equals(mimeType)) { - final int id = (int) parseIdFromIntent(intent, "playlistId", "playlist"); - if (id >= 0) { - int position = intent.getIntExtra("position", 0); - ArrayList songs = new ArrayList<>( - PlaylistSongsLoader.getPlaylistSongList(this, id).blockingFirst()); - MusicPlayerRemote.openQueue(songs, position, true); - handled = true; - } - } else if (MediaStore.Audio.Albums.CONTENT_TYPE.equals(mimeType)) { - final int id = (int) parseIdFromIntent(intent, "albumId", "album"); - if (id >= 0) { - int position = intent.getIntExtra("position", 0); - MusicPlayerRemote - .openQueue(AlbumLoader.getAlbum(this, id).blockingFirst().songs, position, true); - handled = true; - } - } else if (MediaStore.Audio.Artists.CONTENT_TYPE.equals(mimeType)) { - final int id = (int) parseIdFromIntent(intent, "artistId", "artist"); - if (id >= 0) { - int position = intent.getIntExtra("position", 0); - MusicPlayerRemote - .openQueue(ArtistLoader.getArtist(this, id).blockingFirst().getSongs(), position, true); - handled = true; - } - } - if (handled) { - setIntent(new Intent()); - } - } - - private long parseIdFromIntent(@NonNull Intent intent, String longKey, String stringKey) { - 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 - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - switch (requestCode) { - case APP_INTRO_REQUEST: - blockRequestPermissions = false; - if (!hasPermissions()) { - requestPermissions(); - } - - break; - case REQUEST_CODE_THEME: - case APP_USER_INFO_REQUEST: - postRecreate(); - break; - } - - } - - @Override - public boolean handleBackPress() { - return super.handleBackPress() || (currentFragment != null && - currentFragment.handleBackPress()); - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - handlePlaybackIntent(getIntent()); - } - - @Override - protected void requestPermissions() { - if (!blockRequestPermissions) { - super.requestPermissions(); - } - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (key.equals(PreferenceUtil.GENERAL_THEME) || - key.equals(PreferenceUtil.ADAPTIVE_COLOR_APP) || - key.equals(PreferenceUtil.DOMINANT_COLOR) || - key.equals(PreferenceUtil.USER_NAME) || - key.equals(PreferenceUtil.TOGGLE_FULL_SCREEN) || - key.equals(PreferenceUtil.TOGGLE_VOLUME) || - key.equals(PreferenceUtil.ROUND_CORNERS) || - key.equals(PreferenceUtil.CAROUSEL_EFFECT) || - key.equals(PreferenceUtil.NOW_PLAYING_SCREEN_ID) || - key.equals(PreferenceUtil.TOGGLE_GENRE) || - key.equals(PreferenceUtil.BANNER_IMAGE_PATH) || - key.equals(PreferenceUtil.PROFILE_IMAGE_PATH) || - key.equals(PreferenceUtil.CIRCULAR_ALBUM_ART) || - key.equals(PreferenceUtil.KEEP_SCREEN_ON) || - key.equals(PreferenceUtil.TOGGLE_SEPARATE_LINE) || - key.equals(PreferenceUtil.ALBUM_GRID_STYLE) || - key.equals(PreferenceUtil.ARTIST_GRID_STYLE) || - key.equals(PreferenceUtil.TOGGLE_HOME_BANNER) || - key.equals(PreferenceUtil.TOGGLE_ADD_CONTROLS) || - key.equals(PreferenceUtil.ALBUM_COVER_STYLE) || - key.equals(PreferenceUtil.HOME_ARTIST_GRID_STYLE) || - key.equals(PreferenceUtil.ALBUM_COVER_TRANSFORM) || - key.equals(PreferenceUtil.TAB_TEXT_MODE)) postRecreate(); - } - - private void showPromotionalOffer() { - new MaterialDialog.Builder(this) - .positiveText("Buy") - .onPositive((dialog, which) -> - startActivity(new Intent(MainActivity.this, ProVersionActivity.class))) - .negativeText(android.R.string.cancel) - .customView(R.layout.dialog_promotional_offer, false) - .dismissListener(dialog -> { - PreferenceManager.getDefaultSharedPreferences(MainActivity.this) - .edit() - .putBoolean("shown", true) - .apply(); - }) - .show(); - } - - @Override - public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { - PreferenceUtil.getInstance().setLastPage(menuItem.getItemId()); - selectedFragment(menuItem.getItemId()); - return true; - } - - private void selectedFragment(int itemId) { - switch (itemId) { - case R.id.action_album: - case R.id.action_artist: - case R.id.action_playlist: - case R.id.action_song: - setCurrentFragment(LibraryFragment.newInstance(itemId), false, LibraryFragment.TAG); - break; - case R.id.action_home: - setCurrentFragment(BannerHomeFragment.newInstance(), false, BannerHomeFragment.TAG); - break; - - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/MainActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/MainActivity.kt new file mode 100644 index 00000000..e875ca79 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/MainActivity.kt @@ -0,0 +1,294 @@ +package code.name.monkey.retromusic.ui.activities + +import android.annotation.SuppressLint +import android.content.* +import android.content.pm.PackageManager +import android.os.Bundle +import android.preference.PreferenceManager +import android.provider.MediaStore +import android.util.Log +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import butterknife.ButterKnife +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.RetroApplication +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.SearchQueryHelper +import code.name.monkey.retromusic.interfaces.MainActivityFragmentCallbacks +import code.name.monkey.retromusic.loaders.AlbumLoader +import code.name.monkey.retromusic.loaders.ArtistLoader +import code.name.monkey.retromusic.loaders.PlaylistSongsLoader +import code.name.monkey.retromusic.service.MusicService +import code.name.monkey.retromusic.ui.activities.base.AbsSlidingMusicPanelActivity +import code.name.monkey.retromusic.ui.fragments.mainactivity.LibraryFragment +import code.name.monkey.retromusic.ui.fragments.mainactivity.home.BannerHomeFragment +import code.name.monkey.retromusic.util.PreferenceUtil +import com.afollestad.materialdialogs.MaterialDialog +import com.google.android.material.bottomnavigation.BottomNavigationView +import io.reactivex.disposables.CompositeDisposable +import java.util.* + +class MainActivity : AbsSlidingMusicPanelActivity(), SharedPreferences.OnSharedPreferenceChangeListener, BottomNavigationView.OnNavigationItemSelectedListener { + + lateinit var currentFragment: MainActivityFragmentCallbacks + + private var blockRequestPermissions: Boolean = false + private val disposable = CompositeDisposable() + private val broadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val action = intent.action + if (action != null && action == Intent.ACTION_SCREEN_OFF) { + if (PreferenceUtil.getInstance().lockScreen && MusicPlayerRemote.isPlaying) { + /*Intent activity = new Intent(context, LockScreenActivity.class); + activity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + activity.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); + ActivityCompat.startActivity(context, activity, null);*/ + } + } + } + } + + override fun createContentView(): View { + @SuppressLint("InflateParams") + val contentView = layoutInflater.inflate(R.layout.activity_main_drawer_layout, null) + val drawerContent = contentView.findViewById(R.id.drawer_content_container) + drawerContent.addView(wrapSlidingMusicPanel(R.layout.activity_main_content)) + return contentView + } + + override fun onCreate(savedInstanceState: Bundle?) { + setDrawUnderStatusBar() + super.onCreate(savedInstanceState) + ButterKnife.bind(this) + + getBottomNavigationView()!!.setOnNavigationItemSelectedListener(this) + + if (savedInstanceState == null) { + selectedFragment(PreferenceUtil.getInstance().lastPage) + } else { + restoreCurrentFragment() + } + checkShowChangelog() + + if (!RetroApplication.isProVersion && !PreferenceManager.getDefaultSharedPreferences(this).getBoolean("shown", false)) { + showPromotionalOffer() + } + } + + private fun checkShowChangelog() { + try { + val pInfo = packageManager.getPackageInfo(packageName, 0) + val currentVersion = pInfo.versionCode + if (currentVersion != PreferenceUtil.getInstance().lastChangelogVersion) { + startActivityForResult(Intent(this, WhatsNewActivity::class.java), APP_INTRO_REQUEST) + } + } catch (e: PackageManager.NameNotFoundException) { + e.printStackTrace() + } + + } + + override fun onResume() { + super.onResume() + val screenOnOff = IntentFilter() + screenOnOff.addAction(Intent.ACTION_SCREEN_OFF) + registerReceiver(broadcastReceiver, screenOnOff) + + PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this) + + if (intent.hasExtra("expand")) { + if (intent.getBooleanExtra("expand", false)) { + //expandPanel(); + intent.putExtra("expand", false) + } + } + + } + + override fun onDestroy() { + super.onDestroy() + disposable.clear() + unregisterReceiver(broadcastReceiver) + PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this) + } + + fun setCurrentFragment(fragment: Fragment, isStackAdd: Boolean, tag: String) { + val fragmentTransaction = supportFragmentManager.beginTransaction() + fragmentTransaction.replace(R.id.fragment_container, fragment, tag) + if (isStackAdd) { + fragmentTransaction.addToBackStack(tag) + } + fragmentTransaction.commit() + currentFragment = fragment as MainActivityFragmentCallbacks + } + + private fun restoreCurrentFragment() { + currentFragment = supportFragmentManager.findFragmentById(R.id.fragment_container) as MainActivityFragmentCallbacks + } + + private fun handlePlaybackIntent(intent: Intent?) { + if (intent == null) { + return + } + + val uri = intent.data + val mimeType = intent.type + var handled = false + + if (intent.action != null && intent.action == MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH) { + val songs = SearchQueryHelper.getSongs(this, intent.extras!!) + + if (MusicPlayerRemote.shuffleMode == MusicService.SHUFFLE_MODE_SHUFFLE) { + MusicPlayerRemote.openAndShuffleQueue(songs, true) + } else { + MusicPlayerRemote.openQueue(songs, 0, true) + } + handled = true + } + + if (uri != null && uri.toString().length > 0) { + MusicPlayerRemote.playFromUri(uri) + handled = true + } else if (MediaStore.Audio.Playlists.CONTENT_TYPE == mimeType) { + val id = parseIdFromIntent(intent, "playlistId", "playlist").toInt() + if (id >= 0) { + val position = intent.getIntExtra("position", 0) + val songs = ArrayList( + PlaylistSongsLoader.getPlaylistSongList(this, id).blockingFirst()) + MusicPlayerRemote.openQueue(songs, position, true) + handled = true + } + } else if (MediaStore.Audio.Albums.CONTENT_TYPE == mimeType) { + val id = parseIdFromIntent(intent, "albumId", "album").toInt() + if (id >= 0) { + val position = intent.getIntExtra("position", 0) + MusicPlayerRemote + .openQueue(AlbumLoader.getAlbum(this, id).blockingFirst().songs!!, position, true) + handled = true + } + } else if (MediaStore.Audio.Artists.CONTENT_TYPE == mimeType) { + val id = parseIdFromIntent(intent, "artistId", "artist").toInt() + if (id >= 0) { + val position = intent.getIntExtra("position", 0) + MusicPlayerRemote + .openQueue(ArtistLoader.getArtist(this, id).blockingFirst().songs, position, true) + handled = true + } + } + if (handled) { + setIntent(Intent()) + } + } + + private fun parseIdFromIntent(intent: Intent, longKey: String, stringKey: String): Long { + var id = intent.getLongExtra(longKey, -1) + if (id < 0) { + val idString = intent.getStringExtra(stringKey) + if (idString != null) { + try { + id = java.lang.Long.parseLong(idString) + } catch (e: NumberFormatException) { + Log.e(TAG, e.message) + } + + } + } + return id + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + when (requestCode) { + APP_INTRO_REQUEST -> { + blockRequestPermissions = false + if (!hasPermissions()) { + requestPermissions() + } + } + REQUEST_CODE_THEME, APP_USER_INFO_REQUEST -> postRecreate() + } + + } + + override fun handleBackPress(): Boolean { + return super.handleBackPress() || currentFragment.handleBackPress() + } + + override fun onServiceConnected() { + super.onServiceConnected() + handlePlaybackIntent(intent) + } + + override fun requestPermissions() { + if (!blockRequestPermissions) { + super.requestPermissions() + } + } + + override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { + if (key == PreferenceUtil.GENERAL_THEME || + key == PreferenceUtil.ADAPTIVE_COLOR_APP || + key == PreferenceUtil.DOMINANT_COLOR || + key == PreferenceUtil.USER_NAME || + key == PreferenceUtil.TOGGLE_FULL_SCREEN || + key == PreferenceUtil.TOGGLE_VOLUME || + key == PreferenceUtil.ROUND_CORNERS || + key == PreferenceUtil.CAROUSEL_EFFECT || + key == PreferenceUtil.NOW_PLAYING_SCREEN_ID || + key == PreferenceUtil.TOGGLE_GENRE || + key == PreferenceUtil.BANNER_IMAGE_PATH || + key == PreferenceUtil.PROFILE_IMAGE_PATH || + key == PreferenceUtil.CIRCULAR_ALBUM_ART || + key == PreferenceUtil.KEEP_SCREEN_ON || + key == PreferenceUtil.TOGGLE_SEPARATE_LINE || + key == PreferenceUtil.ALBUM_GRID_STYLE || + key == PreferenceUtil.ARTIST_GRID_STYLE || + key == PreferenceUtil.TOGGLE_HOME_BANNER || + key == PreferenceUtil.TOGGLE_ADD_CONTROLS || + key == PreferenceUtil.ALBUM_COVER_STYLE || + key == PreferenceUtil.HOME_ARTIST_GRID_STYLE || + key == PreferenceUtil.ALBUM_COVER_TRANSFORM || + key == PreferenceUtil.TAB_TEXT_MODE) + postRecreate() + } + + private fun showPromotionalOffer() { + MaterialDialog.Builder(this) + .positiveText("Buy") + .onPositive { dialog, which -> startActivity(Intent(this@MainActivity, ProVersionActivity::class.java)) } + .negativeText(android.R.string.cancel) + .customView(R.layout.dialog_promotional_offer, false) + .dismissListener { dialog -> + PreferenceManager.getDefaultSharedPreferences(this@MainActivity) + .edit() + .putBoolean("shown", true) + .apply() + } + .show() + } + + override fun onNavigationItemSelected(menuItem: MenuItem): Boolean { + PreferenceUtil.getInstance().lastPage = menuItem.itemId + selectedFragment(menuItem.itemId) + return true + } + + private fun selectedFragment(itemId: Int) { + when (itemId) { + R.id.action_album, R.id.action_artist, R.id.action_playlist, R.id.action_song -> setCurrentFragment(LibraryFragment.newInstance(itemId), false, LibraryFragment.TAG) + R.id.action_home -> setCurrentFragment(BannerHomeFragment.newInstance(), false, BannerHomeFragment.TAG) + } + } + + companion object { + const val APP_INTRO_REQUEST = 2323 + const val LIBRARY = 1 + const val FOLDERS = 3 + const val HOME = 0 + private const val TAG = "MainActivity" + private const val APP_USER_INFO_REQUEST = 9003 + private const val REQUEST_CODE_THEME = 9002 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/NowPayingActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/NowPayingActivity.java deleted file mode 100644 index 5a56b8f6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/NowPayingActivity.java +++ /dev/null @@ -1,180 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.SharedPreferences; -import android.graphics.Color; -import android.os.Bundle; -import android.transition.Slide; -import android.view.Gravity; -import android.view.animation.AnimationUtils; - -import androidx.fragment.app.Fragment; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity; -import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.adaptive.AdaptiveFragment; -import code.name.monkey.retromusic.ui.fragments.player.blur.BlurPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.card.CardFragment; -import code.name.monkey.retromusic.ui.fragments.player.cardblur.CardBlurFragment; -import code.name.monkey.retromusic.ui.fragments.player.color.ColorFragment; -import code.name.monkey.retromusic.ui.fragments.player.fit.FitFragment; -import code.name.monkey.retromusic.ui.fragments.player.flat.FlatPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.full.FullPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.hmm.HmmPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.material.MaterialFragment; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.plain.PlainPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.simple.SimplePlayerFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class NowPayingActivity extends AbsMusicServiceActivity implements AbsPlayerFragment.Callbacks, SharedPreferences.OnSharedPreferenceChangeListener { - - private NowPlayingScreen currentNowPlayingScreen; - private AbsPlayerFragment playerFragment; - - void setupWindowTransition() { - Slide slide = new Slide(Gravity.BOTTOM); - slide.setInterpolator( - AnimationUtils.loadInterpolator(this, android.R.interpolator.linear_out_slow_in)); - getWindow().setEnterTransition(slide); - //getWindow().setExitTransition(slide); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - setLightNavigationBar(true); - setDrawUnderNavigationBar(); - setupWindowTransition(); - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_now_playng); - chooseFragmentForTheme(); - } - - private boolean isOneOfTheseThemes() { - return currentNowPlayingScreen == NowPlayingScreen.FLAT - || currentNowPlayingScreen == NowPlayingScreen.PLAIN - || currentNowPlayingScreen == NowPlayingScreen.SIMPLE - || currentNowPlayingScreen == NowPlayingScreen.NORMAL - || currentNowPlayingScreen == NowPlayingScreen.ADAPTIVE - || currentNowPlayingScreen == NowPlayingScreen.TINY - || currentNowPlayingScreen == NowPlayingScreen.MATERIAL; - } - - @Override - public void onPaletteColorChanged() { - int paletteColor = playerFragment.getPaletteColor(); - boolean isColorLight = ColorUtil.isColorLight(paletteColor); - super.setTaskDescriptionColor(paletteColor); - if ((currentNowPlayingScreen == NowPlayingScreen.FLAT || currentNowPlayingScreen == NowPlayingScreen.NORMAL) && PreferenceUtil.getInstance().getAdaptiveColor()) { - setLightNavigationBar(ColorUtil.isColorLight(ThemeStore.primaryColor(this))); - setLightStatusbar(isColorLight); - } else if (currentNowPlayingScreen == NowPlayingScreen.COLOR) { - setLightStatusbar(isColorLight); - setLightNavigationBar(isColorLight); - setNavigationbarColor(paletteColor); - } else if (currentNowPlayingScreen == NowPlayingScreen.BLUR || currentNowPlayingScreen == NowPlayingScreen.BLUR_CARD) { - setLightStatusbar(false); - setLightNavigationBar(false); - } else if (currentNowPlayingScreen == NowPlayingScreen.CARD || currentNowPlayingScreen == NowPlayingScreen.FULL) { - setLightStatusbar(false); - setLightNavigationBar(false); - } else if (currentNowPlayingScreen == NowPlayingScreen.FIT) { - setNavigationbarColor(ThemeStore.primaryColor(this)); - setLightNavigationBar(ColorUtil.isColorLight(ThemeStore.primaryColor(this))); - setLightStatusbar(false); - } else { - boolean isTheme = isOneOfTheseThemes() && ColorUtil.isColorLight(ThemeStore.primaryColor(this)); - setStatusbarColor(Color.TRANSPARENT); - setLightStatusbar(isTheme); - setLightNavigationBar(isTheme); - } - } - - @Override - protected void onResume() { - super.onResume(); - if (currentNowPlayingScreen != PreferenceUtil.getInstance().getNowPlayingScreen()) { - postRecreate(); - } - PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this); - } - - @Override - protected void onPause() { - super.onPause(); - PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this); - } - - @Override - public void onQueueChanged() { - super.onQueueChanged(); - if (MusicPlayerRemote.getPlayingQueue().isEmpty()) { - finish(); - } - } - - private void chooseFragmentForTheme() { - currentNowPlayingScreen = PreferenceUtil.getInstance().getNowPlayingScreen(); - - Fragment fragment; // must implement AbsPlayerFragment - switch (currentNowPlayingScreen) { - case MATERIAL: - fragment = new MaterialFragment(); - break; - case FIT: - fragment = new FitFragment(); - break; - case BLUR: - fragment = new BlurPlayerFragment(); - break; - case FLAT: - fragment = new FlatPlayerFragment(); - break; - case PLAIN: - fragment = new PlainPlayerFragment(); - break; - case FULL: - fragment = new FullPlayerFragment(); - break; - case COLOR: - fragment = new ColorFragment(); - break; - case CARD: - fragment = new CardFragment(); - break; - case SIMPLE: - fragment = new SimplePlayerFragment(); - break; - case TINY: - fragment = new HmmPlayerFragment(); - break; - case BLUR_CARD: - fragment = new CardBlurFragment(); - break; - case ADAPTIVE: - fragment = new AdaptiveFragment(); - break; - case NORMAL: - default: - fragment = new PlayerFragment(); - break; - } - getSupportFragmentManager().beginTransaction().replace(R.id.player_fragment_container, fragment).commit(); - getSupportFragmentManager().executePendingTransactions(); - - playerFragment = (AbsPlayerFragment) getSupportFragmentManager() - .findFragmentById(R.id.player_fragment_container); - - - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (key.equals(PreferenceUtil.ALBUM_COVER_STYLE) || key.equals(PreferenceUtil.ALBUM_COVER_TRANSFORM)) { - recreate(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.java index 643e7887..4f90e5b6 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.java @@ -81,8 +81,8 @@ public class PlayingQueueActivity extends AbsMusicServiceActivity { mPlayingQueueAdapter = new PlayingQueueAdapter( this, - MusicPlayerRemote.getPlayingQueue(), - MusicPlayerRemote.getPosition(), + MusicPlayerRemote.INSTANCE.getPlayingQueue(), + MusicPlayerRemote.INSTANCE.getPosition(), R.layout.item_queue); mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(mPlayingQueueAdapter); @@ -92,7 +92,7 @@ public class PlayingQueueActivity extends AbsMusicServiceActivity { mRecyclerView.setAdapter(mWrappedAdapter); mRecyclerView.setItemAnimator(animator); mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView); - mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); + mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.INSTANCE.getPosition() + 1, 0); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override @@ -109,7 +109,7 @@ public class PlayingQueueActivity extends AbsMusicServiceActivity { @Override public void onQueueChanged() { - if (MusicPlayerRemote.getPlayingQueue().isEmpty()) { + if (MusicPlayerRemote.INSTANCE.getPlayingQueue().isEmpty()) { finish(); return; } @@ -133,18 +133,18 @@ public class PlayingQueueActivity extends AbsMusicServiceActivity { } private void updateQueuePosition() { - mPlayingQueueAdapter.setCurrent(MusicPlayerRemote.getPosition()); + mPlayingQueueAdapter.setCurrent(MusicPlayerRemote.INSTANCE.getPosition()); resetToCurrentPosition(); } private void updateQueue() { - mPlayingQueueAdapter.swapDataSet(MusicPlayerRemote.getPlayingQueue(), MusicPlayerRemote.getPosition()); + mPlayingQueueAdapter.swapDataSet(MusicPlayerRemote.INSTANCE.getPlayingQueue(), MusicPlayerRemote.INSTANCE.getPosition()); resetToCurrentPosition(); } private void resetToCurrentPosition() { mRecyclerView.stopScroll(); - mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); + mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.INSTANCE.getPosition() + 1, 0); } @Override @@ -178,7 +178,7 @@ public class PlayingQueueActivity extends AbsMusicServiceActivity { } protected String getUpNextAndQueueTime() { - return getResources().getString(R.string.up_next) + " • " + MusicUtil.getReadableDurationString(MusicPlayerRemote.getQueueDurationMillis(MusicPlayerRemote.getPosition())); + return getResources().getString(R.string.up_next) + " • " + MusicUtil.getReadableDurationString(MusicPlayerRemote.INSTANCE.getQueueDurationMillis(MusicPlayerRemote.INSTANCE.getPosition())); } private void setupToolbar() { @@ -198,6 +198,6 @@ public class PlayingQueueActivity extends AbsMusicServiceActivity { @OnClick(R.id.clear_queue) void clearQueue() { - MusicPlayerRemote.clearQueue(); + MusicPlayerRemote.INSTANCE.clearQueue(); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.java index 027c9a52..724b3e51 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.java @@ -32,7 +32,6 @@ import code.name.monkey.retromusic.interfaces.CabHolder; import code.name.monkey.retromusic.loaders.PlaylistLoader; import code.name.monkey.retromusic.model.AbsCustomPlaylist; import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.PlaylistSong; import code.name.monkey.retromusic.model.Song; import code.name.monkey.retromusic.mvp.contract.PlaylistSongsContract; import code.name.monkey.retromusic.mvp.presenter.PlaylistSongsPresenter; @@ -114,10 +113,9 @@ public class PlaylistDetailActivity extends AbsSlidingMusicPanelActivity impleme } else { recyclerViewDragDropManager = new RecyclerViewDragDropManager(); final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator(); - adapter = new OrderablePlaylistSongAdapter(this, new ArrayList(), + adapter = new OrderablePlaylistSongAdapter(this, new ArrayList<>(), R.layout.item_list, false, this, (fromPosition, toPosition) -> { - if (PlaylistsUtil - .moveItem(PlaylistDetailActivity.this, playlist.id, fromPosition, toPosition)) { + if (PlaylistsUtil.moveItem(PlaylistDetailActivity.this, playlist.id, fromPosition, toPosition)) { Song song = adapter.getDataSet().remove(fromPosition); adapter.getDataSet().add(toPosition, song); adapter.notifyItemMoved(fromPosition, toPosition); @@ -186,7 +184,7 @@ public class PlaylistDetailActivity extends AbsSlidingMusicPanelActivity impleme onBackPressed(); return true; } - return PlaylistMenuHelper.handleMenuClick(this, playlist, item); + return PlaylistMenuHelper.INSTANCE.handleMenuClick(this, playlist, item); } @NonNull @@ -228,7 +226,7 @@ public class PlaylistDetailActivity extends AbsSlidingMusicPanelActivity impleme // Playlist renamed final String playlistName = PlaylistsUtil.getNameForPlaylist(this, playlist.id); if (!playlistName.equals(playlist.name)) { - playlist = PlaylistLoader.getPlaylist(this, playlist.id).blockingFirst(); + playlist = PlaylistLoader.INSTANCE.getPlaylist(this, playlist.id).blockingFirst(); setToolbarTitle(playlist.name); } } @@ -306,6 +304,6 @@ public class PlaylistDetailActivity extends AbsSlidingMusicPanelActivity impleme if (adapter.getDataSet().isEmpty()) { return; } - MusicPlayerRemote.openAndShuffleQueue(adapter.getDataSet(), true); + MusicPlayerRemote.INSTANCE.openAndShuffleQueue(adapter.getDataSet(), true); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.java index dfd277cf..e2a8ea95 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.java @@ -119,7 +119,7 @@ public class ProVersionActivity extends AbsBaseActivity implements @Override public void onPurchaseHistoryRestored() { - if (RetroApplication.isProVersion()) { + if (RetroApplication.Companion.isProVersion()) { Toast.makeText(this, R.string.restored_previous_purchase_please_restart, Toast.LENGTH_LONG) .show(); setResult(RESULT_OK); diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.java index d09a7ccf..b0e912ab 100755 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.java @@ -1,7 +1,6 @@ package code.name.monkey.retromusic.ui.activities; import android.content.SharedPreferences; -import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; @@ -26,7 +25,6 @@ import code.name.monkey.appthemehelper.ThemeStore; import code.name.monkey.appthemehelper.util.ColorUtil; import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.appshortcuts.DynamicShortcutManager; import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; import code.name.monkey.retromusic.ui.fragments.settings.MainSettingsFragment; import code.name.monkey.retromusic.util.PreferenceUtil; @@ -65,9 +63,6 @@ public class SettingsActivity extends AbsBaseActivity implements ColorChooserDia break; } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { - new DynamicShortcutManager(this).updateDynamicShortcuts(); - } recreate(); } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.java index 51c24f8d..4d84ed6d 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.java @@ -115,7 +115,7 @@ public class SupportDevelopmentActivity extends AbsBaseActivity implements Billi @OnClick(R.id.donate) void donate() { - RetroUtil.openUrl(this, PAYPAL_ME_URL); + RetroUtil.openUrl(this,PAYPAL_ME_URL); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/WhatsNewActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/WhatsNewActivity.java deleted file mode 100644 index cb98165b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/WhatsNewActivity.java +++ /dev/null @@ -1,98 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.Context; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.webkit.WebView; -import android.widget.TextView; - -import com.afollestad.materialdialogs.internal.ThemeSingleton; -import com.google.android.material.appbar.AppBarLayout; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; - -import androidx.annotation.NonNull; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class WhatsNewActivity extends AbsBaseActivity { - @BindView(R.id.web_view) - WebView webView; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.app_bar) - AppBarLayout appBarLayout; - - - private static void setChangelogRead(@NonNull Context context) { - try { - PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); - int currentVersion = pInfo.versionCode; - PreferenceUtil.getInstance().setLastChangeLogVersion(currentVersion); - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - } - } - - private static String colorToHex(int color) { - return Integer.toHexString(color).substring(2); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_whats_new); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - - toolbar.setBackgroundColor(ThemeStore.primaryColor(this)); - appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)); - setSupportActionBar(toolbar); - setTitle(null); - toolbar.setNavigationOnClickListener(v -> onBackPressed()); - title.setTextColor(ThemeStore.textColorPrimary(this)); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - - try { - // Load from phonograph-changelog.html in the assets folder - StringBuilder buf = new StringBuilder(); - InputStream json = getAssets().open("retro-changelog.html"); - BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8")); - String str; - while ((str = in.readLine()) != null) - buf.append(str); - in.close(); - - // Inject color values for WebView body background and links - final String backgroundColor = colorToHex(ThemeStore.primaryColor(this)); - final String contentColor = ThemeSingleton.get().darkTheme ? "#ffffff" : "#000000"; - webView.loadData(buf.toString() - .replace("{style-placeholder}", - String.format("body { background-color: %s; color: %s; }", backgroundColor, contentColor)) - .replace("{link-color}", colorToHex(ThemeSingleton.get().positiveColor.getDefaultColor())) - .replace("{link-color-active}", colorToHex(ColorUtil.lightenColor(ThemeSingleton.get().positiveColor.getDefaultColor()))) - , "text/html", "UTF-8"); - } catch (Throwable e) { - webView.loadData("

Unable to load

" + e.getLocalizedMessage() + "

", "text/html", "UTF-8"); - } - setChangelogRead(this); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/WhatsNewActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/WhatsNewActivity.kt new file mode 100644 index 00000000..f70c5e94 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/WhatsNewActivity.kt @@ -0,0 +1,75 @@ +package code.name.monkey.retromusic.ui.activities + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Bundle +import butterknife.ButterKnife +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity +import code.name.monkey.retromusic.util.PreferenceUtil +import com.afollestad.materialdialogs.internal.ThemeSingleton +import kotlinx.android.synthetic.main.activity_whats_new.* +import java.io.BufferedReader +import java.io.InputStreamReader + +class WhatsNewActivity : AbsBaseActivity() { + + + private fun setChangelogRead(context: Context) { + try { + val pInfo = context.packageManager.getPackageInfo(context.packageName, 0) + val currentVersion = pInfo.versionCode + PreferenceUtil.getInstance().setLastChangeLogVersion(currentVersion) + } catch (e: PackageManager.NameNotFoundException) { + e.printStackTrace() + } + + } + + private fun colorToHex(color: Int): String { + return Integer.toHexString(color).substring(2) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_whats_new) + ButterKnife.bind(this) + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + + toolbar.setBackgroundColor(ThemeStore.primaryColor(this)) + appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)) + setSupportActionBar(toolbar) + title = null + toolbar.setNavigationOnClickListener({ v -> onBackPressed() }) + whatNewtitle.setTextColor(ThemeStore.textColorPrimary(this)) + ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)) + + try { + val buf = StringBuilder() + val json = assets.open("retro-changelog.html") + val inputStream = BufferedReader(InputStreamReader(json, "UTF-8")) + while (inputStream.readLine() != null) { + buf.append(inputStream.readLine()) + } + inputStream.close() + // Inject color values for WebView body background and links + val backgroundColor = colorToHex(ThemeStore.primaryColor(this)) + val contentColor = if (ThemeSingleton.get().darkTheme) "#ffffff" else "#000000" + webView.loadData(buf.toString() + .replace("{style-placeholder}", + String.format("body { background-color: %s; color: %s; }", backgroundColor, contentColor)) + .replace("{link-color}", colorToHex(ThemeSingleton.get().positiveColor.defaultColor)) + .replace("{link-color-active}", colorToHex(ColorUtil.lightenColor(ThemeSingleton.get().positiveColor.defaultColor))), "text/html", "UTF-8") + } catch (e: Throwable) { + webView.loadData("

Unable to load

" + e.localizedMessage + "

", "text/html", "UTF-8") + } + + setChangelogRead(this) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsBaseActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsBaseActivity.java deleted file mode 100644 index 1c679cff..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsBaseActivity.java +++ /dev/null @@ -1,159 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.base; - -import android.Manifest; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.media.AudioManager; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.provider.Settings; -import android.view.KeyEvent; -import android.view.View; -import android.view.ViewGroup; - -import com.google.android.material.snackbar.Snackbar; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.app.ActivityCompat; -import androidx.core.view.ViewCompat; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; - - -public abstract class AbsBaseActivity extends AbsThemeActivity { - - public static final int PERMISSION_REQUEST = 100; - private boolean hadPermissions; - private String[] permissions; - private String permissionDeniedMessage; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setVolumeControlStream(AudioManager.STREAM_MUSIC); - - permissions = getPermissionsToRequest(); - hadPermissions = hasPermissions(); - - setPermissionDeniedMessage(null); - } - - @Override - protected void onPostCreate(@Nullable Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - if (!hasPermissions()) { - requestPermissions(); - } - } - - @Override - protected void onResume() { - super.onResume(); - final boolean hasPermissions = hasPermissions(); - if (hasPermissions != hadPermissions) { - hadPermissions = hasPermissions; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - onHasPermissionsChanged(hasPermissions); - } - } - } - - protected void onHasPermissionsChanged(boolean hasPermissions) { - // implemented by sub classes - } - - @Override - public boolean dispatchKeyEvent(@NonNull KeyEvent event) { - if (event.getKeyCode() == KeyEvent.KEYCODE_MENU && event.getAction() == KeyEvent.ACTION_UP) { - showOverflowMenu(); - return true; - } - return super.dispatchKeyEvent(event); - } - - protected void showOverflowMenu() { - - } - - @Override - protected void attachBaseContext(Context newBase) { - super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); - } - - @Nullable - protected String[] getPermissionsToRequest() { - return null; - } - - protected View getSnackBarContainer() { - return getWindow().getDecorView(); - } - - private String getPermissionDeniedMessage() { - return permissionDeniedMessage == null ? getString(R.string.permissions_denied) - : permissionDeniedMessage; - } - - protected void setPermissionDeniedMessage(String message) { - permissionDeniedMessage = message; - } - - protected void requestPermissions() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) { - requestPermissions(permissions, PERMISSION_REQUEST); - } - } - - protected boolean hasPermissions() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) { - for (String permission : permissions) { - if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { - return false; - } - } - } - return true; - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - if (requestCode == PERMISSION_REQUEST) { - for (int grantResult : grantResults) { - if (grantResult != PackageManager.PERMISSION_GRANTED) { - if (ActivityCompat.shouldShowRequestPermissionRationale(AbsBaseActivity.this, - Manifest.permission.WRITE_EXTERNAL_STORAGE)) { - //User has deny from permission dialog - Snackbar.make(getSnackBarContainer(), getPermissionDeniedMessage(), - Snackbar.LENGTH_INDEFINITE) - .setAction(R.string.action_grant, view -> requestPermissions()) - .setActionTextColor(ThemeStore.accentColor(this)) - .show(); - } else { - // User has deny permission and checked never show permission dialog so you can redirect to Application settings page - Snackbar.make(getSnackBarContainer(), getPermissionDeniedMessage(), - Snackbar.LENGTH_INDEFINITE) - .setAction(R.string.action_settings, view -> { - Intent intent = new Intent(); - intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - Uri uri = Uri.fromParts("package", AbsBaseActivity.this.getPackageName(), null); - intent.setData(uri); - startActivity(intent); - }) - .setActionTextColor(ThemeStore.accentColor(this)) - .show(); - } - return; - } - } - hadPermissions = true; - onHasPermissionsChanged(true); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsBaseActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsBaseActivity.kt new file mode 100644 index 00000000..25850c50 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsBaseActivity.kt @@ -0,0 +1,145 @@ +package code.name.monkey.retromusic.ui.activities.base + +import android.Manifest +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.media.AudioManager +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.view.KeyEvent +import android.view.View +import androidx.core.app.ActivityCompat +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import com.google.android.material.snackbar.Snackbar +import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper + + +abstract class AbsBaseActivity : AbsThemeActivity() { + private var hadPermissions: Boolean = false + private var permissions: Array? = null + private var permissionDeniedMessage: String? = null + + + open fun getPermissionsToRequest(): Array? { + return null + } + + protected fun setPermissionDeniedMessage(message: String) { + permissionDeniedMessage = message + } + + fun getPermissionDeniedMessage(): String { + return if (permissionDeniedMessage == null) getString(R.string.permissions_denied) else permissionDeniedMessage!! + } + + + private val snackBarContainer: View + get() = window.decorView + + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + volumeControlStream = AudioManager.STREAM_MUSIC + permissions = getPermissionsToRequest() + hadPermissions = hasPermissions() + permissionDeniedMessage = null + } + + override fun onPostCreate(savedInstanceState: Bundle?) { + super.onPostCreate(savedInstanceState) + if (!hasPermissions()) { + requestPermissions() + } + } + + override fun onResume() { + super.onResume() + val hasPermissions = hasPermissions() + if (hasPermissions != hadPermissions) { + hadPermissions = hasPermissions + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + onHasPermissionsChanged(hasPermissions) + } + } + } + + protected open fun onHasPermissionsChanged(hasPermissions: Boolean) { + // implemented by sub classes + } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (event.keyCode == KeyEvent.KEYCODE_MENU && event.action == KeyEvent.ACTION_UP) { + showOverflowMenu() + return true + } + return super.dispatchKeyEvent(event) + } + + protected fun showOverflowMenu() { + + } + + override fun attachBaseContext(newBase: Context) { + super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)) + } + + protected open fun requestPermissions() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + requestPermissions(permissions!!, PERMISSION_REQUEST) + } + } + + protected fun hasPermissions(): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + for (permission in permissions!!) { + if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { + return false + } + } + } + return true + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == PERMISSION_REQUEST) { + for (grantResult in grantResults) { + if (grantResult != PackageManager.PERMISSION_GRANTED) { + if (ActivityCompat.shouldShowRequestPermissionRationale(this@AbsBaseActivity, + Manifest.permission.WRITE_EXTERNAL_STORAGE)) { + //User has deny from permission dialog + Snackbar.make(snackBarContainer, permissionDeniedMessage!!, + Snackbar.LENGTH_INDEFINITE) + .setAction(R.string.action_grant) { requestPermissions() } + .setActionTextColor(ThemeStore.accentColor(this)) + .show() + } else { + // User has deny permission and checked never show permission dialog so you can redirect to Application settings page + Snackbar.make(snackBarContainer, permissionDeniedMessage!!, + Snackbar.LENGTH_INDEFINITE) + .setAction(R.string.action_settings) { + val intent = Intent() + intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS + val uri = Uri.fromParts("package", this@AbsBaseActivity.packageName, null) + intent.data = uri + startActivity(intent) + } + .setActionTextColor(ThemeStore.accentColor(this)) + .show() + } + return + } + } + hadPermissions = true + onHasPermissionsChanged(true) + } + } + + companion object { + const val PERMISSION_REQUEST = 100 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsCastActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsCastActivity.java deleted file mode 100644 index 7047458b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsCastActivity.java +++ /dev/null @@ -1,157 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.base; - -import android.os.Bundle; -import android.util.Log; -import android.view.Menu; - -import com.google.android.gms.cast.framework.CastButtonFactory; -import com.google.android.gms.cast.framework.CastContext; -import com.google.android.gms.cast.framework.CastSession; -import com.google.android.gms.cast.framework.SessionManagerListener; -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.GoogleApiAvailability; - -import java.io.IOException; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.cast.WebServer; - -public abstract class AbsCastActivity extends AbsBaseActivity { - private static final String TAG = "AbsCastActivity"; - - public boolean playServicesAvailable = false; - - private CastContext castContext; - private SessionManagerListener sessionManagerListener; - private CastSession castSession; - private WebServer castServer; - - private void setupCastListener() { - sessionManagerListener = new SessionManagerListener() { - - @Override - public void onSessionEnded(CastSession session, int error) { - onApplicationDisconnected(); - Log.i(TAG, "onSessionEnded: "); - } - - @Override - public void onSessionResumed(CastSession session, boolean wasSuspended) { - onApplicationConnected(session); - Log.i(TAG, "onSessionResumed: "); - } - - @Override - public void onSessionResumeFailed(CastSession session, int error) { - onApplicationDisconnected(); - Log.i(TAG, "onSessionResumeFailed: "); - } - - @Override - public void onSessionStarted(CastSession session, String sessionId) { - onApplicationConnected(session); - Log.i(TAG, "onSessionStarted: "); - } - - @Override - public void onSessionStartFailed(CastSession session, int error) { - onApplicationDisconnected(); - Log.i(TAG, "onSessionStartFailed: "); - } - - @Override - public void onSessionStarting(CastSession session) { - } - - @Override - public void onSessionEnding(CastSession session) { - } - - @Override - public void onSessionResuming(CastSession session, String sessionId) { - } - - @Override - public void onSessionSuspended(CastSession session, int reason) { - } - - private void onApplicationConnected(CastSession castSession) { - AbsCastActivity.this.castSession = castSession; - castServer = new WebServer(getApplicationContext()); - try { - castServer.start(); - } catch (IOException e) { - e.printStackTrace(); - } - supportInvalidateOptionsMenu(); - showCastMiniController(); - } - - private void onApplicationDisconnected() { - if (castServer != null) { - castServer.stop(); - } - supportInvalidateOptionsMenu(); - hideCastMiniController(); - } - }; - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - try { - playServicesAvailable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS; - } catch (Exception ignored) { - - } - - if (playServicesAvailable) - initCast(); - - - } - - @Override - protected void onResume() { - if (playServicesAvailable) { - castContext.getSessionManager().addSessionManagerListener(sessionManagerListener, CastSession.class); - } - super.onResume(); - } - - @Override - protected void onPause() { - super.onPause(); - if (playServicesAvailable) { - castContext.getSessionManager().removeSessionManagerListener(sessionManagerListener, CastSession.class); - } - } - - private void initCast() { - setupCastListener(); - castContext = CastContext.getSharedInstance(this); - castSession = castContext.getSessionManager().getCurrentCastSession(); - } - - /* @Override - public boolean onCreateOptionsMenu(Menu menu) { - getMenuInflater().inflate(R.menu.menu_cast, menu); - if (playServicesAvailable) { - CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.media_route_menu_item); - } - return true; - }*/ - - public void showCastMiniController() { - //implement by overriding in activities - } - - public void hideCastMiniController() { - //implement by overriding in activities - } - - public CastSession getCastSession() { - return castSession; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsCastActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsCastActivity.kt new file mode 100644 index 00000000..e27d61cc --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsCastActivity.kt @@ -0,0 +1,135 @@ +package code.name.monkey.retromusic.ui.activities.base + +import android.os.Bundle +import android.util.Log +import code.name.monkey.retromusic.cast.WebServer +import com.google.android.gms.cast.framework.CastContext +import com.google.android.gms.cast.framework.CastSession +import com.google.android.gms.cast.framework.SessionManagerListener +import com.google.android.gms.common.ConnectionResult +import com.google.android.gms.common.GoogleApiAvailability +import java.io.IOException + +abstract class AbsCastActivity : AbsBaseActivity() { + + var playServicesAvailable = false + + private var castContext: CastContext? = null + private var sessionManagerListener: SessionManagerListener? = null + var castSession: CastSession? = null + private set + private var castServer: WebServer? = null + + private fun setupCastListener() { + sessionManagerListener = object : SessionManagerListener { + + override fun onSessionEnded(session: CastSession, error: Int) { + onApplicationDisconnected() + Log.i(TAG, "onSessionEnded: ") + } + + override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) { + onApplicationConnected(session) + Log.i(TAG, "onSessionResumed: ") + } + + override fun onSessionResumeFailed(session: CastSession, error: Int) { + onApplicationDisconnected() + Log.i(TAG, "onSessionResumeFailed: ") + } + + override fun onSessionStarted(session: CastSession, sessionId: String) { + onApplicationConnected(session) + Log.i(TAG, "onSessionStarted: ") + } + + override fun onSessionStartFailed(session: CastSession, error: Int) { + onApplicationDisconnected() + Log.i(TAG, "onSessionStartFailed: ") + } + + override fun onSessionStarting(session: CastSession) {} + + override fun onSessionEnding(session: CastSession) {} + + override fun onSessionResuming(session: CastSession, sessionId: String) {} + + override fun onSessionSuspended(session: CastSession, reason: Int) {} + + private fun onApplicationConnected(castSession: CastSession) { + this@AbsCastActivity.castSession = castSession + castServer = WebServer(applicationContext) + try { + castServer!!.start() + } catch (e: IOException) { + e.printStackTrace() + } + invalidateOptionsMenu() + showCastMiniController() + } + + private fun onApplicationDisconnected() { + if (castServer != null) { + castServer!!.stop() + } + invalidateOptionsMenu() + hideCastMiniController() + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + try { + playServicesAvailable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS + } catch (ignored: Exception) { + + } + + if (playServicesAvailable) + initCast() + + + } + + override fun onResume() { + if (playServicesAvailable) { + castContext!!.sessionManager.addSessionManagerListener(sessionManagerListener!!, CastSession::class.java) + } + super.onResume() + } + + override fun onPause() { + super.onPause() + if (playServicesAvailable) { + castContext!!.sessionManager.removeSessionManagerListener(sessionManagerListener, CastSession::class.java) + } + } + + private fun initCast() { + setupCastListener() + castContext = CastContext.getSharedInstance(this) + castSession = castContext!!.sessionManager.currentCastSession + } + + /* @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_cast, menu); + if (playServicesAvailable) { + CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.media_route_menu_item); + } + return true; + }*/ + + open fun showCastMiniController() { + //implement by overriding in activities + } + + open fun hideCastMiniController() { + //implement by overriding in activities + } + + companion object { + private val TAG = "AbsCastActivity" + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsMusicServiceActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsMusicServiceActivity.java deleted file mode 100644 index 4a690e68..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsMusicServiceActivity.java +++ /dev/null @@ -1,224 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.base; - -import android.Manifest; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.ServiceConnection; -import android.os.Bundle; -import android.os.IBinder; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.interfaces.MusicServiceEventListener; - -import static code.name.monkey.retromusic.Constants.MEDIA_STORE_CHANGED; -import static code.name.monkey.retromusic.Constants.META_CHANGED; -import static code.name.monkey.retromusic.Constants.PLAY_STATE_CHANGED; -import static code.name.monkey.retromusic.Constants.QUEUE_CHANGED; -import static code.name.monkey.retromusic.Constants.REPEAT_MODE_CHANGED; -import static code.name.monkey.retromusic.Constants.SHUFFLE_MODE_CHANGED; - - -public abstract class AbsMusicServiceActivity extends AbsCastActivity implements MusicServiceEventListener { - public static final String TAG = AbsMusicServiceActivity.class.getSimpleName(); - - private final ArrayList mMusicServiceEventListeners = new ArrayList<>(); - - private MusicPlayerRemote.ServiceToken serviceToken; - private MusicStateReceiver musicStateReceiver; - private boolean receiverRegistered; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - serviceToken = MusicPlayerRemote.bindToService(this, new ServiceConnection() { - @Override - public void onServiceConnected(ComponentName name, IBinder service) { - AbsMusicServiceActivity.this.onServiceConnected(); - } - - @Override - public void onServiceDisconnected(ComponentName name) { - AbsMusicServiceActivity.this.onServiceDisconnected(); - } - }); - - setPermissionDeniedMessage(getString(R.string.permission_external_storage_denied)); - - } - - @Override - public void onDestroy() { - super.onDestroy(); - MusicPlayerRemote.unbindFromService(serviceToken); - if (receiverRegistered) { - unregisterReceiver(musicStateReceiver); - receiverRegistered = false; - } - } - - public void addMusicServiceEventListener(final MusicServiceEventListener listener) { - if (listener != null) { - mMusicServiceEventListeners.add(listener); - } - } - - public void removeMusicServiceEventListener(final MusicServiceEventListener listener) { - if (listener != null) { - mMusicServiceEventListeners.remove(listener); - } - } - - @Override - public void onServiceConnected() { - if (!receiverRegistered) { - musicStateReceiver = new MusicStateReceiver(this); - - final IntentFilter filter = new IntentFilter(); - filter.addAction(PLAY_STATE_CHANGED); - filter.addAction(SHUFFLE_MODE_CHANGED); - filter.addAction(REPEAT_MODE_CHANGED); - filter.addAction(META_CHANGED); - filter.addAction(QUEUE_CHANGED); - filter.addAction(MEDIA_STORE_CHANGED); - - registerReceiver(musicStateReceiver, filter); - - receiverRegistered = true; - } - - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onServiceConnected(); - } - } - } - - @Override - public void onServiceDisconnected() { - if (receiverRegistered) { - unregisterReceiver(musicStateReceiver); - receiverRegistered = false; - } - - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onServiceDisconnected(); - } - } - } - - @Override - public void onPlayingMetaChanged() { - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onPlayingMetaChanged(); - } - } - } - - @Override - public void onQueueChanged() { - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onQueueChanged(); - } - } - } - - @Override - public void onPlayStateChanged() { - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onPlayStateChanged(); - } - } - } - - @Override - public void onMediaStoreChanged() { - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onMediaStoreChanged(); - } - } - } - - @Override - public void onRepeatModeChanged() { - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onRepeatModeChanged(); - } - } - } - - @Override - public void onShuffleModeChanged() { - for (MusicServiceEventListener listener : mMusicServiceEventListeners) { - if (listener != null) { - listener.onShuffleModeChanged(); - } - } - } - - @Override - protected void onHasPermissionsChanged(boolean hasPermissions) { - super.onHasPermissionsChanged(hasPermissions); - Intent intent = new Intent(MEDIA_STORE_CHANGED); - intent.putExtra("from_permissions_changed", true); // just in case we need to know this at some point - sendBroadcast(intent); - } - - @Nullable - @Override - protected String[] getPermissionsToRequest() { - return new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; - } - - - private static final class MusicStateReceiver extends BroadcastReceiver { - - private final WeakReference reference; - - public MusicStateReceiver(final AbsMusicServiceActivity activity) { - reference = new WeakReference<>(activity); - } - - @Override - public void onReceive(final Context context, @NonNull final Intent intent) { - final String action = intent.getAction(); - AbsMusicServiceActivity activity = reference.get(); - if (activity != null && action != null) { - switch (action) { - case META_CHANGED: - activity.onPlayingMetaChanged(); - break; - case QUEUE_CHANGED: - activity.onQueueChanged(); - break; - case PLAY_STATE_CHANGED: - activity.onPlayStateChanged(); - break; - case REPEAT_MODE_CHANGED: - activity.onRepeatModeChanged(); - break; - case SHUFFLE_MODE_CHANGED: - activity.onShuffleModeChanged(); - break; - case MEDIA_STORE_CHANGED: - activity.onMediaStoreChanged(); - break; - } - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsMusicServiceActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsMusicServiceActivity.kt new file mode 100644 index 00000000..086c9786 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsMusicServiceActivity.kt @@ -0,0 +1,168 @@ +package code.name.monkey.retromusic.ui.activities.base + +import android.Manifest +import android.content.* +import android.os.Bundle +import android.os.IBinder +import code.name.monkey.retromusic.Constants.MEDIA_STORE_CHANGED +import code.name.monkey.retromusic.Constants.META_CHANGED +import code.name.monkey.retromusic.Constants.PLAY_STATE_CHANGED +import code.name.monkey.retromusic.Constants.QUEUE_CHANGED +import code.name.monkey.retromusic.Constants.REPEAT_MODE_CHANGED +import code.name.monkey.retromusic.Constants.SHUFFLE_MODE_CHANGED +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.interfaces.MusicServiceEventListener +import java.lang.ref.WeakReference +import java.util.* + + +abstract class AbsMusicServiceActivity : AbsCastActivity(), MusicServiceEventListener { + + private val mMusicServiceEventListeners = ArrayList() + + private var serviceToken: MusicPlayerRemote.ServiceToken? = null + private var musicStateReceiver: MusicStateReceiver? = null + private var receiverRegistered: Boolean = false + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + serviceToken = MusicPlayerRemote.bindToService(this, object : ServiceConnection { + override fun onServiceConnected(name: ComponentName, service: IBinder) { + this@AbsMusicServiceActivity.onServiceConnected() + } + + override fun onServiceDisconnected(name: ComponentName) { + this@AbsMusicServiceActivity.onServiceDisconnected() + } + }) + + setPermissionDeniedMessage(getString(R.string.permission_external_storage_denied)); + } + + override fun onDestroy() { + super.onDestroy() + MusicPlayerRemote.unbindFromService(serviceToken) + if (receiverRegistered) { + unregisterReceiver(musicStateReceiver) + receiverRegistered = false + } + } + + fun addMusicServiceEventListener(listener: MusicServiceEventListener?) { + if (listener != null) { + mMusicServiceEventListeners.add(listener) + } + } + + fun removeMusicServiceEventListener(listener: MusicServiceEventListener?) { + if (listener != null) { + mMusicServiceEventListeners.remove(listener) + } + } + + override fun onServiceConnected() { + if (!receiverRegistered) { + musicStateReceiver = MusicStateReceiver(this) + + val filter = IntentFilter() + filter.addAction(PLAY_STATE_CHANGED) + filter.addAction(SHUFFLE_MODE_CHANGED) + filter.addAction(REPEAT_MODE_CHANGED) + filter.addAction(META_CHANGED) + filter.addAction(QUEUE_CHANGED) + filter.addAction(MEDIA_STORE_CHANGED) + + registerReceiver(musicStateReceiver, filter) + + receiverRegistered = true + } + + for (listener in mMusicServiceEventListeners) { + listener.onServiceConnected() + } + } + + override fun onServiceDisconnected() { + if (receiverRegistered) { + unregisterReceiver(musicStateReceiver) + receiverRegistered = false + } + + for (listener in mMusicServiceEventListeners) { + listener.onServiceDisconnected() + } + } + + override fun onPlayingMetaChanged() { + for (listener in mMusicServiceEventListeners) { + listener.onPlayingMetaChanged() + } + } + + override fun onQueueChanged() { + for (listener in mMusicServiceEventListeners) { + listener.onQueueChanged() + } + } + + override fun onPlayStateChanged() { + for (listener in mMusicServiceEventListeners) { + listener.onPlayStateChanged() + } + } + + override fun onMediaStoreChanged() { + for (listener in mMusicServiceEventListeners) { + listener.onMediaStoreChanged() + } + } + + override fun onRepeatModeChanged() { + for (listener in mMusicServiceEventListeners) { + listener.onRepeatModeChanged() + } + } + + override fun onShuffleModeChanged() { + for (listener in mMusicServiceEventListeners) { + listener.onShuffleModeChanged() + } + } + + override fun onHasPermissionsChanged(hasPermissions: Boolean) { + super.onHasPermissionsChanged(hasPermissions) + val intent = Intent(MEDIA_STORE_CHANGED) + intent.putExtra("from_permissions_changed", true) // just in case we need to know this at some point + sendBroadcast(intent) + } + + + override fun getPermissionsToRequest(): Array? { + return arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE) + } + + private class MusicStateReceiver(activity: AbsMusicServiceActivity) : BroadcastReceiver() { + + private val reference: WeakReference = WeakReference(activity) + + override fun onReceive(context: Context, intent: Intent) { + val action = intent.action + val activity = reference.get() + if (activity != null && action != null) { + when (action) { + META_CHANGED -> activity.onPlayingMetaChanged() + QUEUE_CHANGED -> activity.onQueueChanged() + PLAY_STATE_CHANGED -> activity.onPlayStateChanged() + REPEAT_MODE_CHANGED -> activity.onRepeatModeChanged() + SHUFFLE_MODE_CHANGED -> activity.onShuffleModeChanged() + MEDIA_STORE_CHANGED -> activity.onMediaStoreChanged() + } + } + } + } + + companion object { + val TAG = AbsMusicServiceActivity::class.java.simpleName + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsSlidingMusicPanelActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsSlidingMusicPanelActivity.java deleted file mode 100644 index 6dc4c5b2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsSlidingMusicPanelActivity.java +++ /dev/null @@ -1,455 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.base; - -import android.animation.ArgbEvaluator; -import android.animation.ValueAnimator; -import android.annotation.SuppressLint; -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewTreeObserver; -import android.view.WindowManager; -import android.view.animation.PathInterpolator; - -import com.google.android.gms.cast.framework.CastSession; -import com.google.android.material.bottomnavigation.BottomNavigationView; -import com.sothree.slidinguppanel.SlidingUpPanelLayout; -import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState; - -import androidx.annotation.FloatRange; -import androidx.annotation.LayoutRes; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.fragment.app.Fragment; -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.ui.fragments.MiniPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.adaptive.AdaptiveFragment; -import code.name.monkey.retromusic.ui.fragments.player.blur.BlurPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.card.CardFragment; -import code.name.monkey.retromusic.ui.fragments.player.cardblur.CardBlurFragment; -import code.name.monkey.retromusic.ui.fragments.player.color.ColorFragment; -import code.name.monkey.retromusic.ui.fragments.player.fit.FitFragment; -import code.name.monkey.retromusic.ui.fragments.player.flat.FlatPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.full.FullPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.hmm.HmmPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.material.MaterialFragment; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.plain.PlainPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.simple.SimplePlayerFragment; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.ViewUtil; -import code.name.monkey.retromusic.views.BottomNavigationBarTinted; - -public abstract class AbsSlidingMusicPanelActivity extends AbsMusicServiceActivity implements - SlidingUpPanelLayout.PanelSlideListener, PlayerFragment.Callbacks { - - public static final String TAG = AbsSlidingMusicPanelActivity.class.getSimpleName(); - - @BindView(R.id.sliding_layout) - SlidingUpPanelLayout slidingUpPanelLayout; - - @BindView(R.id.bottom_navigation) - BottomNavigationBarTinted bottomNavigationView; - - @BindView(R.id.main_content) - CoordinatorLayout coordinatorLayout; - - private MiniPlayerFragment miniPlayerFragment; - private AbsPlayerFragment playerFragment; - private NowPlayingScreen currentNowPlayingScreen; - - private int navigationbarColor; - private int taskColor; - private boolean lightStatusbar; - private boolean lightNavigationBar; - private ValueAnimator navigationBarColorAnimator; - private ArgbEvaluator argbEvaluator = new ArgbEvaluator(); - - protected AbsSlidingMusicPanelActivity() { - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(createContentView()); - ButterKnife.bind(this); - choosFragmentForTheme(); - setupSlidingUpPanel(); - } - - public void setBottomBarVisibility(int gone) { - if (bottomNavigationView != null) { - bottomNavigationView.setVisibility(gone); - hideBottomBar(false); - } - } - - protected abstract View createContentView(); - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - if (!MusicPlayerRemote.getPlayingQueue().isEmpty()) { - slidingUpPanelLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - slidingUpPanelLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); - hideBottomBar(false); - } - }); - } // don't call hideBottomBar(true) here as it causes a bug with the SlidingUpPanelLayout - } - - @Override - public void onQueueChanged() { - super.onQueueChanged(); - hideBottomBar(MusicPlayerRemote.getPlayingQueue().isEmpty()); - } - - public void hideBottomBar(final boolean hide) { - int heightOfBar = getResources().getDimensionPixelSize(R.dimen.mini_player_height); - int heightOfBarWithTabs = getResources().getDimensionPixelSize(R.dimen.mini_player_height_expanded); - - if (hide) { - slidingUpPanelLayout.setPanelHeight(0); - collapsePanel(); - } else { - if (!MusicPlayerRemote.getPlayingQueue().isEmpty()) { - slidingUpPanelLayout.setPanelHeight(bottomNavigationView.getVisibility() == View.VISIBLE ? heightOfBarWithTabs : heightOfBar); - } - } - } - - private void checkDisplayCutout() { - WindowManager.LayoutParams attrs = getWindow().getAttributes(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - attrs.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; - } - - } - - protected View wrapSlidingMusicPanel(@LayoutRes int resId) { - @SuppressLint("InflateParams") - View slidingMusicPanelLayout = getLayoutInflater().inflate(R.layout.sliding_music_panel_layout, null); - ViewGroup contentContainer = slidingMusicPanelLayout.findViewById(R.id.content_container); - getLayoutInflater().inflate(resId, contentContainer); - return slidingMusicPanelLayout; - } - - @Override - public void onBackPressed() { - if (!handleBackPress()) - super.onBackPressed(); - } - - public boolean handleBackPress() { - if (slidingUpPanelLayout.getPanelHeight() != 0 && playerFragment.onBackPressed()) - return true; - if (getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED) { - collapsePanel(); - return true; - } - return false; - } - - @Override - protected View getSnackBarContainer() { - return findViewById(R.id.content_container); - } - - @Override - public void hideCastMiniController() { - super.hideCastMiniController(); - } - - @Override - public void showCastMiniController() { - super.showCastMiniController(); - - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - CastSession castSession = getCastSession(); - if (castSession == null) { - return; - } - //MusicPlayerRemote.setZeroVolume(); - //CastHelper.startCasting(castSession, MusicPlayerRemote.getCurrentSong()); - } - - public void toggleBottomNavigationView(boolean toggle) { - bottomNavigationView.setVisibility(toggle ? View.GONE : View.VISIBLE); - } - - public BottomNavigationView getBottomNavigationView() { - return bottomNavigationView; - } - - public SlidingUpPanelLayout getSlidingUpPanelLayout() { - return slidingUpPanelLayout; - } - - public AbsPlayerFragment getPlayerFragment() { - return playerFragment; - } - - protected void setupSlidingUpPanel() { - slidingUpPanelLayout.getViewTreeObserver() - .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { - @Override - public void onGlobalLayout() { - slidingUpPanelLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); - - if (getPanelState() == PanelState.EXPANDED) { - onPanelSlide(slidingUpPanelLayout, 1); - onPanelExpanded(slidingUpPanelLayout); - } else if (getPanelState() == PanelState.COLLAPSED) { - onPanelCollapsed(slidingUpPanelLayout); - } else { - playerFragment.onHide(); - } - } - }); - - slidingUpPanelLayout.addPanelSlideListener(this); - - } - - public SlidingUpPanelLayout.PanelState getPanelState() { - return slidingUpPanelLayout == null ? null : slidingUpPanelLayout.getPanelState(); - } - - @Override - public void onPanelSlide(View panel, float slideOffset) { - bottomNavigationView.setTranslationY(slideOffset * 400); - setMiniPlayerAlphaProgress(slideOffset); - //if (navigationBarColorAnimator != null) navigationBarColorAnimator.cancel(); - //super.setNavigationbarColor((int) argbEvaluator.evaluate(slideOffset, navigationbarColor, Color.TRANSPARENT)); - } - - @Override - public void onPanelStateChanged(View panel, PanelState previousState, PanelState newState) { - switch (newState) { - case COLLAPSED: - onPanelCollapsed(panel); - break; - case EXPANDED: - onPanelExpanded(panel); - break; - case ANCHORED: - collapsePanel(); // this fixes a bug where the panel would get stuck for some reason - break; - } - } - - public void onPanelCollapsed(View panel) { - // restore values - super.setLightStatusbar(lightStatusbar); - super.setTaskDescriptionColor(taskColor); - super.setNavigationbarColor(navigationbarColor); - super.setLightNavigationBar(lightNavigationBar); - - - playerFragment.setMenuVisibility(false); - playerFragment.setUserVisibleHint(false); - playerFragment.onHide(); - } - - public void onPanelExpanded(View panel) { - int playerFragmentColor = playerFragment.getPaletteColor(); - super.setTaskDescriptionColor(playerFragmentColor); - - playerFragment.setMenuVisibility(true); - playerFragment.setUserVisibleHint(true); - playerFragment.onShow(); - onPaletteColorChanged(); - } - - private void setMiniPlayerAlphaProgress(@FloatRange(from = 0, to = 1) float progress) { - if (miniPlayerFragment.getView() == null) return; - float alpha = 1 - progress; - miniPlayerFragment.getView().setAlpha(alpha); - // necessary to make the views below clickable - miniPlayerFragment.getView().setVisibility(alpha == 0 ? View.GONE : View.VISIBLE); - } - - private void choosFragmentForTheme() { - currentNowPlayingScreen = PreferenceUtil.getInstance().getNowPlayingScreen(); - - Fragment fragment; // must implement AbsPlayerFragment - switch (currentNowPlayingScreen) { - case MATERIAL: - fragment = new MaterialFragment(); - break; - case BLUR: - fragment = new BlurPlayerFragment(); - break; - case FLAT: - fragment = new FlatPlayerFragment(); - break; - case PLAIN: - fragment = new PlainPlayerFragment(); - break; - case FULL: - fragment = new FullPlayerFragment(); - break; - case COLOR: - fragment = new ColorFragment(); - break; - case CARD: - fragment = new CardFragment(); - break; - case SIMPLE: - fragment = new SimplePlayerFragment(); - break; - case TINY: - fragment = new HmmPlayerFragment(); - break; - case BLUR_CARD: - fragment = new CardBlurFragment(); - break; - case ADAPTIVE: - fragment = new AdaptiveFragment(); - break; - case FIT: - fragment = new FitFragment(); - break; - case NORMAL: - default: - fragment = new PlayerFragment(); - break; - } - getSupportFragmentManager().beginTransaction().replace(R.id.player_fragment_container, fragment).commit(); - getSupportFragmentManager().executePendingTransactions(); - - playerFragment = (AbsPlayerFragment) getSupportFragmentManager().findFragmentById(R.id.player_fragment_container); - miniPlayerFragment = (MiniPlayerFragment) getSupportFragmentManager().findFragmentById(R.id.mini_player_fragment); - - //noinspection ConstantConditions - miniPlayerFragment.getView().setOnClickListener(v -> expandPanel()); - - } - - @Override - protected void onResume() { - super.onResume(); - if (currentNowPlayingScreen != PreferenceUtil.getInstance().getNowPlayingScreen()) { - postRecreate(); - } - } - - public void setAntiDragView(View antiDragView) { - //slidingUpPanelLayout.setAntiDragView(antiDragView); - } - - public void collapsePanel() { - slidingUpPanelLayout.setPanelState(PanelState.COLLAPSED); - } - - public void expandPanel() { - slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED); - } - - @Override - public void onPaletteColorChanged() { - if (getPanelState() == PanelState.EXPANDED) { - int paletteColor = playerFragment.getPaletteColor(); - boolean isColorLight = ColorUtil.isColorLight(paletteColor); - super.setTaskDescriptionColor(paletteColor); - if ((currentNowPlayingScreen == NowPlayingScreen.FLAT || currentNowPlayingScreen == NowPlayingScreen.NORMAL) && PreferenceUtil.getInstance().getAdaptiveColor()) { - super.setLightNavigationBar(true); - super.setLightStatusbar(isColorLight); - } else if (currentNowPlayingScreen == NowPlayingScreen.COLOR) { - super.setLightStatusbar(isColorLight); - super.setLightNavigationBar(isColorLight); - super.setNavigationbarColor(paletteColor); - } else if (currentNowPlayingScreen == NowPlayingScreen.BLUR || currentNowPlayingScreen == NowPlayingScreen.BLUR_CARD) { - super.setLightStatusbar(false); - super.setLightNavigationBar(true); - } else if (currentNowPlayingScreen == NowPlayingScreen.CARD || currentNowPlayingScreen == NowPlayingScreen.FULL) { - super.setLightStatusbar(false); - super.setLightNavigationBar(ColorUtil.isColorLight(ThemeStore.primaryColor(this))); - } else if (currentNowPlayingScreen == NowPlayingScreen.FIT) { - super.setNavigationbarColor(ThemeStore.primaryColor(this)); - super.setLightNavigationBar(ColorUtil.isColorLight(ThemeStore.primaryColor(this))); - super.setLightStatusbar(false); - } else { - boolean isTheme = isOneOfTheseThemes() && ColorUtil.isColorLight(ThemeStore.primaryColor(this)); - super.setStatusbarColor(Color.TRANSPARENT); - super.setLightStatusbar(isTheme); - super.setLightNavigationBar(isTheme); - } - } - } - - private boolean isOneOfTheseThemes() { - return currentNowPlayingScreen == NowPlayingScreen.FLAT - || currentNowPlayingScreen == NowPlayingScreen.PLAIN - || currentNowPlayingScreen == NowPlayingScreen.SIMPLE - || currentNowPlayingScreen == NowPlayingScreen.NORMAL - || currentNowPlayingScreen == NowPlayingScreen.ADAPTIVE - || currentNowPlayingScreen == NowPlayingScreen.TINY - || currentNowPlayingScreen == NowPlayingScreen.MATERIAL; - } - - @Override - public void setLightStatusbar(boolean enabled) { - lightStatusbar = enabled; - if (getPanelState() == PanelState.COLLAPSED) { - super.setLightStatusbar(enabled); - } - } - - @Override - public void setLightNavigationBar(boolean enabled) { - lightNavigationBar = enabled; - if (getPanelState() == PanelState.COLLAPSED) { - super.setLightNavigationBar(enabled); - } - } - - @Override - public void setNavigationbarColor(int color) { - navigationbarColor = color; - if (getPanelState() == PanelState.COLLAPSED) { - if (navigationBarColorAnimator != null) navigationBarColorAnimator.cancel(); - super.setNavigationbarColor(color); - } - } - - @Override - public void setTaskDescriptionColor(int color) { - taskColor = color; - if (getPanelState() == PanelState.COLLAPSED) { - super.setTaskDescriptionColor(color); - } - } - - private void animateNavigationBarColor(int color) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - if (navigationBarColorAnimator != null) navigationBarColorAnimator.cancel(); - navigationBarColorAnimator = ValueAnimator - .ofArgb(getWindow().getNavigationBarColor(), color) - .setDuration(ViewUtil.RETRO_MUSIC_ANIM_TIME); - navigationBarColorAnimator.setInterpolator(new PathInterpolator(0.4f, 0f, 1f, 1f)); - navigationBarColorAnimator.addUpdateListener(animation -> AbsSlidingMusicPanelActivity.super.setNavigationbarColor((Integer) animation.getAnimatedValue())); - navigationBarColorAnimator.start(); - } - } - - @Override - public void onDestroy() { - super.onDestroy(); - if (navigationBarColorAnimator != null) navigationBarColorAnimator.cancel(); // just in case - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsSlidingMusicPanelActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsSlidingMusicPanelActivity.kt new file mode 100644 index 00000000..d41255e7 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsSlidingMusicPanelActivity.kt @@ -0,0 +1,301 @@ +package code.name.monkey.retromusic.ui.activities.base + +import android.animation.ArgbEvaluator +import android.animation.ValueAnimator +import android.annotation.SuppressLint +import android.graphics.Color +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import android.view.ViewTreeObserver +import androidx.annotation.FloatRange +import androidx.annotation.LayoutRes +import androidx.fragment.app.Fragment +import butterknife.ButterKnife +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.ui.fragments.MiniPlayerFragment +import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen +import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment +import code.name.monkey.retromusic.ui.fragments.player.adaptive.AdaptiveFragment +import code.name.monkey.retromusic.ui.fragments.player.blur.BlurPlayerFragment +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.views.BottomNavigationBarTinted +import com.google.android.material.bottomnavigation.BottomNavigationView +import com.sothree.slidinguppanel.SlidingUpPanelLayout +import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState + +abstract class AbsSlidingMusicPanelActivity protected constructor() : AbsMusicServiceActivity(), SlidingUpPanelLayout.PanelSlideListener, AbsPlayerFragment.Callbacks { + + + lateinit var slidingUpPanelLayout: SlidingUpPanelLayout + private lateinit var bottomNavigationView: BottomNavigationBarTinted + + private var miniPlayerFragment: MiniPlayerFragment? = null + var playerFragment: AbsPlayerFragment? = null + private var currentNowPlayingScreen: NowPlayingScreen? = null + + private var navigationbarColor: Int = 0 + private var taskColor: Int = 0 + private var lightStatusbar: Boolean = false + private var lightNavigationBar: Boolean = false + private var navigationBarColorAnimator: ValueAnimator? = null + private val argbEvaluator = ArgbEvaluator() + + val panelState: SlidingUpPanelLayout.PanelState? + get() = slidingUpPanelLayout.panelState + + private val isOneOfTheseThemes: Boolean + get() = (currentNowPlayingScreen == NowPlayingScreen.ADAPTIVE) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(createContentView()) + ButterKnife.bind(this) + + slidingUpPanelLayout = findViewById(R.id.sliding_layout); + bottomNavigationView = findViewById(R.id.bottom_navigation); + + choosFragmentForTheme() + setupSlidingUpPanel() + } + + fun setBottomBarVisibility(gone: Int) { + bottomNavigationView.visibility = gone + hideBottomBar(false) + } + + protected abstract fun createContentView(): View + + override fun onServiceConnected() { + super.onServiceConnected() + if (!MusicPlayerRemote.playingQueue.isEmpty()) { + slidingUpPanelLayout.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { + override fun onGlobalLayout() { + slidingUpPanelLayout.viewTreeObserver.removeOnGlobalLayoutListener(this) + hideBottomBar(false) + } + }) + } // don't call hideBottomBar(true) here as it causes a bug with the SlidingUpPanelLayout + } + + override fun onQueueChanged() { + super.onQueueChanged() + hideBottomBar(MusicPlayerRemote.playingQueue.isEmpty()) + } + + fun hideBottomBar(hide: Boolean) { + val heightOfBar = resources.getDimensionPixelSize(R.dimen.mini_player_height) + val heightOfBarWithTabs = resources.getDimensionPixelSize(R.dimen.mini_player_height_expanded) + + if (hide) { + slidingUpPanelLayout.panelHeight = 0 + collapsePanel() + } else { + if (!MusicPlayerRemote.playingQueue.isEmpty()) { + slidingUpPanelLayout.panelHeight = if (bottomNavigationView.visibility == View.VISIBLE) heightOfBarWithTabs else heightOfBar + } + } + } + + protected fun wrapSlidingMusicPanel(@LayoutRes resId: Int): View { + @SuppressLint("InflateParams") + val slidingMusicPanelLayout = layoutInflater.inflate(R.layout.sliding_music_panel_layout, null) + val contentContainer = slidingMusicPanelLayout.findViewById(R.id.content_container) + layoutInflater.inflate(resId, contentContainer) + return slidingMusicPanelLayout + } + + override fun onBackPressed() { + if (!handleBackPress()) + super.onBackPressed() + } + + open fun handleBackPress(): Boolean { + if (slidingUpPanelLayout.panelHeight != 0 && playerFragment!!.onBackPressed()) + return true + if (panelState == SlidingUpPanelLayout.PanelState.EXPANDED) { + collapsePanel() + return true + } + return false + } + + override fun onPlayingMetaChanged() { + super.onPlayingMetaChanged() + castSession ?: return + //MusicPlayerRemote.setZeroVolume(); + //CastHelper.startCasting(castSession, MusicPlayerRemote.getCurrentSong()); + } + + fun toggleBottomNavigationView(toggle: Boolean) { + bottomNavigationView.visibility = if (toggle) View.GONE else View.VISIBLE + } + + fun getBottomNavigationView(): BottomNavigationView? { + return bottomNavigationView + } + + private fun setupSlidingUpPanel() { + slidingUpPanelLayout.viewTreeObserver + .addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { + override fun onGlobalLayout() { + slidingUpPanelLayout.viewTreeObserver.removeOnGlobalLayoutListener(this) + + if (panelState == PanelState.EXPANDED) { + onPanelSlide(slidingUpPanelLayout, 1f) + onPanelExpanded() + } else if (panelState == PanelState.COLLAPSED) { + onPanelCollapsed() + } else { + playerFragment!!.onHide() + } + } + }) + + slidingUpPanelLayout.addPanelSlideListener(this) + + } + + override fun onPanelSlide(panel: View?, slideOffset: Float) { + bottomNavigationView.translationY = slideOffset * 400 + setMiniPlayerAlphaProgress(slideOffset) + //if (navigationBarColorAnimator != null) navigationBarColorAnimator.cancel(); + //super.setNavigationbarColor((int) argbEvaluator.evaluate(slideOffset, navigationbarColor, Color.TRANSPARENT)); + } + + override fun onPanelStateChanged(panel: View, previousState: PanelState, newState: PanelState) { + when (newState) { + SlidingUpPanelLayout.PanelState.COLLAPSED -> onPanelCollapsed() + SlidingUpPanelLayout.PanelState.EXPANDED -> onPanelExpanded() + SlidingUpPanelLayout.PanelState.ANCHORED -> collapsePanel() // this fixes a bug where the panel would get stuck for some reason + else -> { + } + } + } + + fun onPanelCollapsed() { + // restore values + super.setLightStatusbar(lightStatusbar) + super.setTaskDescriptionColor(taskColor) + super.setNavigationbarColor(navigationbarColor) + super.setLightNavigationBar(lightNavigationBar) + + + playerFragment!!.setMenuVisibility(false) + playerFragment!!.userVisibleHint = false + playerFragment!!.onHide() + } + + fun onPanelExpanded() { + val playerFragmentColor = playerFragment!!.paletteColor + super.setTaskDescriptionColor(playerFragmentColor) + + playerFragment!!.setMenuVisibility(true) + playerFragment!!.userVisibleHint = true + playerFragment!!.onShow() + onPaletteColorChanged() + } + + private fun setMiniPlayerAlphaProgress(@FloatRange(from = 0.0, to = 1.0) progress: Float) { + if (miniPlayerFragment!!.view == null) return + val alpha = 1 - progress + miniPlayerFragment!!.view!!.alpha = alpha + // necessary to make the views below clickable + miniPlayerFragment!!.view!!.visibility = if (alpha == 0f) View.GONE else View.VISIBLE + } + + private fun choosFragmentForTheme() { + currentNowPlayingScreen = PreferenceUtil.getInstance().nowPlayingScreen + + val fragment: Fragment // must implement AbsPlayerFragment + when (currentNowPlayingScreen) { + NowPlayingScreen.BLUR -> fragment = BlurPlayerFragment() + NowPlayingScreen.ADAPTIVE -> fragment = AdaptiveFragment() + else -> fragment = AdaptiveFragment() + } + supportFragmentManager.beginTransaction().replace(R.id.player_fragment_container, fragment).commit() + supportFragmentManager.executePendingTransactions() + + playerFragment = supportFragmentManager.findFragmentById(R.id.player_fragment_container) as AbsPlayerFragment? + miniPlayerFragment = supportFragmentManager.findFragmentById(R.id.mini_player_fragment) as MiniPlayerFragment? + + + miniPlayerFragment!!.view!!.setOnClickListener { expandPanel() } + + } + + override fun onResume() { + super.onResume() + if (currentNowPlayingScreen != PreferenceUtil.getInstance().nowPlayingScreen) { + postRecreate() + } + } + + private fun collapsePanel() { + slidingUpPanelLayout.panelState = PanelState.COLLAPSED + } + + private fun expandPanel() { + slidingUpPanelLayout.panelState = PanelState.EXPANDED + } + + + override fun onPaletteColorChanged() { + if (panelState == PanelState.EXPANDED) { + val paletteColor = playerFragment!!.paletteColor + ColorUtil.isColorLight(paletteColor) + super.setTaskDescriptionColor(paletteColor) + if (currentNowPlayingScreen == NowPlayingScreen.BLUR) { + super.setLightStatusbar(false) + super.setLightNavigationBar(true) + } else { + val isTheme = isOneOfTheseThemes && ColorUtil.isColorLight(ThemeStore.primaryColor(this)) + super.setStatusbarColor(Color.TRANSPARENT) + super.setLightStatusbar(isTheme) + super.setLightNavigationBar(isTheme) + } + } + } + + override fun setLightStatusbar(enabled: Boolean) { + lightStatusbar = enabled + if (panelState == PanelState.COLLAPSED) { + super.setLightStatusbar(enabled) + } + } + + override fun setLightNavigationBar(enabled: Boolean) { + lightNavigationBar = enabled + if (panelState == PanelState.COLLAPSED) { + super.setLightNavigationBar(enabled) + } + } + + override fun setNavigationbarColor(color: Int) { + navigationbarColor = color + if (panelState == PanelState.COLLAPSED) { + if (navigationBarColorAnimator != null) navigationBarColorAnimator!!.cancel() + super.setNavigationbarColor(color) + } + } + + override fun setTaskDescriptionColor(color: Int) { + taskColor = color + if (panelState == PanelState.COLLAPSED) { + super.setTaskDescriptionColor(color) + } + } + + override fun onDestroy() { + super.onDestroy() + if (navigationBarColorAnimator != null) navigationBarColorAnimator!!.cancel() // just in case + } + + companion object { + + val TAG = AbsSlidingMusicPanelActivity::class.java.simpleName + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsThemeActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsThemeActivity.java deleted file mode 100644 index c0231627..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsThemeActivity.java +++ /dev/null @@ -1,216 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.base; - -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.view.KeyEvent; -import android.view.View; -import android.view.WindowManager; - -import androidx.annotation.ColorInt; -import androidx.core.content.ContextCompat; -import code.name.monkey.appthemehelper.ATH; -import code.name.monkey.appthemehelper.ATHActivity; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialDialogsUtil; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.appthemehelper.util.VersionUtils; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; - -public abstract class AbsThemeActivity extends ATHActivity implements Runnable { - - private Handler handler = new Handler(); - - @Override - protected void onCreate(Bundle savedInstanceState) { - setTheme(PreferenceUtil.getInstance().getGeneralTheme()); - hideStatusBar(); - super.onCreate(savedInstanceState); - MaterialDialogsUtil.updateMaterialDialogsThemeSingleton(this); - - changeBackgroundShape(); - setImmersiveFullscreen(); - registerSystemUiVisibility(); - toggleScreenOn(); - } - - private void toggleScreenOn() { - if (PreferenceUtil.getInstance().isScreenOnEnabled()) { - getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } else { - getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - } - - @Override - public void onWindowFocusChanged(boolean hasFocus) { - super.onWindowFocusChanged(hasFocus); - if (hasFocus) { - hideStatusBar(); - handler.removeCallbacks(this); - handler.postDelayed(this, 300); - } else { - handler.removeCallbacks(this); - } - } - - public void hideStatusBar() { - hideStatusBar(PreferenceUtil.getInstance().getFullScreenMode()); - } - - private void hideStatusBar(boolean fullscreen) { - final View statusBar = getWindow().getDecorView().getRootView().findViewById(R.id.status_bar); - if (statusBar != null) { - statusBar.setVisibility(fullscreen ? View.GONE : View.VISIBLE); - } - } - - - private void changeBackgroundShape() { - Drawable background = PreferenceUtil.getInstance().isRoundCorners() ? - ContextCompat.getDrawable(this, R.drawable.round_window) - : ContextCompat.getDrawable(this, R.drawable.square_window); - background = TintHelper.createTintedDrawable(background, ThemeStore.primaryColor(this)); - getWindow().setBackgroundDrawable(background); - } - - public void setDrawUnderStatusBar() { - if (VersionUtils.hasLollipop()) { - RetroUtil.setAllowDrawUnderStatusBar(getWindow()); - } else if (VersionUtils.hasKitKat()) { - RetroUtil.setStatusBarTranslucent(getWindow()); - } - } - - public void setDrawUnderNavigationBar() { - RetroUtil.setAllowDrawUnderNavigationBar(getWindow()); - } - - /** - * This will set the color of the view with the id "status_bar" on KitKat and Lollipop. On - * Lollipop if no such view is found it will set the statusbar color using the native method. - * - * @param color the new statusbar color (will be shifted down on Lollipop and above) - */ - public void setStatusbarColor(int color) { - if (VersionUtils.hasKitKat()) { - final View statusBar = getWindow().getDecorView().getRootView().findViewById(R.id.status_bar); - if (statusBar != null) { - if (VersionUtils.hasMarshmallow()) { - getWindow().setStatusBarColor(color); - } else if (VersionUtils.hasLollipop()) { - statusBar.setBackgroundColor(ColorUtil.darkenColor(color)); - } else { - statusBar.setBackgroundColor(color); - } - } else if (Build.VERSION.SDK_INT >= 21) { - getWindow().setStatusBarColor(ColorUtil.darkenColor(color)); - } - } - setLightStatusbarAuto(color); - } - - public void setStatusbarColorAuto() { - // we don't want to use statusbar color because we are doing the color darkening on our own to support KitKat - setStatusbarColor(ThemeStore.primaryColor(this)); - } - - public void setTaskDescriptionColor(@ColorInt int color) { - ATH.setTaskDescriptionColor(this, color); - } - - public void setTaskDescriptionColorAuto() { - setTaskDescriptionColor(ThemeStore.primaryColor(this)); - } - - public void setNavigationbarColor(int color) { - if (ThemeStore.coloredNavigationBar(this)) { - ATH.setNavigationbarColor(this, color); - } else { - ATH.setNavigationbarColor(this, Color.BLACK); - } - } - - public void setNavigationbarColorAuto() { - setNavigationbarColor(ThemeStore.navigationBarColor(this)); - } - - public void setLightStatusbar(boolean enabled) { - ATH.setLightStatusbar(this, enabled); - } - - public void setLightStatusbarAuto(int bgColor) { - setLightStatusbar(ColorUtil.isColorLight(bgColor)); - } - - public void setLightNavigationBar(boolean enabled) { - if (!ATHUtil.isWindowBackgroundDark(this) && ThemeStore.coloredNavigationBar(this)) { - ATH.setLightNavigationbar(this, enabled); - } - } - - private void registerSystemUiVisibility() { - final View decorView = getWindow().getDecorView(); - decorView.setOnSystemUiVisibilityChangeListener(visibility -> { - if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) { - setImmersiveFullscreen(); - } - }); - } - - private void unregisterSystemUiVisibility() { - final View decorView = getWindow().getDecorView(); - decorView.setOnSystemUiVisibilityChangeListener(null); - } - - public void setImmersiveFullscreen() { - int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN - | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION - | View.SYSTEM_UI_FLAG_FULLSCREEN - | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; - if (PreferenceUtil.getInstance().getFullScreenMode()) { - getWindow().getDecorView().setSystemUiVisibility(flags); - } - } - - public void exitFullscreen() { - getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); - } - - @Override - public void run() { - setImmersiveFullscreen(); - } - - @Override - protected void onStop() { - handler.removeCallbacks(this); - super.onStop(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - unregisterSystemUiVisibility(); - exitFullscreen(); - } - - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)) { - handler.removeCallbacks(this); - handler.postDelayed(this, 500); - } - return super.onKeyDown(keyCode, event); - - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsThemeActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsThemeActivity.kt new file mode 100644 index 00000000..a88a03e6 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/base/AbsThemeActivity.kt @@ -0,0 +1,206 @@ +package code.name.monkey.retromusic.ui.activities.base + +import android.graphics.Color +import android.graphics.drawable.Drawable +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.view.KeyEvent +import android.view.View +import android.view.WindowManager +import androidx.annotation.ColorInt +import androidx.core.content.ContextCompat +import code.name.monkey.appthemehelper.ATH +import code.name.monkey.appthemehelper.ATHActivity +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.* +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil + +abstract class AbsThemeActivity : ATHActivity(), Runnable { + + private val handler = Handler() + + override fun onCreate(savedInstanceState: Bundle?) { + setTheme(PreferenceUtil.getInstance().generalTheme) + hideStatusBar() + super.onCreate(savedInstanceState) + MaterialDialogsUtil.updateMaterialDialogsThemeSingleton(this) + + changeBackgroundShape() + setImmersiveFullscreen() + registerSystemUiVisibility() + toggleScreenOn() + } + + private fun toggleScreenOn() { + if (PreferenceUtil.getInstance().isScreenOnEnabled) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } else { + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + if (hasFocus) { + hideStatusBar() + handler.removeCallbacks(this) + handler.postDelayed(this, 300) + } else { + handler.removeCallbacks(this) + } + } + + fun hideStatusBar() { + hideStatusBar(PreferenceUtil.getInstance().fullScreenMode) + } + + private fun hideStatusBar(fullscreen: Boolean) { + val statusBar = window.decorView.rootView.findViewById(R.id.status_bar) + if (statusBar != null) { + statusBar.visibility = if (fullscreen) View.GONE else View.VISIBLE + } + } + + + private fun changeBackgroundShape() { + var background: Drawable? = if (PreferenceUtil.getInstance().isRoundCorners) + ContextCompat.getDrawable(this, R.drawable.round_window) + else + ContextCompat.getDrawable(this, R.drawable.square_window) + background = TintHelper.createTintedDrawable(background, ThemeStore.primaryColor(this)) + window.setBackgroundDrawable(background) + } + + fun setDrawUnderStatusBar() { + if (VersionUtils.hasLollipop()) { + RetroUtil.setAllowDrawUnderStatusBar(window) + } else if (VersionUtils.hasKitKat()) { + RetroUtil.setStatusBarTranslucent(window) + } + } + + fun setDrawUnderNavigationBar() { + RetroUtil.setAllowDrawUnderNavigationBar(window) + } + + /** + * This will set the color of the view with the id "status_bar" on KitKat and Lollipop. On + * Lollipop if no such view is found it will set the statusbar color using the native method. + * + * @param color the new statusbar color (will be shifted down on Lollipop and above) + */ + fun setStatusbarColor(color: Int) { + if (VersionUtils.hasKitKat()) { + val statusBar = window.decorView.rootView.findViewById(R.id.status_bar) + if (statusBar != null) { + if (VersionUtils.hasMarshmallow()) { + window.statusBarColor = color + } else if (VersionUtils.hasLollipop()) { + statusBar.setBackgroundColor(ColorUtil.darkenColor(color)) + } else { + statusBar.setBackgroundColor(color) + } + } else if (Build.VERSION.SDK_INT >= 21) { + window.statusBarColor = ColorUtil.darkenColor(color) + } + } + setLightStatusbarAuto(color) + } + + fun setStatusbarColorAuto() { + // we don't want to use statusbar color because we are doing the color darkening on our own to support KitKat + setStatusbarColor(ThemeStore.primaryColor(this)) + } + + open fun setTaskDescriptionColor(@ColorInt color: Int) { + ATH.setTaskDescriptionColor(this, color) + } + + fun setTaskDescriptionColorAuto() { + setTaskDescriptionColor(ThemeStore.primaryColor(this)) + } + + open fun setNavigationbarColor(color: Int) { + if (ThemeStore.coloredNavigationBar(this)) { + ATH.setNavigationbarColor(this, color) + } else { + ATH.setNavigationbarColor(this, Color.BLACK) + } + } + + fun setNavigationbarColorAuto() { + setNavigationbarColor(ThemeStore.navigationBarColor(this)) + } + + open fun setLightStatusbar(enabled: Boolean) { + ATH.setLightStatusbar(this, enabled) + } + + fun setLightStatusbarAuto(bgColor: Int) { + setLightStatusbar(ColorUtil.isColorLight(bgColor)) + } + + open fun setLightNavigationBar(enabled: Boolean) { + if (!ATHUtil.isWindowBackgroundDark(this) && ThemeStore.coloredNavigationBar(this)) { + ATH.setLightNavigationbar(this, enabled) + } + } + + private fun registerSystemUiVisibility() { + val decorView = window.decorView + decorView.setOnSystemUiVisibilityChangeListener { visibility -> + if (visibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) { + setImmersiveFullscreen() + } + } + } + + private fun unregisterSystemUiVisibility() { + val decorView = window.decorView + decorView.setOnSystemUiVisibilityChangeListener(null) + } + + private fun setImmersiveFullscreen() { + val flags = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE + or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN + or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION + or View.SYSTEM_UI_FLAG_FULLSCREEN + or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) + if (PreferenceUtil.getInstance().fullScreenMode) { + window.decorView.systemUiVisibility = flags + } + } + + private fun exitFullscreen() { + window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE + } + + override fun run() { + setImmersiveFullscreen() + } + + override fun onStop() { + handler.removeCallbacks(this) + super.onStop() + } + + public override fun onDestroy() { + super.onDestroy() + unregisterSystemUiVisibility() + exitFullscreen() + } + + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { + handler.removeCallbacks(this) + handler.postDelayed(this, 500) + } + return super.onKeyDown(keyCode, event) + + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.java index a909cf2b..326db21e 100755 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.java @@ -245,10 +245,10 @@ public class AlbumTagEditorActivity extends AbsTagEditorActivity implements Text @NonNull @Override protected List getSongPaths() { - ArrayList songs = AlbumLoader.getAlbum(this, getId()).blockingFirst().songs; + ArrayList songs = AlbumLoader.Companion.getAlbum(this, getId()).blockingFirst().getSongs(); ArrayList paths = new ArrayList<>(songs.size()); for (Song song : songs) { - paths.add(song.data); + paths.add(song.getData()); } return paths; } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.java index 89204692..4672b62e 100755 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.java @@ -147,7 +147,7 @@ public class SongTagEditorActivity extends AbsTagEditorActivity implements TextW @Override protected List getSongPaths() { ArrayList paths = new ArrayList<>(1); - paths.add(SongLoader.Companion.getSong(this, getId()).blockingFirst().data); + paths.add(SongLoader.INSTANCE.getSong(this, getId()).blockingFirst().getData()); return paths; } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.java index 2c1f2144..4e955f2c 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.java @@ -84,7 +84,7 @@ public class CollageSongAdapter extends RecyclerView.Adapter { - MusicPlayerRemote.openQueue(dataSet, 0, true); + MusicPlayerRemote.INSTANCE.openQueue(dataSet, 0, true); }); view.setBackgroundColor(color); view.setTextColor(MaterialValueHelper.getPrimaryTextColor(context, ColorUtil.isColorLight(color))); @@ -96,7 +96,7 @@ public class CollageSongAdapter extends RecyclerView.Adapter { - MusicPlayerRemote.playNext(dataSet.get(startPosition)); + MusicPlayerRemote.INSTANCE.playNext(dataSet.get(startPosition)); }); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/ContributorAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/ContributorAdapter.java deleted file mode 100644 index 6190c77e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/ContributorAdapter.java +++ /dev/null @@ -1,71 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter; - -import android.app.Activity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.ArrayList; -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Contributor; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.views.NetworkImageView; - -import static code.name.monkey.retromusic.util.RetroUtil.openUrl; - -public class ContributorAdapter extends RecyclerView.Adapter { - private List contributors = new ArrayList<>(); - - public ContributorAdapter(List contributors) { - this.contributors = contributors; - } - - public ContributorAdapter() { - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contributor, parent, false)); - } - - @Override - public void onBindViewHolder(@NonNull ViewHolder holder, int position) { - Contributor contributor = contributors.get(position); - holder.bindData(contributor); - } - - @Override - public int getItemCount() { - return contributors.size(); - } - - public class ViewHolder extends MediaEntryViewHolder { - - public ViewHolder(View itemView) { - super(itemView); - } - - void bindData(Contributor contributor) { - if (title != null) { - title.setText(contributor.getName()); - } - if (text != null) { - text.setText(contributor.getSummary()); - } - if (image instanceof NetworkImageView) { - ((NetworkImageView) image).setImageUrl(contributor.getProfileImage()); - } - } - - @Override - public void onClick(View v) { - super.onClick(v); - openUrl((Activity) v.getContext(), contributors.get(getAdapterPosition()).getLink()); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/ContributorAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/ContributorAdapter.kt new file mode 100644 index 00000000..b362892d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/ContributorAdapter.kt @@ -0,0 +1,48 @@ +package code.name.monkey.retromusic.ui.adapter + +import android.app.Activity +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Contributor +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.RetroUtil.openUrl +import code.name.monkey.retromusic.views.NetworkImageView + +class ContributorAdapter(private var contributors: ArrayList) : RecyclerView.Adapter() { + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_contributor, parent, false)) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val contributor = contributors[position] + holder.bindData(contributor) + } + + override fun getItemCount(): Int { + return contributors.size + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + internal fun bindData(contributor: Contributor) { + if (title != null) { + title!!.text = contributor.name + } + if (text != null) { + text!!.text = contributor.summary + } + if (image is NetworkImageView) { + (image as NetworkImageView).setImageUrl(contributor.profileImage) + } + } + + override fun onClick(v: View?) { + super.onClick(v) + openUrl(v!!.context as Activity, contributors[adapterPosition].link) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/GenreAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/GenreAdapter.java deleted file mode 100644 index 1b9ac20e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/GenreAdapter.java +++ /dev/null @@ -1,87 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter; - -import android.app.Activity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.ArrayList; -import java.util.Locale; - -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.NavigationUtil; - -/** - * @author Hemanth S (h4h13). - */ - -public class GenreAdapter extends RecyclerView.Adapter { - private ArrayList mGenres = new ArrayList<>(); - private Activity mActivity; - private int mItemLayoutRes; - - public GenreAdapter(@NonNull Activity activity, ArrayList dataSet, int itemLayoutRes) { - mActivity = activity; - mGenres = dataSet; - mItemLayoutRes = itemLayoutRes; - } - - public ArrayList getDataSet() { - return mGenres; - } - - @NonNull - @Override - public GenreAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new ViewHolder(LayoutInflater.from(mActivity).inflate(mItemLayoutRes, parent, false)); - } - - @Override - public void onBindViewHolder(@NonNull GenreAdapter.ViewHolder holder, int position) { - Genre genre = mGenres.get(position); - if (holder.title != null) { - holder.title.setText(genre.name); - } - if (holder.text != null) { - holder.text.setText(String.format(Locale.getDefault(), "%d %s", genre.songCount, genre.songCount > 1 ? - mActivity.getString(R.string.songs) : - mActivity.getString(R.string.song))); - } - - if (holder.separator != null) { - holder.separator.setVisibility(View.VISIBLE); - } - } - - @Override - public int getItemCount() { - return mGenres.size(); - } - - public void swapDataSet(ArrayList list) { - mGenres = list; - notifyDataSetChanged(); - } - - public class ViewHolder extends MediaEntryViewHolder { - public ViewHolder(View itemView) { - super(itemView); - if (menu != null) { - menu.setVisibility(View.GONE); - } - assert imageContainer != null; - imageContainer.setVisibility(View.GONE); - } - - @Override - public void onClick(View v) { - super.onClick(v); - Genre genre = mGenres.get(getAdapterPosition()); - NavigationUtil.goToGenre(mActivity, genre); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/GenreAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/GenreAdapter.kt new file mode 100644 index 00000000..d9f11dd9 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/GenreAdapter.kt @@ -0,0 +1,73 @@ +package code.name.monkey.retromusic.ui.adapter + +import android.app.Activity +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup + +import java.util.ArrayList +import java.util.Locale +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Genre +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.NavigationUtil + +/** + * @author Hemanth S (h4h13). + */ + +class GenreAdapter(private val mActivity: Activity, dataSet: ArrayList, private val mItemLayoutRes: Int) : RecyclerView.Adapter() { + var dataSet = ArrayList() + private set + + init { + this.dataSet = dataSet + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GenreAdapter.ViewHolder { + return ViewHolder(LayoutInflater.from(mActivity).inflate(mItemLayoutRes, parent, false)) + } + + override fun onBindViewHolder(holder: GenreAdapter.ViewHolder, position: Int) { + val genre = dataSet[position] + if (holder.title != null) { + holder.title!!.text = genre.name + } + if (holder.text != null) { + holder.text!!.text = String.format(Locale.getDefault(), "%d %s", genre.songCount, if (genre.songCount > 1) + mActivity.getString(R.string.songs) + else + mActivity.getString(R.string.song)) + } + + if (holder.separator != null) { + holder.separator!!.visibility = View.VISIBLE + } + } + + override fun getItemCount(): Int { + return dataSet.size + } + + fun swapDataSet(list: ArrayList) { + dataSet = list + notifyDataSetChanged() + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + init { + if (menu != null) { + menu!!.visibility = View.GONE + } + assert(imageContainer != null) + imageContainer!!.visibility = View.GONE + } + + override fun onClick(v: View?) { + super.onClick(v) + val genre = dataSet[adapterPosition] + NavigationUtil.goToGenre(mActivity, genre) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SearchAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SearchAdapter.java deleted file mode 100644 index 8198722d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SearchAdapter.java +++ /dev/null @@ -1,163 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter; - -import androidx.annotation.NonNull; -import androidx.core.util.Pair; -import androidx.appcompat.app.AppCompatActivity; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; - -import java.util.ArrayList; -import java.util.List; - -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.ArtistGlideRequest; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.menu.SongMenuHelper; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; - - -public class SearchAdapter extends RecyclerView.Adapter { - - private static final int HEADER = 0; - private static final int ALBUM = 1; - private static final int ARTIST = 2; - private static final int SONG = 3; - - private final AppCompatActivity activity; - private List dataSet; - - public SearchAdapter(@NonNull AppCompatActivity activity, @NonNull List dataSet) { - this.activity = activity; - this.dataSet = dataSet; - } - - public void swapDataSet(@NonNull ArrayList dataSet) { - this.dataSet = dataSet; - notifyDataSetChanged(); - } - - @Override - public int getItemViewType(int position) { - if (dataSet.get(position) instanceof Album) return ALBUM; - if (dataSet.get(position) instanceof Artist) return ARTIST; - if (dataSet.get(position) instanceof Song) return SONG; - return HEADER; - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - if (viewType == HEADER) - return new ViewHolder(LayoutInflater.from(activity).inflate(R.layout.sub_header, parent, false), viewType); - return new ViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_list, parent, false), viewType); - } - - @SuppressWarnings("ConstantConditions") - @Override - public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { - switch (getItemViewType(position)) { - case ALBUM: - final Album album = (Album) dataSet.get(position); - holder.title.setText(album.getTitle()); - holder.text.setText(album.getArtistName()); - SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) - .checkIgnoreMediaStore(activity).build() - .into(holder.image); - break; - case ARTIST: - final Artist artist = (Artist) dataSet.get(position); - holder.title.setText(artist.getName()); - holder.text.setText(MusicUtil.getArtistInfoString(activity, artist)); - ArtistGlideRequest.Builder.from(Glide.with(activity), artist) - .build().into(holder.image); - break; - case SONG: - final Song song = (Song) dataSet.get(position); - holder.title.setText(song.title); - holder.text.setText(song.albumName); - break; - default: - holder.title.setText(dataSet.get(position).toString()); - holder.title.setTextColor(ThemeStore.accentColor(activity)); - break; - } - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - public class ViewHolder extends MediaEntryViewHolder { - public ViewHolder(@NonNull View itemView, int itemViewType) { - super(itemView); - itemView.setOnLongClickListener(null); - - if (itemViewType != HEADER) { - if (separator != null) { - separator.setVisibility(View.GONE); - } - } - - if (menu != null) { - if (itemViewType == SONG) { - menu.setVisibility(View.VISIBLE); - menu.setOnClickListener(new SongMenuHelper.OnClickSongMenu(activity) { - @Override - public Song getSong() { - return (Song) dataSet.get(getAdapterPosition()); - } - }); - } else { - menu.setVisibility(View.GONE); - } - } - - switch (itemViewType) { - case ALBUM: - setImageTransitionName(activity.getString(R.string.transition_album_art)); - break; - case ARTIST: - setImageTransitionName(activity.getString(R.string.transition_artist_image)); - break; - default: - View container = itemView.findViewById(R.id.image_container); - if (container != null) { - container.setVisibility(View.GONE); - } - break; - } - } - - @Override - public void onClick(View view) { - Object item = dataSet.get(getAdapterPosition()); - switch (getItemViewType()) { - case ALBUM: - NavigationUtil.goToAlbum(activity, - ((Album) item).getId(), Pair.create(image, activity.getResources().getString(R.string.transition_album_art))); - break; - case ARTIST: - NavigationUtil.goToArtist(activity, - ((Artist) item).getId(), Pair.create(image, activity.getResources().getString(R.string.transition_artist_image))); - break; - case SONG: - ArrayList playList = new ArrayList<>(); - playList.add((Song) item); - MusicPlayerRemote.openQueue(playList, 0, true); - break; - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SearchAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SearchAdapter.kt new file mode 100644 index 00000000..58d66083 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SearchAdapter.kt @@ -0,0 +1,132 @@ +package code.name.monkey.retromusic.ui.adapter + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.util.Pair +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.ArtistGlideRequest +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.menu.SongMenuHelper +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import com.bumptech.glide.Glide +import java.util.* + + +class SearchAdapter(private val activity: AppCompatActivity, private var dataSet: List?) : RecyclerView.Adapter() { + + fun swapDataSet(dataSet: ArrayList) { + this.dataSet = dataSet + notifyDataSetChanged() + } + + override fun getItemViewType(position: Int): Int { + if (dataSet!![position] is Album) return ALBUM + if (dataSet!![position] is Artist) return ARTIST + return if (dataSet!![position] is Song) SONG else HEADER + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return if (viewType == HEADER) ViewHolder(LayoutInflater.from(activity).inflate(R.layout.sub_header, parent, false), viewType) else ViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_list, parent, false), viewType) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + when (getItemViewType(position)) { + ALBUM -> { + val album = dataSet!![position] as Album + holder.title!!.text = album.title + holder.text!!.text = album.artistName + SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) + .checkIgnoreMediaStore(activity).build() + .into(holder.image!!) + } + ARTIST -> { + val artist = dataSet!![position] as Artist + holder.title!!.text = artist.name + holder.text!!.text = MusicUtil.getArtistInfoString(activity, artist) + ArtistGlideRequest.Builder.from(Glide.with(activity), artist) + .build().into(holder.image!!) + } + SONG -> { + val song = dataSet!![position] as Song + holder.title!!.text = song.title + holder.text!!.text = song.albumName + } + else -> { + holder.title!!.text = dataSet!![position].toString() + holder.title!!.setTextColor(ThemeStore.accentColor(activity)) + } + } + } + + override fun getItemCount(): Int { + return dataSet!!.size + } + + inner class ViewHolder(itemView: View, itemViewType: Int) : MediaEntryViewHolder(itemView) { + init { + itemView.setOnLongClickListener(null) + + if (itemViewType != HEADER) { + if (separator != null) { + separator!!.visibility = View.GONE + } + } + + if (menu != null) { + if (itemViewType == SONG) { + menu!!.visibility = View.VISIBLE + menu!!.setOnClickListener(object : SongMenuHelper.OnClickSongMenu(activity) { + override val song: Song + get() = dataSet!![adapterPosition] as Song + }) + } else { + menu!!.visibility = View.GONE + } + } + + when (itemViewType) { + ALBUM -> setImageTransitionName(activity.getString(R.string.transition_album_art)) + ARTIST -> setImageTransitionName(activity.getString(R.string.transition_artist_image)) + else -> { + val container = itemView.findViewById(R.id.image_container) + if (container != null) { + container.visibility = View.GONE + } + } + } + } + + override fun onClick(v: View?) { + val item = dataSet!![adapterPosition] + when (itemViewType) { + ALBUM -> NavigationUtil.goToAlbum(activity, + (item as Album).id, Pair.create(image, activity.resources.getString(R.string.transition_album_art))) + ARTIST -> NavigationUtil.goToArtist(activity, + (item as Artist).id, Pair.create(image, activity.resources.getString(R.string.transition_artist_image))) + SONG -> { + val playList = ArrayList() + playList.add(item as Song) + MusicPlayerRemote.openQueue(playList, 0, true) + } + } + } + } + + companion object { + + private val HEADER = 0 + private val ALBUM = 1 + private val ARTIST = 2 + private val SONG = 3 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SongFileAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SongFileAdapter.java deleted file mode 100644 index 8a110673..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SongFileAdapter.java +++ /dev/null @@ -1,215 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter; - -import android.graphics.PorterDuff; -import android.graphics.drawable.Drawable; -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.load.engine.DiskCacheStrategy; -import com.bumptech.glide.signature.MediaStoreSignature; -import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; - -import java.io.File; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; - -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.audiocover.AudioFileCover; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.RetroUtil; - -public class SongFileAdapter extends AbsMultiSelectAdapter implements FastScrollRecyclerView.SectionedAdapter { - - private static final int FILE = 0; - private static final int FOLDER = 1; - - private final AppCompatActivity activity; - private final int itemLayoutRes; - @Nullable - private final Callbacks callbacks; - private List dataSet; - - public SongFileAdapter(@NonNull AppCompatActivity activity, @NonNull List songFiles, @LayoutRes int itemLayoutRes, @Nullable Callbacks callback, @Nullable CabHolder cabHolder) { - super(activity, cabHolder, R.menu.menu_media_selection); - this.activity = activity; - this.dataSet = songFiles; - this.itemLayoutRes = itemLayoutRes; - this.callbacks = callback; - setHasStableIds(true); - } - - public static String readableFileSize(long size) { - if (size <= 0) return size + " B"; - final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"}; - int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); - return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; - } - - @Override - public int getItemViewType(int position) { - return dataSet.get(position).isDirectory() ? FOLDER : FILE; - } - - @Override - public long getItemId(int position) { - return dataSet.get(position).hashCode(); - } - - public void swapDataSet(@NonNull List songFiles) { - this.dataSet = songFiles; - notifyDataSetChanged(); - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new ViewHolder(LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)); - } - - @Override - public void onBindViewHolder(@NonNull final ViewHolder holder, int index) { - final File file = dataSet.get(index); - - holder.itemView.setActivated(isChecked(file)); - - if (holder.getAdapterPosition() == getItemCount() - 1) { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.GONE); - } - } else { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.VISIBLE); - } - } - - if (holder.title != null) { - holder.title.setText(getFileTitle(file)); - } - if (holder.text != null) { - if (holder.getItemViewType() == FILE) { - holder.text.setText(getFileText(file)); - } else { - holder.text.setVisibility(View.GONE); - } - } - - if (holder.image != null) { - loadFileImage(file, holder); - } - } - - protected String getFileTitle(File file) { - return file.getName(); - } - - protected String getFileText(File file) { - return file.isDirectory() ? null : readableFileSize(file.length()); - } - - @SuppressWarnings("ConstantConditions") - protected void loadFileImage(File file, final ViewHolder holder) { - final int iconColor = ATHUtil.resolveColor(activity, R.attr.iconColor); - if (file.isDirectory()) { - holder.image.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN); - holder.image.setImageResource(R.drawable.ic_folder_white_24dp); - } else { - Drawable error = RetroUtil.getTintedVectorDrawable(activity, R.drawable.ic_file_music_white_24dp, iconColor); - Glide.with(activity) - .load(new AudioFileCover(file.getPath())) - .diskCacheStrategy(DiskCacheStrategy.NONE) - .error(error) - .placeholder(error) - .animate(android.R.anim.fade_in) - .signature(new MediaStoreSignature("", file.lastModified(), 0)) - .into(holder.image); - } - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - @Override - protected File getIdentifier(int position) { - return dataSet.get(position); - } - - @Override - protected String getName(File object) { - return getFileTitle(object); - } - - @Override - protected void onMultipleItemAction(MenuItem menuItem, ArrayList selection) { - if (callbacks == null) return; - callbacks.onMultipleItemAction(menuItem, selection); - } - - @NonNull - @Override - public String getSectionName(int position) { - return String.valueOf(dataSet.get(position).getName().charAt(0)).toUpperCase(); - } - - public interface Callbacks { - void onFileSelected(File file); - - void onFileMenuClicked(File file, View view); - - void onMultipleItemAction(MenuItem item, ArrayList files); - } - - public class ViewHolder extends MediaEntryViewHolder { - - public ViewHolder(View itemView) { - super(itemView); - if (menu != null && callbacks != null) { - menu.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - int position = getAdapterPosition(); - if (isPositionInRange(position)) { - callbacks.onFileMenuClicked(dataSet.get(position), v); - } - } - }); - } - } - - @Override - public void onClick(View v) { - int position = getAdapterPosition(); - if (isPositionInRange(position)) { - if (isInQuickSelectMode()) { - toggleChecked(position); - } else { - if (callbacks != null) { - callbacks.onFileSelected(dataSet.get(position)); - } - } - } - } - - @Override - public boolean onLongClick(View view) { - int position = getAdapterPosition(); - return isPositionInRange(position) && toggleChecked(position); - } - - private boolean isPositionInRange(int position) { - return position >= 0 && position < dataSet.size(); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SongFileAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SongFileAdapter.kt new file mode 100644 index 00000000..0bad9a4f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/SongFileAdapter.kt @@ -0,0 +1,180 @@ +package code.name.monkey.retromusic.ui.adapter + +import android.graphics.PorterDuff +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.audiocover.AudioFileCover +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.RetroUtil +import com.bumptech.glide.Glide +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.signature.MediaStoreSignature +import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView +import java.io.File +import java.text.DecimalFormat +import java.util.* + +class SongFileAdapter(private val activity: AppCompatActivity, private var dataSet: List?, @param:LayoutRes private val itemLayoutRes: Int, private val callbacks: Callbacks?, cabHolder: CabHolder?) : AbsMultiSelectAdapter(activity, cabHolder, R.menu.menu_media_selection), FastScrollRecyclerView.SectionedAdapter { + + init { + this.setHasStableIds(true) + } + + override fun getItemViewType(position: Int): Int { + return if (dataSet!![position].isDirectory) FOLDER else FILE + } + + override fun getItemId(position: Int): Long { + return dataSet!![position].hashCode().toLong() + } + + fun swapDataSet(songFiles: List) { + this.dataSet = songFiles + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return ViewHolder(LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)) + } + + override fun onBindViewHolder(holder: ViewHolder, index: Int) { + val file = dataSet!![index] + + holder.itemView.isActivated = isChecked(file) + + if (holder.adapterPosition == itemCount - 1) { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.GONE + } + } else { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.VISIBLE + } + } + + if (holder.title != null) { + holder.title!!.text = getFileTitle(file) + } + if (holder.text != null) { + if (holder.itemViewType == FILE) { + holder.text!!.text = getFileText(file) + } else { + holder.text!!.visibility = View.GONE + } + } + + if (holder.image != null) { + loadFileImage(file, holder) + } + } + + private fun getFileTitle(file: File): String { + return file.name + } + + private fun getFileText(file: File): String? { + return if (file.isDirectory) null else readableFileSize(file.length()) + } + + private fun loadFileImage(file: File, holder: ViewHolder) { + val iconColor = ATHUtil.resolveColor(activity, R.attr.iconColor) + if (file.isDirectory) { + holder.image!!.setColorFilter(iconColor, PorterDuff.Mode.SRC_IN) + holder.image!!.setImageResource(R.drawable.ic_folder_white_24dp) + } else { + val error = RetroUtil.getTintedVectorDrawable(activity, R.drawable.ic_file_music_white_24dp, iconColor) + Glide.with(activity) + .load(AudioFileCover(file.path)) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .error(error) + .placeholder(error) + .animate(android.R.anim.fade_in) + .signature(MediaStoreSignature("", file.lastModified(), 0)) + .into(holder.image!!) + } + } + + override fun getItemCount(): Int { + return dataSet!!.size + } + + override fun getIdentifier(position: Int): File? { + return dataSet!![position] + } + + override fun getName(`object`: File): String { + return getFileTitle(`object`) + } + + override fun onMultipleItemAction(menuItem: MenuItem, selection: ArrayList) { + if (callbacks == null) return + callbacks.onMultipleItemAction(menuItem, selection) + } + + override fun getSectionName(position: Int): String { + return dataSet!![position].name[0].toString().toUpperCase() + } + + interface Callbacks { + fun onFileSelected(file: File) + + fun onFileMenuClicked(file: File, view: View) + + fun onMultipleItemAction(item: MenuItem, files: ArrayList) + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + init { + if (menu != null && callbacks != null) { + menu!!.setOnClickListener { v -> + val position = adapterPosition + if (isPositionInRange(position)) { + callbacks.onFileMenuClicked(dataSet!![position], v) + } + } + } + } + + override fun onClick(v: View?) { + val position = adapterPosition + if (isPositionInRange(position)) { + if (isInQuickSelectMode) { + toggleChecked(position) + } else { + callbacks?.onFileSelected(dataSet!![position]) + } + } + } + + override fun onLongClick(v: View?): Boolean { + val position = adapterPosition + return isPositionInRange(position) && toggleChecked(position) + } + + private fun isPositionInRange(position: Int): Boolean { + return position >= 0 && position < dataSet!!.size + } + } + + companion object { + + private const val FILE = 0 + private const val FOLDER = 1 + + fun readableFileSize(size: Long): String { + if (size <= 0) return size.toString() + " B" + val units = arrayOf("B", "KB", "MB", "GB", "TB") + val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt() + return DecimalFormat("#,##0.##").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups] + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumAdapter.java deleted file mode 100644 index 90bfd72d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumAdapter.java +++ /dev/null @@ -1,249 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.album; - -import android.content.res.ColorStateList; -import android.graphics.drawable.Drawable; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; -import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; - -import java.util.ArrayList; -import java.util.List; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.util.Pair; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.SortOrder; -import code.name.monkey.retromusic.helper.menu.SongsMenuHelper; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - - -public class AlbumAdapter extends AbsMultiSelectAdapter implements - FastScrollRecyclerView.SectionedAdapter { - - public static final String TAG = AlbumAdapter.class.getSimpleName(); - - protected final AppCompatActivity activity; - protected ArrayList dataSet; - - protected int itemLayoutRes; - - protected boolean usePalette = false; - - - public AlbumAdapter(@NonNull AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes, boolean usePalette, - @Nullable CabHolder cabHolder) { - super(activity, cabHolder, R.menu.menu_media_selection); - this.activity = activity; - this.dataSet = dataSet; - this.itemLayoutRes = itemLayoutRes; - this.usePalette = usePalette; - setHasStableIds(true); - - } - - - public void useItemLayout(int itemLayoutRes) { - this.itemLayoutRes = itemLayoutRes; - notifyDataSetChanged(); - } - - public void usePalette(boolean usePalette) { - this.usePalette = usePalette; - notifyDataSetChanged(); - } - - public void swapDataSet(ArrayList dataSet) { - this.dataSet = dataSet; - notifyDataSetChanged(); - } - - public ArrayList getDataSet() { - return dataSet; - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View view = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false); - return createViewHolder(view, viewType); - } - - protected ViewHolder createViewHolder(View view, int viewType) { - return new ViewHolder(view); - } - - private String getAlbumTitle(Album album) { - return album.getTitle(); - } - - protected String getAlbumText(Album album) { - return album.getArtistName(); - } - - @Override - public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { - final Album album = dataSet.get(position); - - final boolean isChecked = isChecked(album); - holder.itemView.setActivated(isChecked); - - if (holder.getAdapterPosition() == getItemCount() - 1) { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.GONE); - } - } else { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.VISIBLE); - } - } - - if (holder.title != null) { - holder.title.setText(getAlbumTitle(album)); - } - if (holder.text != null) { - holder.text.setText(getAlbumText(album)); - } - if (holder.playSongs != null) { - holder.playSongs.setOnClickListener(v -> MusicPlayerRemote.openQueue(album.songs, 0, true)); - } - loadAlbumCover(album, holder); - } - - protected void setColors(int color, ViewHolder holder) { - if (holder.paletteColorContainer != null) { - holder.paletteColorContainer.setBackgroundColor(color); - if (holder.title != null) { - holder.title.setTextColor(MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))); - } - if (holder.text != null) { - holder.text.setTextColor(MaterialValueHelper.getSecondaryTextColor(activity, ColorUtil.isColorLight(color))); - } - } - if (holder.mask != null) { - holder.mask.setBackgroundTintList(ColorStateList.valueOf(color)); - } - } - - protected void loadAlbumCover(Album album, final ViewHolder holder) { - if (holder.image == null) { - return; - } - - SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) - .checkIgnoreMediaStore(activity) - .generatePalette(activity).build() - .into(new RetroMusicColoredTarget(holder.image) { - @Override - public void onLoadCleared(Drawable placeholder) { - super.onLoadCleared(placeholder); - setColors(getDefaultFooterColor(), holder); - } - - @Override - public void onColorReady(int color) { - setColors(color, holder); - } - }); - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - @Override - public long getItemId(int position) { - return dataSet.get(position).getId(); - } - - @Override - protected Album getIdentifier(int position) { - return dataSet.get(position); - } - - @Override - protected String getName(Album album) { - return album.getTitle(); - } - - @Override - protected void onMultipleItemAction(@NonNull MenuItem menuItem, - @NonNull ArrayList selection) { - SongsMenuHelper.handleMenuClick(activity, getSongList(selection), menuItem.getItemId()); - } - - @NonNull - private ArrayList getSongList(@NonNull List albums) { - final ArrayList songs = new ArrayList<>(); - for (Album album : albums) { - songs.addAll(album.songs); - } - return songs; - } - - @NonNull - @Override - public String getSectionName(int position) { - @Nullable String sectionName = null; - switch (PreferenceUtil.getInstance().getAlbumSortOrder()) { - case SortOrder.AlbumSortOrder.ALBUM_A_Z: - case SortOrder.AlbumSortOrder.ALBUM_Z_A: - sectionName = dataSet.get(position).getTitle(); - break; - case SortOrder.AlbumSortOrder.ALBUM_ARTIST: - sectionName = dataSet.get(position).getArtistName(); - break; - case SortOrder.AlbumSortOrder.ALBUM_YEAR: - return MusicUtil.getYearString(dataSet.get(position).getYear()); - } - - return MusicUtil.getSectionName(sectionName); - } - - public class ViewHolder extends MediaEntryViewHolder { - - public ViewHolder(@NonNull final View itemView) { - super(itemView); - setImageTransitionName(activity.getString(R.string.transition_album_art)); - if (menu != null) { - menu.setVisibility(View.GONE); - } - } - - @Override - public void onClick(View v) { - if (isInQuickSelectMode()) { - toggleChecked(getAdapterPosition()); - } else { - Pair[] albumPairs = new Pair[]{Pair.create(image, activity.getResources().getString(R.string.transition_album_art))}; - NavigationUtil.goToAlbum(activity, dataSet.get(getAdapterPosition()).getId(), albumPairs); - } - } - - @Override - public boolean onLongClick(View view) { - toggleChecked(getAdapterPosition()); - return true; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumAdapter.kt new file mode 100644 index 00000000..301a335e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumAdapter.kt @@ -0,0 +1,214 @@ +package code.name.monkey.retromusic.ui.adapter.album + +import android.content.res.ColorStateList +import android.graphics.drawable.Drawable +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import androidx.core.util.Pair +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.MaterialValueHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.SortOrder +import code.name.monkey.retromusic.helper.menu.SongsMenuHelper +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import com.bumptech.glide.Glide +import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView +import java.util.* + + +open class AlbumAdapter(protected val activity: AppCompatActivity, + dataSet: ArrayList, + @param:LayoutRes protected var itemLayoutRes: Int, + usePalette: Boolean, + cabHolder: CabHolder?) : AbsMultiSelectAdapter(activity, cabHolder, R.menu.menu_media_selection), FastScrollRecyclerView.SectionedAdapter { + var dataSet: ArrayList + protected set + + protected var usePalette = false + + + init { + this.dataSet = dataSet + this.usePalette = usePalette + this.setHasStableIds(true) + } + + fun useItemLayout(itemLayoutRes: Int) { + this.itemLayoutRes = itemLayoutRes + notifyDataSetChanged() + } + + fun usePalette(usePalette: Boolean) { + this.usePalette = usePalette + notifyDataSetChanged() + } + + fun swapDataSet(dataSet: ArrayList) { + this.dataSet = dataSet + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false) + return createViewHolder(view, viewType) + } + + protected open fun createViewHolder(view: View, viewType: Int): ViewHolder { + return ViewHolder(view) + } + + private fun getAlbumTitle(album: Album): String? { + return album.title + } + + protected open fun getAlbumText(album: Album): String? { + return album.artistName + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val album = dataSet[position] + + val isChecked = isChecked(album) + holder.itemView.isActivated = isChecked + + if (holder.adapterPosition == itemCount - 1) { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.GONE + } + } else { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.VISIBLE + } + } + + if (holder.title != null) { + holder.title!!.text = getAlbumTitle(album) + } + if (holder.text != null) { + holder.text!!.text = getAlbumText(album) + } + if (holder.playSongs != null) { + holder.playSongs!!.setOnClickListener { MusicPlayerRemote.openQueue(album.songs!!, 0, true) } + } + loadAlbumCover(album, holder) + } + + protected open fun setColors(color: Int, holder: ViewHolder) { + if (holder.paletteColorContainer != null) { + holder.paletteColorContainer!!.setBackgroundColor(color) + if (holder.title != null) { + holder.title!!.setTextColor(MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))) + } + if (holder.text != null) { + holder.text!!.setTextColor(MaterialValueHelper.getSecondaryTextColor(activity, ColorUtil.isColorLight(color))) + } + } + if (holder.mask != null) { + holder.mask!!.backgroundTintList = ColorStateList.valueOf(color) + } + } + + protected open fun loadAlbumCover(album: Album, holder: ViewHolder) { + if (holder.image == null) { + return + } + + SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) + .checkIgnoreMediaStore(activity) + .generatePalette(activity).build() + .into(object : RetroMusicColoredTarget(holder.image!!) { + override fun onLoadCleared(placeholder: Drawable?) { + super.onLoadCleared(placeholder) + setColors(defaultFooterColor, holder) + } + + override fun onColorReady(color: Int) { + setColors(color, holder) + } + }) + } + + override fun getItemCount(): Int { + return dataSet.size + } + + override fun getItemId(position: Int): Long { + return dataSet[position].id.toLong() + } + + override fun getIdentifier(position: Int): Album? { + return dataSet[position] + } + + override fun getName(album: Album): String { + return album.title!! + } + + override fun onMultipleItemAction(menuItem: MenuItem, + selection: ArrayList) { + SongsMenuHelper.handleMenuClick(activity, getSongList(selection), menuItem.itemId) + } + + private fun getSongList(albums: List): ArrayList { + val songs = ArrayList() + for (album in albums) { + songs.addAll(album.songs!!) + } + return songs + } + + override fun getSectionName(position: Int): String { + var sectionName: String? = null + when (PreferenceUtil.getInstance().albumSortOrder) { + SortOrder.AlbumSortOrder.ALBUM_A_Z, SortOrder.AlbumSortOrder.ALBUM_Z_A -> sectionName = dataSet[position].title + SortOrder.AlbumSortOrder.ALBUM_ARTIST -> sectionName = dataSet[position].artistName + SortOrder.AlbumSortOrder.ALBUM_YEAR -> return MusicUtil.getYearString(dataSet[position].year) + } + + return MusicUtil.getSectionName(sectionName) + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + init { + setImageTransitionName(activity.getString(R.string.transition_album_art)) + if (menu != null) { + menu!!.visibility = View.GONE + } + } + + override fun onClick(v: View?) { + super.onClick(v) + if (isInQuickSelectMode) { + toggleChecked(adapterPosition) + } else { + val albumPairs = arrayOf>(Pair.create(image, activity.resources.getString(R.string.transition_album_art))) + NavigationUtil.goToAlbum(activity, dataSet[adapterPosition].id, *albumPairs) + } + } + + override fun onLongClick(v: View?): Boolean { + toggleChecked(adapterPosition) + return super.onLongClick(v) + } + } + + companion object { + + val TAG = AlbumAdapter::class.java.simpleName + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumCoverPagerAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumCoverPagerAdapter.java deleted file mode 100644 index 6fe11538..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumCoverPagerAdapter.java +++ /dev/null @@ -1,200 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.album; - -import android.content.Intent; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import com.bumptech.glide.Glide; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.misc.CustomFragmentStatePagerAdapter; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.activities.LyricsActivity; -import code.name.monkey.retromusic.util.PreferenceUtil; - - -public class AlbumCoverPagerAdapter extends CustomFragmentStatePagerAdapter { - - public static final String TAG = AlbumCoverPagerAdapter.class.getSimpleName(); - - private ArrayList dataSet; - - private AlbumCoverFragment.ColorReceiver currentColorReceiver; - private int currentColorReceiverPosition = -1; - - public AlbumCoverPagerAdapter(FragmentManager fm, ArrayList dataSet) { - super(fm); - this.dataSet = dataSet; - } - - @Override - public Fragment getItem(final int position) { - return AlbumCoverFragment.newInstance(dataSet.get(position)); - } - - @Override - public int getCount() { - return dataSet.size(); - } - - @NonNull - @Override - public Object instantiateItem(ViewGroup container, int position) { - Object o = super.instantiateItem(container, position); - if (currentColorReceiver != null && currentColorReceiverPosition == position) { - receiveColor(currentColorReceiver, currentColorReceiverPosition); - } - return o; - } - - /** - * Only the latest passed {@link AlbumCoverFragment.ColorReceiver} is guaranteed to receive a - * response - */ - public void receiveColor(AlbumCoverFragment.ColorReceiver colorReceiver, int position) { - AlbumCoverFragment fragment = (AlbumCoverFragment) getFragment(position); - if (fragment != null) { - currentColorReceiver = null; - currentColorReceiverPosition = -1; - fragment.receiveColor(colorReceiver, position); - } else { - currentColorReceiver = colorReceiver; - currentColorReceiverPosition = position; - } - } - - public static class AlbumCoverFragment extends Fragment { - - private static final String SONG_ARG = "song"; - @BindView(R.id.player_image) - ImageView albumCover; - private Unbinder unbinder; - private boolean isColorReady; - private int color; - private Song song; - private ColorReceiver colorReceiver; - private int request; - - public static AlbumCoverFragment newInstance(final Song song) { - AlbumCoverFragment frag = new AlbumCoverFragment(); - final Bundle args = new Bundle(); - args.putParcelable(SONG_ARG, song); - frag.setArguments(args); - return frag; - } - - @Override - public void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (getArguments() != null) { - song = getArguments().getParcelable(SONG_ARG); - } - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - int layout = getLayout(); - View view = inflater.inflate(layout, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - private int getLayout() { - int layout; - switch (PreferenceUtil.getInstance().getAlbumCoverStyle()) { - default: - case NORMAL: - layout = R.layout.fragment_album_cover; - break; - case FLAT: - layout = R.layout.fragment_album_flat_cover; - break; - case CIRCLE: - layout = R.layout.fragment_album_circle_cover; - break; - case CARD: - layout = R.layout.fragment_album_card_cover; - break; - case MATERIAL: - layout = R.layout.fragment_album_material_cover; - break; - case FULL: - layout = R.layout.fragment_album_full_cover; - break; - case FULL_CARD: - layout = R.layout.fragment_album_full_card_cover; - break; - } - return layout; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - loadAlbumCover(); - } - - @OnClick(R.id.player_image) - void showLyrics() { - startActivity(new Intent(getContext(), LyricsActivity.class)); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - colorReceiver = null; - } - - private void loadAlbumCover() { - SongGlideRequest.Builder.from(Glide.with(getContext()), song) - .checkIgnoreMediaStore(getActivity()) - .generatePalette(getActivity()).build() - .into(new RetroMusicColoredTarget(albumCover) { - @Override - public void onColorReady(int color) { - setColor(color); - } - }); - } - - private void setColor(int color) { - this.color = color; - isColorReady = true; - if (colorReceiver != null) { - colorReceiver.onColorReady(color, request); - colorReceiver = null; - } - } - - void receiveColor(ColorReceiver colorReceiver, int request) { - if (isColorReady) { - colorReceiver.onColorReady(color, request); - } else { - this.colorReceiver = colorReceiver; - this.request = request; - } - } - - public interface ColorReceiver { - - void onColorReady(int color, int request); - } - } -} - diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumCoverPagerAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumCoverPagerAdapter.kt new file mode 100644 index 00000000..fc902b49 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumCoverPagerAdapter.kt @@ -0,0 +1,172 @@ +package code.name.monkey.retromusic.ui.adapter.album + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.misc.CustomFragmentStatePagerAdapter +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.activities.LyricsActivity +import code.name.monkey.retromusic.ui.fragments.AlbumCoverStyle +import code.name.monkey.retromusic.util.PreferenceUtil +import com.bumptech.glide.Glide +import java.util.* + + +class AlbumCoverPagerAdapter(fm: FragmentManager, private val dataSet: ArrayList) : CustomFragmentStatePagerAdapter(fm) { + + private var currentColorReceiver: AlbumCoverFragment.ColorReceiver? = null + private var currentColorReceiverPosition = -1 + + override fun getItem(position: Int): Fragment { + return AlbumCoverFragment.newInstance(dataSet[position]) + } + + override fun getCount(): Int { + return dataSet.size + } + + override fun instantiateItem(container: ViewGroup, position: Int): Any { + val o = super.instantiateItem(container, position) + if (currentColorReceiver != null && currentColorReceiverPosition == position) { + receiveColor(currentColorReceiver!!, currentColorReceiverPosition) + } + return o + } + + /** + * Only the latest passed [AlbumCoverFragment.ColorReceiver] is guaranteed to receive a + * response + */ + fun receiveColor(colorReceiver: AlbumCoverFragment.ColorReceiver, position: Int) { + + if (getFragment(position) is AlbumCoverFragment) { + val fragment = getFragment(position) as AlbumCoverFragment + currentColorReceiver = null + currentColorReceiverPosition = -1 + fragment.receiveColor(colorReceiver, position) + } else { + currentColorReceiver = colorReceiver + currentColorReceiverPosition = position + } + + /*val fragment = getFragment(position) as AlbumCoverFragment + if (fragment != null) { + currentColorReceiver = null + currentColorReceiverPosition = -1 + fragment.receiveColor(colorReceiver, position) + } else { + currentColorReceiver = colorReceiver + currentColorReceiverPosition = position + }*/ + } + + class AlbumCoverFragment : Fragment() { + + lateinit var albumCover: ImageView + private var isColorReady: Boolean = false + private var color: Int = 0 + private var song: Song? = null + private var colorReceiver: ColorReceiver? = null + private var request: Int = 0 + + private val layout: Int + get() { + return when (PreferenceUtil.getInstance().albumCoverStyle) { + AlbumCoverStyle.NORMAL -> R.layout.fragment_album_cover + AlbumCoverStyle.FLAT -> R.layout.fragment_album_flat_cover + AlbumCoverStyle.CIRCLE -> R.layout.fragment_album_circle_cover + AlbumCoverStyle.CARD -> R.layout.fragment_album_card_cover + AlbumCoverStyle.MATERIAL -> R.layout.fragment_album_material_cover + AlbumCoverStyle.FULL -> R.layout.fragment_album_full_cover + AlbumCoverStyle.FULL_CARD -> R.layout.fragment_album_full_card_cover + else -> R.layout.fragment_album_cover + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (arguments != null) { + song = arguments!!.getParcelable(SONG_ARG) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val layout = layout + val view = inflater.inflate(layout, container, false) + albumCover = view.findViewById(R.id.player_image) + albumCover.setOnClickListener { startActivity(Intent(context, LyricsActivity::class.java)) } + return view + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + loadAlbumCover() + } + + + override fun onDestroyView() { + super.onDestroyView() + colorReceiver = null + } + + private fun loadAlbumCover() { + SongGlideRequest.Builder.from(Glide.with(context), song) + .checkIgnoreMediaStore(activity) + .generatePalette(activity).build() + .into(object : RetroMusicColoredTarget(albumCover) { + override fun onColorReady(color: Int) { + setColor(color) + } + }) + } + + private fun setColor(color: Int) { + this.color = color + isColorReady = true + if (colorReceiver != null) { + colorReceiver!!.onColorReady(color, request) + colorReceiver = null + } + } + + internal fun receiveColor(colorReceiver: ColorReceiver, request: Int) { + if (isColorReady) { + colorReceiver.onColorReady(color, request) + } else { + this.colorReceiver = colorReceiver + this.request = request + } + } + + interface ColorReceiver { + + fun onColorReady(color: Int, request: Int) + } + + companion object { + + private const val SONG_ARG = "song" + + fun newInstance(song: Song): AlbumCoverFragment { + val frag = AlbumCoverFragment() + val args = Bundle() + args.putParcelable(SONG_ARG, song) + frag.arguments = args + return frag + } + } + } + + companion object { + val TAG: String = AlbumCoverPagerAdapter::class.java.simpleName + } +} + diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumFullWithAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumFullWithAdapter.java deleted file mode 100644 index 348619b3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumFullWithAdapter.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2017. Alexander Bilchuk - * - * 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 code.name.monkey.retromusic.ui.adapter.album; - -import android.app.Activity; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import androidx.annotation.NonNull; -import androidx.core.util.Pair; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; - -import java.util.ArrayList; -import java.util.List; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.views.MetalRecyclerViewPager; - -public class AlbumFullWithAdapter extends - MetalRecyclerViewPager.MetalAdapter { - - private Activity activity; - private List dataSet = new ArrayList<>(); - - public AlbumFullWithAdapter(@NonNull Activity activity, - @NonNull DisplayMetrics metrics) { - super(metrics); - this.activity = activity; - } - - public void swapData(ArrayList list) { - dataSet = list; - notifyDataSetChanged(); - } - - @NonNull - @Override - public FullMetalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View viewItem = LayoutInflater.from(parent.getContext()) - .inflate(R.layout.pager_item, parent, false); - return new FullMetalViewHolder(viewItem); - } - - private Bitmap combineImageIntoOne(ArrayList bitmap) { - int w = 0, h = 0; - for (int i = 0; i < bitmap.size(); i++) { - if (i < bitmap.size() - 1) { - h = bitmap.get(i).getWidth() > bitmap.get(i + 1).getWidth() ? bitmap.get(i).getWidth() - : bitmap.get(i + 1).getWidth(); - } - w += bitmap.get(i).getHeight(); - } - - Bitmap temp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); - Canvas canvas = new Canvas(temp); - int top = 0, left = 0; - for (int i = 0; i < bitmap.size(); i++) { - Log.d("HTML", "Combine: " + i + "/" + bitmap.size() + 1); - - top = (i == 0 ? 0 : top + bitmap.get(i).getHeight()); - left = (i == 0 ? 0 : top + bitmap.get(i).getWidth()); - canvas.drawBitmap(bitmap.get(i), left, 0f, null); - } - return temp; - } - - @Override - public void onBindViewHolder(@NonNull FullMetalViewHolder holder, int position) { - // don't forget about calling supper.onBindViewHolder! - super.onBindViewHolder(holder, position); - - final Album album = dataSet.get(position); - - if (holder.title != null) { - holder.title.setText(getAlbumTitle(album)); - } - if (holder.text != null) { - holder.text.setText(getAlbumText(album)); - } - if (holder.playSongs != null) { - holder.playSongs.setOnClickListener(v -> MusicPlayerRemote.openQueue(album.songs, 0, true)); - } - loadAlbumCover(album, holder); - } - - private String getAlbumTitle(Album album) { - return album.getTitle(); - } - - private String getAlbumText(Album album) { - return album.getArtistName(); - } - - private void loadAlbumCover(Album album, FullMetalViewHolder holder) { - if (holder.image == null) { - return; - } - - SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) - .checkIgnoreMediaStore(activity) - .generatePalette(activity).build() - .into(new RetroMusicColoredTarget(holder.image) { - @Override - public void onColorReady(int color) { - - } - }); - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - class FullMetalViewHolder extends MetalRecyclerViewPager.MetalViewHolder { - - FullMetalViewHolder(View itemView) { - super(itemView); - } - - @Override - public void onClick(View v) { - Pair[] albumPairs = new Pair[]{ - Pair.create(image, activity.getResources().getString(R.string.transition_album_art))}; - NavigationUtil.goToAlbum(activity, dataSet.get(getAdapterPosition()).getId(), albumPairs); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumFullWithAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumFullWithAdapter.kt new file mode 100644 index 00000000..36de3f85 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/AlbumFullWithAdapter.kt @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2017. Alexander Bilchuk + * + * 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 code.name.monkey.retromusic.ui.adapter.album + +import android.app.Activity +import android.graphics.Bitmap +import android.graphics.Canvas +import android.util.DisplayMetrics +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import androidx.core.util.Pair +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.views.MetalRecyclerViewPager +import com.bumptech.glide.Glide +import java.util.* + +class AlbumFullWithAdapter(private val activity: Activity, + metrics: DisplayMetrics) : MetalRecyclerViewPager.MetalAdapter(metrics) { + private var dataSet: List = ArrayList() + + fun swapData(list: ArrayList) { + dataSet = list + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FullMetalViewHolder { + val viewItem = LayoutInflater.from(parent.context) + .inflate(R.layout.pager_item, parent, false) + return FullMetalViewHolder(viewItem) + } + + override fun onBindViewHolder(holder: FullMetalViewHolder, position: Int) { + // don't forget about calling supper.onBindViewHolder! + super.onBindViewHolder(holder, position) + + val album = dataSet[position] + + if (holder.title != null) { + holder.title!!.text = getAlbumTitle(album) + } + if (holder.text != null) { + holder.text!!.text = getAlbumText(album) + } + if (holder.playSongs != null) { + holder.playSongs!!.setOnClickListener { MusicPlayerRemote.openQueue(album.songs!!, 0, true) } + } + loadAlbumCover(album, holder) + } + + private fun getAlbumTitle(album: Album): String? { + return album.title + } + + private fun getAlbumText(album: Album): String? { + return album.artistName + } + + private fun loadAlbumCover(album: Album, holder: FullMetalViewHolder) { + if (holder.image == null) { + return + } + + SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) + .checkIgnoreMediaStore(activity) + .generatePalette(activity).build() + .into(object : RetroMusicColoredTarget(holder.image!!) { + override fun onColorReady(color: Int) { + + } + }) + } + + override fun getItemCount(): Int { + return dataSet.size + } + + inner class FullMetalViewHolder(itemView: View) : MetalRecyclerViewPager.MetalViewHolder(itemView) { + + override fun onClick(v: View?) { + val albumPairs = arrayOf>(Pair.create(image, activity.resources.getString(R.string.transition_album_art))) + NavigationUtil.goToAlbum(activity, dataSet[adapterPosition].id, *albumPairs) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/HorizontalAlbumAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/HorizontalAlbumAdapter.java deleted file mode 100644 index 1d28988e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/HorizontalAlbumAdapter.java +++ /dev/null @@ -1,83 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.album; - -import android.graphics.drawable.Drawable; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; - -import java.util.ArrayList; - -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.HorizontalAdapterHelper; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.util.MusicUtil; - - -public class HorizontalAlbumAdapter extends AlbumAdapter { - public static final String TAG = AlbumAdapter.class.getSimpleName(); - - public HorizontalAlbumAdapter(@NonNull AppCompatActivity activity, ArrayList dataSet, boolean usePalette, @Nullable CabHolder cabHolder) { - super(activity, dataSet, HorizontalAdapterHelper.LAYOUT_RES, usePalette, cabHolder); - } - - @Override - protected ViewHolder createViewHolder(View view, int viewType) { - ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); - HorizontalAdapterHelper.applyMarginToLayoutParams(activity, params, viewType); - return new ViewHolder(view); - } - - @Override - protected void setColors(int color, ViewHolder holder) { - if (holder.itemView != null) { - if (holder.title != null) { - holder.title.setTextColor(MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))); - } - if (holder.text != null) { - holder.text.setTextColor(MaterialValueHelper.getSecondaryTextColor(activity, ColorUtil.isColorLight(color))); - } - } - } - - @Override - protected void loadAlbumCover(Album album, final ViewHolder holder) { - if (holder.image == null) return; - - SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) - .checkIgnoreMediaStore(activity) - .generatePalette(activity).build() - .into(new RetroMusicColoredTarget(holder.image) { - @Override - public void onLoadCleared(Drawable placeholder) { - super.onLoadCleared(placeholder); - setColors(getAlbumArtistFooterColor(), holder); - } - - @Override - public void onColorReady(int color) { - if (usePalette) - setColors(color, holder); - else - setColors(getAlbumArtistFooterColor(), holder); - } - }); - } - - @Override - protected String getAlbumText(Album album) { - return MusicUtil.getYearString(album.getYear()); - } - - @Override - public int getItemViewType(int position) { - return HorizontalAdapterHelper.getItemViewtype(position, getItemCount()); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/HorizontalAlbumAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/HorizontalAlbumAdapter.kt new file mode 100644 index 00000000..84bb8f5c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/album/HorizontalAlbumAdapter.kt @@ -0,0 +1,68 @@ +package code.name.monkey.retromusic.ui.adapter.album + +import android.graphics.drawable.Drawable +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.MaterialValueHelper +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.HorizontalAdapterHelper +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.util.MusicUtil +import com.bumptech.glide.Glide +import java.util.* + + +class HorizontalAlbumAdapter(activity: AppCompatActivity, dataSet: ArrayList, usePalette: Boolean, cabHolder: CabHolder?) : AlbumAdapter(activity, dataSet, HorizontalAdapterHelper.LAYOUT_RES, usePalette, cabHolder) { + + override fun createViewHolder(view: View, viewType: Int): ViewHolder { + val params = view.layoutParams as ViewGroup.MarginLayoutParams + HorizontalAdapterHelper.applyMarginToLayoutParams(activity, params, viewType) + return ViewHolder(view) + } + + override fun setColors(color: Int, holder: ViewHolder) { + if (holder.title != null) { + holder.title!!.setTextColor(MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))) + } + if (holder.text != null) { + holder.text!!.setTextColor(MaterialValueHelper.getSecondaryTextColor(activity, ColorUtil.isColorLight(color))) + } + } + + override fun loadAlbumCover(album: Album, holder: ViewHolder) { + if (holder.image == null) return + + SongGlideRequest.Builder.from(Glide.with(activity), album.safeGetFirstSong()) + .checkIgnoreMediaStore(activity) + .generatePalette(activity).build() + .into(object : RetroMusicColoredTarget(holder.image!!) { + override fun onLoadCleared(placeholder: Drawable?) { + super.onLoadCleared(placeholder) + setColors(albumArtistFooterColor, holder) + } + + override fun onColorReady(color: Int) { + if (usePalette) + setColors(color, holder) + else + setColors(albumArtistFooterColor, holder) + } + }) + } + + override fun getAlbumText(album: Album): String? { + return MusicUtil.getYearString(album.year) + } + + override fun getItemViewType(position: Int): Int { + return HorizontalAdapterHelper.getItemViewtype(position, itemCount) + } + + companion object { + val TAG: String = AlbumAdapter::class.java.simpleName + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/artist/ArtistAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/artist/ArtistAdapter.java deleted file mode 100644 index ac08ec33..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/artist/ArtistAdapter.java +++ /dev/null @@ -1,201 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.artist; - -import android.content.res.ColorStateList; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; -import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; - -import java.util.ArrayList; -import java.util.List; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.util.Pair; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.ArtistGlideRequest; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.helper.menu.SongsMenuHelper; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; - - -public class ArtistAdapter extends AbsMultiSelectAdapter implements FastScrollRecyclerView.SectionedAdapter { - - protected final AppCompatActivity activity; - protected ArrayList dataSet; - - protected int itemLayoutRes; - - protected boolean usePalette = false; - - - public ArtistAdapter(@NonNull AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder) { - super(activity, cabHolder, R.menu.menu_media_selection); - this.activity = activity; - this.dataSet = dataSet; - this.itemLayoutRes = itemLayoutRes; - this.usePalette = usePalette; - //setHasStableIds(true); - } - - public ArtistAdapter(@NonNull AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes) { - super(activity, null, R.menu.menu_media_selection); - this.activity = activity; - this.dataSet = dataSet; - this.itemLayoutRes = itemLayoutRes; - } - - public void swapDataSet(ArrayList dataSet) { - this.dataSet = dataSet; - notifyDataSetChanged(); - } - - public ArrayList getDataSet() { - return dataSet; - } - - public void usePalette(boolean usePalette) { - this.usePalette = usePalette; - notifyDataSetChanged(); - } - - @Override - public long getItemId(int position) { - return dataSet.get(position).getId(); - } - - @Override - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false); - return createViewHolder(view); - } - - protected ViewHolder createViewHolder(View view) { - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { - final Artist artist = dataSet.get(position); - - boolean isChecked = isChecked(artist); - holder.itemView.setActivated(isChecked); - - if (holder.title != null) { - holder.title.setText(artist.getName()); - } - if (holder.text != null) { - holder.text.setVisibility(View.GONE); - } - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.VISIBLE); - } - loadArtistImage(artist, holder); - } - - protected void setColors(int color, ViewHolder holder) { - if (holder.paletteColorContainer != null) { - holder.paletteColorContainer.setBackgroundColor(color); - if (holder.title != null) { - holder.title.setTextColor( - MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))); - } - } - if (holder.mask != null) { - holder.mask.setBackgroundTintList(ColorStateList.valueOf(color)); - } - } - - private void loadArtistImage(Artist artist, final ViewHolder holder) { - if (holder.image == null) { - return; - } - ArtistGlideRequest.Builder.from(Glide.with(activity), artist) - .generatePalette(activity).build() - .into(new RetroMusicColoredTarget(holder.image) { - @Override - public void onColorReady(int color) { - setColors(color, holder); - } - }); - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - @Override - protected Artist getIdentifier(int position) { - return dataSet.get(position); - } - - @Override - protected String getName(Artist artist) { - return artist.getName(); - } - - @Override - protected void onMultipleItemAction(@NonNull MenuItem menuItem, - @NonNull ArrayList selection) { - SongsMenuHelper.handleMenuClick(activity, getSongList(selection), menuItem.getItemId()); - } - - @NonNull - private ArrayList getSongList(@NonNull List artists) { - final ArrayList songs = new ArrayList<>(); - for (Artist artist : artists) { - songs.addAll(artist.getSongs()); // maybe async in future? - } - return songs; - } - - @NonNull - @Override - public String getSectionName(int position) { - return MusicUtil.getSectionName(dataSet.get(position).getName()); - } - - public class ViewHolder extends MediaEntryViewHolder { - - public ViewHolder(@NonNull View itemView) { - super(itemView); - setImageTransitionName(activity.getString(R.string.transition_artist_image)); - if (menu != null) { - menu.setVisibility(View.GONE); - } - } - - @Override - public void onClick(View v) { - if (isInQuickSelectMode()) { - toggleChecked(getAdapterPosition()); - } else { - Pair[] artistPairs = new Pair[]{Pair.create(image, - activity.getResources().getString(R.string.transition_artist_image))}; - NavigationUtil.goToArtist(activity, dataSet.get(getAdapterPosition()).getId(), artistPairs); - } - } - - @Override - public boolean onLongClick(View view) { - toggleChecked(getAdapterPosition()); - return true; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/artist/ArtistAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/artist/ArtistAdapter.kt new file mode 100644 index 00000000..876b244e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/artist/ArtistAdapter.kt @@ -0,0 +1,157 @@ +package code.name.monkey.retromusic.ui.adapter.artist + +import android.content.res.ColorStateList +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import androidx.core.util.Pair +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.MaterialValueHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.ArtistGlideRequest +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.helper.menu.SongsMenuHelper +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import com.bumptech.glide.Glide +import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView +import java.util.* + + +class ArtistAdapter(val activity: AppCompatActivity, + var dataSet: ArrayList, + @LayoutRes var itemLayoutRes: Int, + var usePalette: Boolean, + cabHolder: CabHolder?) : AbsMultiSelectAdapter(activity, cabHolder, R.menu.menu_media_selection), FastScrollRecyclerView.SectionedAdapter { + + fun swapDataSet(dataSet: ArrayList) { + this.dataSet = dataSet + notifyDataSetChanged() + } + + fun usePalette(usePalette: Boolean) { + this.usePalette = usePalette + notifyDataSetChanged() + } + + override fun getItemId(position: Int): Long { + return dataSet[position].id.toLong() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false) + return createViewHolder(view) + } + + protected fun createViewHolder(view: View): ViewHolder { + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val artist = dataSet[position] + + val isChecked = isChecked(artist) + holder.itemView.isActivated = isChecked + + if (holder.title != null) { + holder.title!!.text = artist.name + } + if (holder.text != null) { + holder.text!!.visibility = View.GONE + } + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.VISIBLE + } + loadArtistImage(artist, holder) + } + + fun setColors(color: Int, holder: ViewHolder) { + if (holder.paletteColorContainer != null) { + holder.paletteColorContainer!!.setBackgroundColor(color) + if (holder.title != null) { + holder.title!!.setTextColor( + MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))) + } + } + if (holder.mask != null) { + holder.mask!!.backgroundTintList = ColorStateList.valueOf(color) + } + } + + private fun loadArtistImage(artist: Artist, holder: ViewHolder) { + if (holder.image == null) { + return + } + ArtistGlideRequest.Builder.from(Glide.with(activity), artist) + .generatePalette(activity).build() + .into(object : RetroMusicColoredTarget(holder.image!!) { + override fun onColorReady(color: Int) { + setColors(color, holder) + } + }) + } + + override fun getItemCount(): Int { + return dataSet.size + } + + override fun getIdentifier(position: Int): Artist? { + return dataSet[position] + } + + override fun getName(artist: Artist): String { + return artist.name + } + + override fun onMultipleItemAction(menuItem: MenuItem, + selection: ArrayList) { + SongsMenuHelper.handleMenuClick(activity, getSongList(selection), menuItem.itemId) + } + + private fun getSongList(artists: List): ArrayList { + val songs = ArrayList() + for (artist in artists) { + songs.addAll(artist.songs) // maybe async in future? + } + return songs + } + + override fun getSectionName(position: Int): String { + return MusicUtil.getSectionName(dataSet[position].name) + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + init { + setImageTransitionName(activity.getString(R.string.transition_artist_image)) + if (menu != null) { + menu!!.visibility = View.GONE + } + } + + override fun onClick(v: View?) { + super.onClick(v) + if (isInQuickSelectMode) { + toggleChecked(adapterPosition) + } else { + val artistPairs = arrayOf>(Pair.create(image, + activity.resources.getString(R.string.transition_artist_image))) + NavigationUtil.goToArtist(activity, dataSet[adapterPosition].id, *artistPairs) + } + } + + override fun onLongClick(v: View?): Boolean { + toggleChecked(adapterPosition) + return super.onLongClick(v) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/base/MediaEntryViewHolder.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/base/MediaEntryViewHolder.java deleted file mode 100644 index 249f52a3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/base/MediaEntryViewHolder.java +++ /dev/null @@ -1,101 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.base; - -import android.os.Build; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.cardview.widget.CardView; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; - - -public class MediaEntryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { - - @Nullable - @BindView(R.id.image) - public ImageView image; - @Nullable - @BindView(R.id.image_text) - public TextView imageText; - @Nullable - @BindView(R.id.title) - public TextView title; - @Nullable - @BindView(R.id.text) - public TextView text; - @Nullable - @BindView(R.id.image_container) - public ViewGroup imageContainer; - @Nullable - @BindView(R.id.image_container_card) - public CardView imageContainerCard; - @Nullable - @BindView(R.id.menu) - public View menu; - @Nullable - @BindView(R.id.separator) - public View separator; - @Nullable - @BindView(R.id.short_separator) - public View shortSeparator; - @Nullable - @BindView(R.id.drag_view) - public View dragView; - @Nullable - @BindView(R.id.palette_color_container) - public View paletteColorContainer; - @BindView(R.id.time) - @Nullable - public TextView time; - @BindView(R.id.recycler_view) - @Nullable - public RecyclerView recyclerView; - @BindView(R.id.play_songs) - @Nullable - public ImageButton playSongs; - @BindView(R.id.mask) - @Nullable - public View mask; - @BindView(R.id.image_text_container) - @Nullable - public CardView imageTextContainer; - - - public MediaEntryViewHolder(View itemView) { - super(itemView); - ButterKnife.bind(this, itemView); - - itemView.setOnClickListener(this); - itemView.setOnLongClickListener(this); - - if (imageTextContainer != null) { - imageTextContainer.setCardBackgroundColor(ThemeStore.primaryColor(itemView.getContext())); - } - if (imageContainerCard != null) { - imageContainerCard.setCardBackgroundColor(ThemeStore.primaryColor(itemView.getContext())); - } - } - - protected void setImageTransitionName(@NonNull String transitionName) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && image != null) { - image.setTransitionName(transitionName); - } - } - - @Override - public boolean onLongClick(View v) { - return false; - } - - @Override - public void onClick(View v) { - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/base/MediaEntryViewHolder.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/base/MediaEntryViewHolder.kt new file mode 100644 index 00000000..bac037a1 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/base/MediaEntryViewHolder.kt @@ -0,0 +1,80 @@ +package code.name.monkey.retromusic.ui.adapter.base + +import android.os.Build +import android.view.View +import android.view.ViewGroup +import android.widget.ImageButton +import android.widget.ImageView +import android.widget.TextView +import androidx.cardview.widget.CardView +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R + +open class MediaEntryViewHolder(w: View) : RecyclerView.ViewHolder(w), View.OnClickListener, View.OnLongClickListener { + override fun onLongClick(v: View?): Boolean { + return false + } + + override fun onClick(v: View?) { + + } + + var image: ImageView? = null + var imageText: TextView? = null + var title: TextView? = null + var text: TextView? = null + var imageContainer: ViewGroup? = null + var imageContainerCard: CardView? = null + var menu: View? = null + var separator: View? = null + var shortSeparator: View? = null + var dragView: View? = null + var paletteColorContainer: View? = null + var time: TextView? = null + var recyclerView: RecyclerView? = null + var playSongs: ImageButton? = null + var mask: View? = null + var imageTextContainer: CardView? = null + + init { + title = w.findViewById(R.id.title) + text = w.findViewById(R.id.text) + + image = w.findViewById(R.id.image) + imageContainer = w.findViewById(R.id.image_container) + imageTextContainer = w.findViewById(R.id.image_text_container) + imageContainerCard = w.findViewById(R.id.image_container_card) + + imageText = w.findViewById(R.id.image_text) + + menu = w.findViewById(R.id.menu) + dragView = w.findViewById(R.id.drag_view) + + separator = w.findViewById(R.id.separator) + shortSeparator = w.findViewById(R.id.short_separator) + paletteColorContainer = w.findViewById(R.id.palette_color_container) + + time = w.findViewById(R.id.time); + recyclerView = w.findViewById(R.id.recycler_view) + + mask = w.findViewById(R.id.mask) + playSongs = w.findViewById(R.id.play_songs) + + w.setOnClickListener(this) + w.setOnLongClickListener(this) + + if (imageTextContainer != null) { + imageTextContainer!!.setCardBackgroundColor(ThemeStore.primaryColor(itemView.context)) + } + if (imageContainerCard != null) { + imageContainerCard!!.setCardBackgroundColor(ThemeStore.primaryColor(itemView.context)) + } + } + + fun setImageTransitionName(transitionName: String) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && image != null) { + image!!.transitionName = transitionName + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/AddToPlaylist.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/AddToPlaylist.java deleted file mode 100644 index 112a42a6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/AddToPlaylist.java +++ /dev/null @@ -1,69 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.playlist; - -import android.app.Activity; -import android.app.Dialog; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.ui.adapter.playlist.AddToPlaylist.ViewHolder; -import code.name.monkey.retromusic.util.PlaylistsUtil; - -public class AddToPlaylist extends RecyclerView.Adapter { - - private Activity activity; - private ArrayList playlists; - private int itemLayoutRes; - private ArrayList songs; - private Dialog dialog; - - public AddToPlaylist(Activity activity, - ArrayList playlists, int itemLayoutRes, - ArrayList songs, Dialog dialog) { - this.activity = activity; - this.playlists = playlists; - this.itemLayoutRes = itemLayoutRes; - this.songs = songs; - this.dialog = dialog; - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new ViewHolder(LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)); - } - - @Override - public void onBindViewHolder(@NonNull ViewHolder holder, int position) { - Playlist playlist = playlists.get(position); - if (holder.title != null) { - holder.title.setText(playlist.name); - } - } - - @Override - public int getItemCount() { - return playlists.size(); - } - - public class ViewHolder extends MediaEntryViewHolder { - - public ViewHolder(View itemView) { - super(itemView); - } - - @Override - public void onClick(View v) { - super.onClick(v); - PlaylistsUtil.addToPlaylist(activity, songs, playlists.get(getAdapterPosition()).id, true); - dialog.dismiss(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/AddToPlaylist.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/AddToPlaylist.kt new file mode 100644 index 00000000..f85746ee --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/AddToPlaylist.kt @@ -0,0 +1,44 @@ +package code.name.monkey.retromusic.ui.adapter.playlist + +import android.app.Activity +import android.app.Dialog +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup + +import java.util.ArrayList +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.ui.adapter.playlist.AddToPlaylist.ViewHolder +import code.name.monkey.retromusic.util.PlaylistsUtil + +class AddToPlaylist(private val activity: Activity, + private val playlists: ArrayList, private val itemLayoutRes: Int, + private val songs: ArrayList, private val dialog: Dialog) : RecyclerView.Adapter() { + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return ViewHolder(LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val playlist = playlists[position] + if (holder.title != null) { + holder.title!!.text = playlist.name + } + } + + override fun getItemCount(): Int { + return playlists.size + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + override fun onClick(v: View?) { + super.onClick(v) + PlaylistsUtil.addToPlaylist(activity, songs, playlists[adapterPosition].id, true) + dialog.dismiss() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/PlaylistAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/PlaylistAdapter.java deleted file mode 100755 index 945800fe..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/PlaylistAdapter.java +++ /dev/null @@ -1,297 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.playlist; - -import android.graphics.Bitmap; -import android.graphics.PorterDuff; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import com.bumptech.glide.Glide; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.ExecutionException; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.PopupMenu; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.ClearSmartPlaylistDialog; -import code.name.monkey.retromusic.dialogs.DeletePlaylistDialog; -import code.name.monkey.retromusic.helper.menu.PlaylistMenuHelper; -import code.name.monkey.retromusic.helper.menu.SongsMenuHelper; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.loaders.PlaylistSongsLoader; -import code.name.monkey.retromusic.model.AbsCustomPlaylist; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.model.smartplaylist.AbsSmartPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist; -import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import io.reactivex.Observable; - -public class PlaylistAdapter extends AbsMultiSelectAdapter { - - public static final String TAG = PlaylistAdapter.class.getSimpleName(); - - private static final int SMART_PLAYLIST = 0; - private static final int DEFAULT_PLAYLIST = 1; - - protected final AppCompatActivity activity; - protected ArrayList dataSet; - protected int itemLayoutRes; - private ArrayList mSongs = new ArrayList<>(); - - - public PlaylistAdapter(AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes, @Nullable CabHolder cabHolder) { - super(activity, cabHolder, R.menu.menu_playlists_selection); - this.activity = activity; - this.dataSet = dataSet; - this.itemLayoutRes = itemLayoutRes; - setHasStableIds(true); - } - - public ArrayList getDataSet() { - return dataSet; - } - - public void swapDataSet(ArrayList dataSet) { - this.dataSet = dataSet; - notifyDataSetChanged(); - } - - @Override - public long getItemId(int position) { - return dataSet.get(position).id; - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(activity) - .inflate(itemLayoutRes, parent, false); - return createViewHolder(view, viewType); - } - - protected ViewHolder createViewHolder(View view, int viewType) { - return new ViewHolder(view, viewType); - } - - @Override - public void onBindViewHolder(@NonNull ViewHolder holder, int position) { - /* if (getItemViewType(position) == SMART_PLAYLIST) { - if (holder.viewList != null) { - holder.viewList.get(0).setOnClickListener( - v -> NavigationUtil.goToPlaylistNew(activity, new HistoryPlaylist(activity))); - holder.viewList.get(1).setOnClickListener( - v -> NavigationUtil.goToPlaylistNew(activity, new LastAddedPlaylist(activity))); - holder.viewList.get(2).setOnClickListener( - v -> NavigationUtil.goToPlaylistNew(activity, new MyTopTracksPlaylist(activity))); - } - return; - }*/ - final Playlist playlist = dataSet.get(position); - ArrayList songs = getSongs(playlist); - holder.itemView.setActivated(isChecked(playlist)); - - if (holder.title != null) { - holder.title.setText(playlist.name); - } - if (holder.text != null) { - holder.text.setText(String.format(Locale.getDefault(), "%d Songs", songs.size())); - } - if (holder.image != null) { - holder.image.setImageResource(getIconRes(playlist)); - } - if (holder.getAdapterPosition() == getItemCount() - 1) { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.GONE); - } - } else { - if (holder.shortSeparator != null && !(dataSet.get(position) instanceof AbsSmartPlaylist)) { - holder.shortSeparator.setVisibility(View.VISIBLE); - } - } - } - - private int getIconRes(Playlist playlist) { - if (playlist instanceof AbsSmartPlaylist) { - return ((AbsSmartPlaylist) playlist).iconRes; - } - return MusicUtil.isFavoritePlaylist(activity, playlist) ? R.drawable.ic_favorite_white_24dp - : R.drawable.ic_playlist_play_white_24dp; - } - - @Override - public int getItemViewType(int position) { - return dataSet.get(position) instanceof AbsSmartPlaylist ? SMART_PLAYLIST : DEFAULT_PLAYLIST; - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - @Override - protected Playlist getIdentifier(int position) { - return dataSet.get(position); - } - - @Override - protected String getName(Playlist playlist) { - return playlist.name; - } - - @Override - protected void onMultipleItemAction(@NonNull MenuItem menuItem, - @NonNull ArrayList selection) { - switch (menuItem.getItemId()) { - case R.id.action_delete_playlist: - for (int i = 0; i < selection.size(); i++) { - Playlist playlist = selection.get(i); - if (playlist instanceof AbsSmartPlaylist) { - AbsSmartPlaylist absSmartPlaylist = (AbsSmartPlaylist) playlist; - ClearSmartPlaylistDialog.create(absSmartPlaylist) - .show(activity.getSupportFragmentManager(), - "CLEAR_PLAYLIST_" + absSmartPlaylist.name); - selection.remove(playlist); - i--; - } - } - if (selection.size() > 0) { - DeletePlaylistDialog.create(selection) - .show(activity.getSupportFragmentManager(), "DELETE_PLAYLIST"); - } - break; - default: - SongsMenuHelper.handleMenuClick(activity, getSongList(selection), menuItem.getItemId()); - break; - } - } - - public ArrayList getSongs() { - return mSongs; - } - - public void setSongs(ArrayList songs) { - mSongs = songs; - } - - @NonNull - private ArrayList getSongList(@NonNull List playlists) { - final ArrayList songs = new ArrayList<>(); - for (Playlist playlist : playlists) { - if (playlist instanceof AbsCustomPlaylist) { - songs.addAll(((AbsCustomPlaylist) playlist).getSongs(activity).blockingFirst()); - //((AbsCustomPlaylist) playlist).getSongs(activity).subscribe(this::setSongs); - } else { - songs - .addAll(PlaylistSongsLoader.getPlaylistSongList(activity, playlist.id).blockingFirst()); - } - } - return songs; - } - - @Nullable - private ArrayList getSongs(@NonNull Playlist playlist) { - final ArrayList songs = new ArrayList<>(); - if (playlist instanceof AbsSmartPlaylist) { - songs.addAll(((AbsSmartPlaylist) playlist).getSongs(activity).blockingFirst()); - } else { - songs.addAll(PlaylistSongsLoader.getPlaylistSongList(activity, playlist.id).blockingFirst()); - } - return songs; - } - - private Observable> loadBitmaps(@NonNull ArrayList songs) { - return Observable.create(e -> { - ArrayList bitmaps = new ArrayList(); - for (Song song : songs) { - try { - Bitmap bitmap = Glide.with(activity) - .load(RetroUtil.getAlbumArtUri(song.albumId)) - .asBitmap() - .into(500, 500) - .get(); - if (bitmap != null) { - Log.i(TAG, "loadBitmaps: has"); - bitmaps.add(bitmap); - } - if (bitmaps.size() == 4) { - break; - } - } catch (InterruptedException | ExecutionException ex) { - ex.printStackTrace(); - } - } - e.onNext(bitmaps); - e.onComplete(); - }); - } - - public class ViewHolder extends MediaEntryViewHolder { - public ViewHolder(@NonNull View itemView, int itemViewType) { - super(itemView); - ButterKnife.bind(this, itemView); - if (image != null) { - int iconPadding = activity.getResources() - .getDimensionPixelSize(R.dimen.list_item_image_icon_padding); - image.setPadding(iconPadding, iconPadding, iconPadding, iconPadding); - image.setColorFilter(ATHUtil.resolveColor(activity, R.attr.iconColor), - PorterDuff.Mode.SRC_IN); - } - if (menu != null) { - menu.setOnClickListener(view -> { - final Playlist playlist = dataSet.get(getAdapterPosition()); - final PopupMenu popupMenu = new PopupMenu(activity, view); - popupMenu.inflate(getItemViewType() == SMART_PLAYLIST ? R.menu.menu_item_smart_playlist - : R.menu.menu_item_playlist); - if (playlist instanceof LastAddedPlaylist) { - popupMenu.getMenu().findItem(R.id.action_clear_playlist).setVisible(false); - } - popupMenu.setOnMenuItemClickListener(item -> { - if (item.getItemId() == R.id.action_clear_playlist) { - if (playlist instanceof AbsSmartPlaylist) { - ClearSmartPlaylistDialog.create((AbsSmartPlaylist) playlist) - .show(activity.getSupportFragmentManager(), - "CLEAR_SMART_PLAYLIST_" + playlist.name); - return true; - } - } - return PlaylistMenuHelper.handleMenuClick( - activity, dataSet.get(getAdapterPosition()), item); - }); - popupMenu.show(); - }); - } - } - - @Override - public void onClick(View view) { - if (isInQuickSelectMode()) { - toggleChecked(getAdapterPosition()); - } else { - Playlist playlist = dataSet.get(getAdapterPosition()); - NavigationUtil.goToPlaylistNew(activity, playlist); - } - } - - @Override - public boolean onLongClick(View view) { - toggleChecked(getAdapterPosition()); - return true; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/PlaylistAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/PlaylistAdapter.kt new file mode 100755 index 00000000..67a3f52e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/playlist/PlaylistAdapter.kt @@ -0,0 +1,268 @@ +package code.name.monkey.retromusic.ui.adapter.playlist + +import android.graphics.Bitmap +import android.graphics.PorterDuff +import android.util.Log +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.widget.PopupMenu +import butterknife.ButterKnife +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.ClearSmartPlaylistDialog +import code.name.monkey.retromusic.dialogs.DeletePlaylistDialog +import code.name.monkey.retromusic.helper.menu.PlaylistMenuHelper +import code.name.monkey.retromusic.helper.menu.SongsMenuHelper +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.loaders.PlaylistSongsLoader +import code.name.monkey.retromusic.model.AbsCustomPlaylist +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.model.smartplaylist.AbsSmartPlaylist +import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist +import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.RetroUtil +import com.bumptech.glide.Glide +import io.reactivex.Observable +import java.util.* +import java.util.concurrent.ExecutionException + +class PlaylistAdapter(protected val activity: AppCompatActivity, dataSet: ArrayList, + @param:LayoutRes protected var itemLayoutRes: Int, cabHolder: CabHolder?) : AbsMultiSelectAdapter(activity, cabHolder, R.menu.menu_playlists_selection) { + var dataSet: ArrayList + protected set + var songs = ArrayList() + + + init { + this.dataSet = dataSet + setHasStableIds(true) + } + + fun swapDataSet(dataSet: ArrayList) { + this.dataSet = dataSet + notifyDataSetChanged() + } + + override fun getItemId(position: Int): Long { + return dataSet[position].id.toLong() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(activity) + .inflate(itemLayoutRes, parent, false) + return createViewHolder(view) + } + + protected fun createViewHolder(view: View): ViewHolder { + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + /* if (getItemViewType(position) == SMART_PLAYLIST) { + if (holder.viewList != null) { + holder.viewList.get(0).setOnClickListener( + v -> NavigationUtil.goToPlaylistNew(activity, new HistoryPlaylist(activity))); + holder.viewList.get(1).setOnClickListener( + v -> NavigationUtil.goToPlaylistNew(activity, new LastAddedPlaylist(activity))); + holder.viewList.get(2).setOnClickListener( + v -> NavigationUtil.goToPlaylistNew(activity, new MyTopTracksPlaylist(activity))); + } + return; + }*/ + val playlist = dataSet[position] + val songs = getSongs(playlist) + holder.itemView.isActivated = isChecked(playlist) + + if (holder.title != null) { + holder.title!!.text = playlist.name + } + if (holder.text != null) { + holder.text!!.text = String.format(Locale.getDefault(), "%d Songs", songs!!.size) + } + if (holder.image != null) { + holder.image!!.setImageResource(getIconRes(playlist)) + } + if (holder.adapterPosition == itemCount - 1) { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.GONE + } + } else { + if (holder.shortSeparator != null && dataSet[position] !is AbsSmartPlaylist) { + holder.shortSeparator!!.visibility = View.VISIBLE + } + } + } + + private fun getIconRes(playlist: Playlist): Int { + if (playlist is AbsSmartPlaylist) { + return playlist.iconRes + } + return if (MusicUtil.isFavoritePlaylist(activity, playlist)) + R.drawable.ic_favorite_white_24dp + else + R.drawable.ic_playlist_play_white_24dp + } + + override fun getItemViewType(position: Int): Int { + return if (dataSet[position] is AbsSmartPlaylist) SMART_PLAYLIST else DEFAULT_PLAYLIST + } + + override fun getItemCount(): Int { + return dataSet.size + } + + override fun getIdentifier(position: Int): Playlist? { + return dataSet[position] + } + + override fun getName(playlist: Playlist): String { + return playlist.name + } + + override fun onMultipleItemAction(menuItem: MenuItem, + selection: ArrayList) { + when (menuItem.itemId) { + R.id.action_delete_playlist -> { + var i = 0 + while (i < selection.size) { + val playlist = selection[i] + if (playlist is AbsSmartPlaylist) { + ClearSmartPlaylistDialog.create(playlist) + .show(activity.supportFragmentManager, + "CLEAR_PLAYLIST_" + playlist.name) + selection.remove(playlist) + i-- + } + i++ + } + if (selection.size > 0) { + DeletePlaylistDialog.create(selection) + .show(activity.supportFragmentManager, "DELETE_PLAYLIST") + } + } + else -> SongsMenuHelper.handleMenuClick(activity, getSongList(selection), menuItem.itemId) + } + } + + private fun getSongList(playlists: List): ArrayList { + val songs = ArrayList() + for (playlist in playlists) { + if (playlist is AbsCustomPlaylist) { + songs.addAll(playlist.getSongs(activity).blockingFirst()) + //((AbsCustomPlaylist) playlist).getSongs(activity).subscribe(this::setSongs); + } else { + songs + .addAll(PlaylistSongsLoader.getPlaylistSongList(activity, playlist.id).blockingFirst()) + } + } + return songs + } + + private fun getSongs(playlist: Playlist): ArrayList? { + val songs = ArrayList() + if (playlist is AbsSmartPlaylist) { + songs.addAll(playlist.getSongs(activity).blockingFirst()) + } else { + songs.addAll(PlaylistSongsLoader.getPlaylistSongList(activity, playlist.id).blockingFirst()) + } + return songs + } + + private fun loadBitmaps(songs: ArrayList): Observable> { + return Observable.create { e -> + val bitmaps = ArrayList() + for (song in songs) { + try { + val bitmap = Glide.with(activity) + .load(RetroUtil.getAlbumArtUri(song.albumId.toLong())) + .asBitmap() + .into(500, 500) + .get() + if (bitmap != null) { + Log.i(TAG, "loadBitmaps: has") + bitmaps.add(bitmap) + } + if (bitmaps.size == 4) { + break + } + } catch (ex: InterruptedException) { + ex.printStackTrace() + } catch (ex: ExecutionException) { + ex.printStackTrace() + } + + } + e.onNext(bitmaps) + e.onComplete() + } + } + + inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + init { + ButterKnife.bind(this, itemView) + if (image != null) { + val iconPadding = activity.resources + .getDimensionPixelSize(R.dimen.list_item_image_icon_padding) + image!!.setPadding(iconPadding, iconPadding, iconPadding, iconPadding) + image!!.setColorFilter(ATHUtil.resolveColor(activity, R.attr.iconColor), + PorterDuff.Mode.SRC_IN) + } + if (menu != null) { + menu!!.setOnClickListener { view -> + val playlist = dataSet[adapterPosition] + val popupMenu = PopupMenu(activity, view) + popupMenu.inflate(if (getItemViewType() == SMART_PLAYLIST) + R.menu.menu_item_smart_playlist + else + R.menu.menu_item_playlist) + if (playlist is LastAddedPlaylist) { + popupMenu.menu.findItem(R.id.action_clear_playlist).isVisible = false + } + popupMenu.setOnMenuItemClickListener { item -> + if (item.itemId == R.id.action_clear_playlist) { + if (playlist is AbsSmartPlaylist) { + ClearSmartPlaylistDialog.create(playlist) + .show(activity.supportFragmentManager, + "CLEAR_SMART_PLAYLIST_" + playlist.name) + return@setOnMenuItemClickListener true + } + } + PlaylistMenuHelper.handleMenuClick( + activity, dataSet[adapterPosition], item) + } + popupMenu.show() + } + } + } + + override fun onClick(v: View?) { + if (isInQuickSelectMode) { + toggleChecked(adapterPosition) + } else { + val playlist = dataSet[adapterPosition] + NavigationUtil.goToPlaylistNew(activity, playlist) + } + } + + override fun onLongClick(v: View?): Boolean { + toggleChecked(adapterPosition) + return true + } + } + + companion object { + + val TAG: String = PlaylistAdapter::class.java.simpleName + + private const val SMART_PLAYLIST = 0 + private const val DEFAULT_PLAYLIST = 1 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/AbsOffsetSongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/AbsOffsetSongAdapter.java deleted file mode 100644 index dfe89524..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/AbsOffsetSongAdapter.java +++ /dev/null @@ -1,110 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Song; - - -public abstract class AbsOffsetSongAdapter extends SongAdapter { - - protected static final int OFFSET_ITEM = 0; - protected static final int SONG = 1; - - public AbsOffsetSongAdapter(AppCompatActivity activity, ArrayList dataSet, @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder) { - super(activity, dataSet, itemLayoutRes, usePalette, cabHolder); - } - - public AbsOffsetSongAdapter(AppCompatActivity activity, ArrayList dataSet, @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder, boolean showSectionName) { - super(activity, dataSet, itemLayoutRes, usePalette, cabHolder, showSectionName); - } - - @NonNull - @Override - public SongAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - if (viewType == OFFSET_ITEM) { - View view = LayoutInflater.from(activity).inflate(R.layout.item_list_single_row, parent, false); - return createViewHolder(view); - } - return super.onCreateViewHolder(parent, viewType); - } - - @Override - protected SongAdapter.ViewHolder createViewHolder(View view) { - return new AbsOffsetSongAdapter.ViewHolder(view); - } - - @Override - public long getItemId(int position) { - position--; - if (position < 0) return -2; - return super.getItemId(position); - } - - @Nullable - @Override - protected Song getIdentifier(int position) { - position--; - if (position < 0) return null; - return super.getIdentifier(position); - } - - @Override - public int getItemCount() { - int superItemCount = super.getItemCount(); - return superItemCount == 0 ? 0 : superItemCount + 1; - } - - @Override - public int getItemViewType(int position) { - return position == 0 ? OFFSET_ITEM : SONG; - } - - @NonNull - @Override - public String getSectionName(int position) { - position--; - if (position < 0) return ""; - return super.getSectionName(position); - } - - public class ViewHolder extends SongAdapter.ViewHolder { - - public ViewHolder(@NonNull View itemView) { - super(itemView); - } - - @Override - protected Song getSong() { - if (getItemViewType() == OFFSET_ITEM) - return Song.EMPTY_SONG; // could also return null, just to be safe return empty song - return dataSet.get(getAdapterPosition() - 1); - } - - @Override - public void onClick(View v) { - if (isInQuickSelectMode() && getItemViewType() != OFFSET_ITEM) { - toggleChecked(getAdapterPosition()); - } else { - MusicPlayerRemote.openQueue(dataSet, getAdapterPosition() - 1, true); - } - } - - @Override - public boolean onLongClick(View view) { - if (getItemViewType() == OFFSET_ITEM) return false; - toggleChecked(getAdapterPosition()); - return true; - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/AbsOffsetSongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/AbsOffsetSongAdapter.kt new file mode 100644 index 00000000..4329ea2b --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/AbsOffsetSongAdapter.kt @@ -0,0 +1,85 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.Song +import java.util.* + + +abstract class AbsOffsetSongAdapter : SongAdapter { + + constructor(activity: AppCompatActivity, dataSet: ArrayList, @LayoutRes itemLayoutRes: Int, usePalette: Boolean, cabHolder: CabHolder?) : super(activity, dataSet, itemLayoutRes, usePalette, cabHolder) + + constructor(activity: AppCompatActivity, dataSet: ArrayList, @LayoutRes itemLayoutRes: Int, usePalette: Boolean, cabHolder: CabHolder?, showSectionName: Boolean) : super(activity, dataSet, itemLayoutRes, usePalette, cabHolder, showSectionName) {} + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SongAdapter.ViewHolder { + if (viewType == OFFSET_ITEM) { + val view = LayoutInflater.from(activity).inflate(R.layout.item_list_single_row, parent, false) + return createViewHolder(view) + } + return super.onCreateViewHolder(parent, viewType) + } + + override fun createViewHolder(view: View): SongAdapter.ViewHolder { + return ViewHolder(view) + } + + override fun getItemId(position: Int): Long { + var positionFinal = position + positionFinal-- + return if (positionFinal < 0) -2 else super.getItemId(positionFinal) + } + + override fun getIdentifier(position: Int): Song? { + var positionFinal = position + positionFinal-- + return if (positionFinal < 0) null else super.getIdentifier(positionFinal) + } + + override fun getItemCount(): Int { + val superItemCount = super.getItemCount() + return if (superItemCount == 0) 0 else superItemCount + 1 + } + + override fun getItemViewType(position: Int): Int { + return if (position == 0) OFFSET_ITEM else SONG + } + + override fun getSectionName(position: Int): String { + var positionFinal = position + positionFinal-- + return if (position < 0) "" else super.getSectionName(positionFinal) + } + + open inner class ViewHolder(itemView: View) : SongAdapter.ViewHolder(itemView) { + + override// could also return null, just to be safe return empty song + val song: Song + get() = if (itemViewType == OFFSET_ITEM) Song.EMPTY_SONG else dataSet[adapterPosition - 1] + + override fun onClick(v: View?) { + if (isInQuickSelectMode && itemViewType != OFFSET_ITEM) { + toggleChecked(adapterPosition) + } else { + MusicPlayerRemote.openQueue(dataSet, adapterPosition - 1, true) + } + } + + override fun onLongClick(v: View?): Boolean { + if (itemViewType == OFFSET_ITEM) return false + toggleChecked(adapterPosition) + return true + } + } + + companion object { + const val OFFSET_ITEM = 0 + const val SONG = 1 + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/OrderablePlaylistSongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/OrderablePlaylistSongAdapter.java deleted file mode 100644 index a5887904..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/OrderablePlaylistSongAdapter.java +++ /dev/null @@ -1,145 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import android.view.MenuItem; -import android.view.View; - -import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter; -import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemViewHolder; -import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange; -import com.h6ah4i.android.widget.advrecyclerview.draggable.annotation.DraggableItemStateFlags; - -import java.util.ArrayList; -import java.util.List; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.RemoveFromPlaylistDialog; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.PlaylistSong; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.ViewUtil; - - -@SuppressWarnings("unchecked") -public class OrderablePlaylistSongAdapter extends PlaylistSongAdapter - implements DraggableItemAdapter { - - public static final String TAG = OrderablePlaylistSongAdapter.class.getSimpleName(); - - private OnMoveItemListener onMoveItemListener; - - public OrderablePlaylistSongAdapter(@NonNull AppCompatActivity activity, - @NonNull ArrayList dataSet, - @LayoutRes int itemLayoutRes, - boolean usePalette, - @Nullable CabHolder cabHolder, - @Nullable OnMoveItemListener onMoveItemListener) { - super(activity, (ArrayList) (List) dataSet, itemLayoutRes, usePalette, cabHolder); - setMultiSelectMenuRes(R.menu.menu_playlists_songs_selection); - this.onMoveItemListener = onMoveItemListener; - } - - @Override - protected SongAdapter.ViewHolder createViewHolder(View view) { - return new ViewHolder(view); - } - - @Override - public long getItemId(int position) { - position--; - if (position < 0) return -2; - return ((ArrayList) (List) dataSet).get(position).idInPlayList; // important! - } - - @Override - protected void onMultipleItemAction(@NonNull MenuItem menuItem, @NonNull ArrayList selection) { - switch (menuItem.getItemId()) { - case R.id.action_remove_from_playlist: - RemoveFromPlaylistDialog.create((ArrayList) (List) selection).show(activity.getSupportFragmentManager(), "ADD_PLAYLIST"); - return; - } - super.onMultipleItemAction(menuItem, selection); - } - - @Override - public boolean onCheckCanStartDrag(ViewHolder holder, int position, int x, int y) { - return onMoveItemListener != null && position > 0 && - (ViewUtil.hitTest(holder.dragView, x, y) || ViewUtil.hitTest(holder.image, x, y)); - } - - @Override - public ItemDraggableRange onGetItemDraggableRange(ViewHolder holder, int position) { - return new ItemDraggableRange(1, dataSet.size()); - } - - @Override - public void onMoveItem(int fromPosition, int toPosition) { - if (onMoveItemListener != null && fromPosition != toPosition) { - onMoveItemListener.onMoveItem(fromPosition - 1, toPosition - 1); - } - } - - @Override - public boolean onCheckCanDrop(int draggingPosition, int dropPosition) { - return dropPosition > 0; - } - - @Override - public void onItemDragStarted(int position) { - notifyDataSetChanged(); - } - - @Override - public void onItemDragFinished(int fromPosition, int toPosition, boolean result) { - notifyDataSetChanged(); - } - - public interface OnMoveItemListener { - void onMoveItem(int fromPosition, int toPosition); - } - - public class ViewHolder extends PlaylistSongAdapter.ViewHolder implements DraggableItemViewHolder { - @DraggableItemStateFlags - private int mDragStateFlags; - - public ViewHolder(@NonNull View itemView) { - super(itemView); - if (dragView != null) { - if (onMoveItemListener != null) { - dragView.setVisibility(View.VISIBLE); - } else { - dragView.setVisibility(View.GONE); - } - } - } - - @Override - protected int getSongMenuRes() { - return R.menu.menu_item_playlist_song; - } - - @Override - protected boolean onSongMenuItemClick(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_remove_from_playlist: - RemoveFromPlaylistDialog.create((PlaylistSong) getSong()).show(activity.getSupportFragmentManager(), "REMOVE_FROM_PLAYLIST"); - return true; - } - return super.onSongMenuItemClick(item); - } - - @Override - @DraggableItemStateFlags - public int getDragStateFlags() { - return mDragStateFlags; - } - - @Override - public void setDragStateFlags(@DraggableItemStateFlags int flags) { - mDragStateFlags = flags; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/OrderablePlaylistSongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/OrderablePlaylistSongAdapter.kt new file mode 100644 index 00000000..a55a548f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/OrderablePlaylistSongAdapter.kt @@ -0,0 +1,136 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.view.MenuItem +import android.view.View +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.RemoveFromPlaylistDialog +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.PlaylistSong +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.ViewUtil +import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter +import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemViewHolder +import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange +import com.h6ah4i.android.widget.advrecyclerview.draggable.annotation.DraggableItemStateFlags + + +class OrderablePlaylistSongAdapter(activity: AppCompatActivity, + dataSet: ArrayList, + @LayoutRes itemLayoutRes: Int, + usePalette: Boolean, + cabHolder: CabHolder?, + private val onMoveItemListener: OnMoveItemListener?) : PlaylistSongAdapter(activity, dataSet, itemLayoutRes, usePalette, cabHolder), DraggableItemAdapter { + + init { + setMultiSelectMenuRes(R.menu.menu_playlists_songs_selection) + } + + override fun createViewHolder(view: View): SongAdapter.ViewHolder { + return ViewHolder(view) + } + + override fun getItemId(position: Int): Long { + var positionFinal = position + positionFinal-- + + var long: Long = 0 + if (position < 0) { + long = -2 + } else { + if (dataSet[positionFinal] is PlaylistSong) { + long = (dataSet[positionFinal] as PlaylistSong).idInPlayList.toLong() + } + } + return long + } + + override fun onMultipleItemAction(menuItem: MenuItem, selection: ArrayList) { + when (menuItem.itemId) { + R.id.action_remove_from_playlist -> { + val songs = ArrayList() + songs.addAll(songs) + RemoveFromPlaylistDialog.create(songs).show(activity.supportFragmentManager, "ADD_PLAYLIST") + return + } + } + super.onMultipleItemAction(menuItem, selection) + } + + override fun onCheckCanStartDrag(holder: ViewHolder, position: Int, x: Int, y: Int): Boolean { + return onMoveItemListener != null && position > 0 && + (ViewUtil.hitTest(holder.dragView, x, y) || ViewUtil.hitTest(holder.image, x, y)) + } + + override fun onGetItemDraggableRange(holder: ViewHolder, position: Int): ItemDraggableRange { + return ItemDraggableRange(1, dataSet.size) + } + + override fun onMoveItem(fromPosition: Int, toPosition: Int) { + if (onMoveItemListener != null && fromPosition != toPosition) { + onMoveItemListener.onMoveItem(fromPosition - 1, toPosition - 1) + } + } + + override fun onCheckCanDrop(draggingPosition: Int, dropPosition: Int): Boolean { + return dropPosition > 0 + } + + override fun onItemDragStarted(position: Int) { + notifyDataSetChanged() + } + + override fun onItemDragFinished(fromPosition: Int, toPosition: Int, result: Boolean) { + notifyDataSetChanged() + } + + interface OnMoveItemListener { + fun onMoveItem(fromPosition: Int, toPosition: Int) + } + + inner class ViewHolder(itemView: View) : PlaylistSongAdapter.ViewHolder(itemView), DraggableItemViewHolder { + @DraggableItemStateFlags + private var mDragStateFlags: Int = 0 + + override var songMenuRes: Int + get() = R.menu.menu_item_playlist_song + set(value: Int) { + super.songMenuRes = value + } + + init { + if (dragView != null) { + if (onMoveItemListener != null) { + dragView!!.visibility = View.VISIBLE + } else { + dragView!!.visibility = View.GONE + } + } + } + + override fun onSongMenuItemClick(item: MenuItem): Boolean { + when (item.itemId) { + R.id.action_remove_from_playlist -> { + RemoveFromPlaylistDialog.create(song as PlaylistSong).show(activity.supportFragmentManager, "REMOVE_FROM_PLAYLIST") + return true + } + } + return super.onSongMenuItemClick(item) + } + + @DraggableItemStateFlags + override fun getDragStateFlags(): Int { + return mDragStateFlags + } + + override fun setDragStateFlags(@DraggableItemStateFlags flags: Int) { + mDragStateFlags = flags + } + } + + companion object { + + val TAG = OrderablePlaylistSongAdapter::class.java.simpleName + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlayingQueueAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlayingQueueAdapter.java deleted file mode 100644 index 9c98f5f7..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlayingQueueAdapter.java +++ /dev/null @@ -1,215 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.view.MenuItem; -import android.view.View; -import android.widget.ImageView; - -import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter; -import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemViewHolder; -import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange; -import com.h6ah4i.android.widget.advrecyclerview.draggable.annotation.DraggableItemStateFlags; - -import java.util.ArrayList; - -import androidx.annotation.ColorInt; -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.ViewUtil; - - -public class PlayingQueueAdapter extends SongAdapter implements DraggableItemAdapter { - - private static final int HISTORY = 0; - private static final int CURRENT = 1; - private static final int UP_NEXT = 2; - - private int current; - private int color = -1; - - public PlayingQueueAdapter(AppCompatActivity activity, ArrayList dataSet, int current, - @LayoutRes int itemLayoutRes) { - super(activity, dataSet, itemLayoutRes, false, null); - this.current = current; - } - - public PlayingQueueAdapter(AppCompatActivity activity, ArrayList dataSet, int current, - @LayoutRes int itemLayoutRes, @ColorInt int color) { - super(activity, dataSet, itemLayoutRes, false, null); - this.current = current; - this.color = color; - } - - @Override - protected SongAdapter.ViewHolder createViewHolder(View view) { - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull SongAdapter.ViewHolder holder, int position) { - super.onBindViewHolder(holder, position); - if (holder.imageText != null) { - holder.imageText.setText(String.valueOf(position - current)); - } - if (holder.time != null) { - holder.time.setText(MusicUtil.getReadableDurationString(getDataSet().get(position).duration)); - } - if (holder.getItemViewType() == HISTORY || holder.getItemViewType() == CURRENT) { - setAlpha(holder, 0.5f); - } - if (usePalette) { - setColor(holder, Color.WHITE); - } - } - - private void setColor(SongAdapter.ViewHolder holder, int white) { - - if (holder.title != null) { - holder.title.setTextColor(white); - if (color != -1) { - holder.title.setTextColor(color); - } - } - if (holder.text != null) { - holder.text.setTextColor(white); - } - if (holder.time != null) { - holder.time.setTextColor(white); - } - if (holder.imageText != null) { - holder.imageText.setTextColor(white); - } - if (holder.menu != null) { - ((ImageView) holder.menu).setColorFilter(white, PorterDuff.Mode.SRC_IN); - } - } - - @Override - public void usePalette(boolean color) { - super.usePalette(color); - usePalette = color; - notifyDataSetChanged(); - } - - @Override - public int getItemViewType(int position) { - if (position < current) { - return HISTORY; - } else if (position > current) { - return UP_NEXT; - } - return CURRENT; - } - - @Override - protected void loadAlbumCover(Song song, SongAdapter.ViewHolder holder) { - // We don't want to load it in this adapter - } - - public void swapDataSet(ArrayList dataSet, int position) { - this.dataSet = dataSet; - current = position; - notifyDataSetChanged(); - } - - public void setCurrent(int current) { - this.current = current; - notifyDataSetChanged(); - } - - private void setAlpha(SongAdapter.ViewHolder holder, float alpha) { - if (holder.image != null) { - holder.image.setAlpha(alpha); - } - if (holder.title != null) { - holder.title.setAlpha(alpha); - } - if (holder.text != null) { - holder.text.setAlpha(alpha); - } - if (holder.imageText != null) { - holder.imageText.setAlpha(alpha); - } - if (holder.paletteColorContainer != null) { - holder.paletteColorContainer.setAlpha(alpha); - } - } - - @Override - public boolean onCheckCanStartDrag(ViewHolder holder, int position, int x, int y) { - return ViewUtil.hitTest(holder.imageText, x, y) || (ViewUtil.hitTest(holder.dragView, x, y)); - } - - @Override - public ItemDraggableRange onGetItemDraggableRange(ViewHolder holder, int position) { - return null; - } - - @Override - public void onMoveItem(int fromPosition, int toPosition) { - MusicPlayerRemote.moveSong(fromPosition, toPosition); - } - - @Override - public boolean onCheckCanDrop(int draggingPosition, int dropPosition) { - return true; - } - - @Override - public void onItemDragStarted(int position) { - notifyDataSetChanged(); - } - - @Override - public void onItemDragFinished(int fromPosition, int toPosition, boolean result) { - notifyDataSetChanged(); - } - - public class ViewHolder extends SongAdapter.ViewHolder implements DraggableItemViewHolder { - - @DraggableItemStateFlags - private int mDragStateFlags; - - public ViewHolder(@NonNull View itemView) { - super(itemView); - if (imageText != null) { - imageText.setVisibility(View.VISIBLE); - } - if (dragView != null) { - dragView.setVisibility(View.VISIBLE); - } - } - - @Override - protected int getSongMenuRes() { - return R.menu.menu_item_playing_queue_song; - } - - @Override - protected boolean onSongMenuItemClick(MenuItem item) { - switch (item.getItemId()) { - case R.id.action_remove_from_playing_queue: - MusicPlayerRemote.removeFromQueue(getAdapterPosition()); - return true; - } - return super.onSongMenuItemClick(item); - } - - @Override - @DraggableItemStateFlags - public int getDragStateFlags() { - return mDragStateFlags; - } - - @Override - public void setDragStateFlags(@DraggableItemStateFlags int flags) { - mDragStateFlags = flags; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlayingQueueAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlayingQueueAdapter.kt new file mode 100644 index 00000000..ee92dcc8 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlayingQueueAdapter.kt @@ -0,0 +1,199 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.graphics.Color +import android.graphics.PorterDuff +import android.view.MenuItem +import android.view.View +import android.widget.ImageView +import androidx.annotation.ColorInt +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.ViewUtil +import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter +import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemViewHolder +import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange +import com.h6ah4i.android.widget.advrecyclerview.draggable.annotation.DraggableItemStateFlags +import java.util.* + + +class PlayingQueueAdapter : SongAdapter, DraggableItemAdapter { + + private var current: Int = 0 + private var color = -1 + + constructor(activity: AppCompatActivity, dataSet: ArrayList, current: Int, + @LayoutRes itemLayoutRes: Int) : super(activity, dataSet, itemLayoutRes, false, null) { + this.current = current + } + + constructor(activity: AppCompatActivity, dataSet: ArrayList, current: Int, + @LayoutRes itemLayoutRes: Int, @ColorInt color: Int) : super(activity, dataSet, itemLayoutRes, false, null) { + this.current = current + this.color = color + } + + override fun createViewHolder(view: View): SongAdapter.ViewHolder { + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: SongAdapter.ViewHolder, position: Int) { + super.onBindViewHolder(holder, position) + if (holder.imageText != null) { + holder.imageText!!.text = (position - current).toString() + } + if (holder.time != null) { + holder.time!!.text = MusicUtil.getReadableDurationString(dataSet[position].duration) + } + if (holder.itemViewType == HISTORY || holder.itemViewType == CURRENT) { + setAlpha(holder, 0.5f) + } + if (usePalette) { + setColor(holder, Color.WHITE) + } + } + + private fun setColor(holder: SongAdapter.ViewHolder, white: Int) { + + if (holder.title != null) { + holder.title!!.setTextColor(white) + if (color != -1) { + holder.title!!.setTextColor(color) + } + } + if (holder.text != null) { + holder.text!!.setTextColor(white) + } + if (holder.time != null) { + holder.time!!.setTextColor(white) + } + if (holder.imageText != null) { + holder.imageText!!.setTextColor(white) + } + if (holder.menu != null) { + (holder.menu as ImageView).setColorFilter(white, PorterDuff.Mode.SRC_IN) + } + } + + override fun usePalette(usePalette: Boolean) { + super.usePalette(usePalette) + this.usePalette = usePalette + notifyDataSetChanged() + } + + override fun getItemViewType(position: Int): Int { + if (position < current) { + return HISTORY + } else if (position > current) { + return UP_NEXT + } + return CURRENT + } + + override fun loadAlbumCover(song: Song, holder: SongAdapter.ViewHolder) { + // We don't want to load it in this adapter + } + + fun swapDataSet(dataSet: ArrayList, position: Int) { + this.dataSet = dataSet + current = position + notifyDataSetChanged() + } + + fun setCurrent(current: Int) { + this.current = current + notifyDataSetChanged() + } + + private fun setAlpha(holder: SongAdapter.ViewHolder, alpha: Float) { + if (holder.image != null) { + holder.image!!.alpha = alpha + } + if (holder.title != null) { + holder.title!!.alpha = alpha + } + if (holder.text != null) { + holder.text!!.alpha = alpha + } + if (holder.imageText != null) { + holder.imageText!!.alpha = alpha + } + if (holder.paletteColorContainer != null) { + holder.paletteColorContainer!!.alpha = alpha + } + } + + override fun onCheckCanStartDrag(holder: ViewHolder, position: Int, x: Int, y: Int): Boolean { + return ViewUtil.hitTest(holder.imageText, x, y) || ViewUtil.hitTest(holder.dragView, x, y) + } + + override fun onGetItemDraggableRange(holder: ViewHolder, position: Int): ItemDraggableRange? { + return null + } + + override fun onMoveItem(fromPosition: Int, toPosition: Int) { + MusicPlayerRemote.moveSong(fromPosition, toPosition) + } + + override fun onCheckCanDrop(draggingPosition: Int, dropPosition: Int): Boolean { + return true + } + + override fun onItemDragStarted(position: Int) { + notifyDataSetChanged() + } + + override fun onItemDragFinished(fromPosition: Int, toPosition: Int, result: Boolean) { + notifyDataSetChanged() + } + + inner class ViewHolder(itemView: View) : SongAdapter.ViewHolder(itemView), DraggableItemViewHolder { + + @DraggableItemStateFlags + private var mDragStateFlags: Int = 0 + + override var songMenuRes: Int + get() = R.menu.menu_item_playing_queue_song + set(value: Int) { + super.songMenuRes = value + } + + init { + if (imageText != null) { + imageText!!.visibility = View.VISIBLE + } + if (dragView != null) { + dragView!!.visibility = View.VISIBLE + } + } + + override fun onSongMenuItemClick(item: MenuItem): Boolean { + when (item.itemId) { + R.id.action_remove_from_playing_queue -> { + MusicPlayerRemote.removeFromQueue(adapterPosition) + return true + } + } + return super.onSongMenuItemClick(item) + } + + @DraggableItemStateFlags + override fun getDragStateFlags(): Int { + return mDragStateFlags + } + + override fun setDragStateFlags(@DraggableItemStateFlags flags: Int) { + mDragStateFlags = flags + } + } + + companion object { + + private const val HISTORY = 0 + private const val CURRENT = 1 + private const val UP_NEXT = 2 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlaylistSongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlaylistSongAdapter.java deleted file mode 100644 index 14df6bfd..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlaylistSongAdapter.java +++ /dev/null @@ -1,93 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.util.Pair; -import androidx.appcompat.app.AppCompatActivity; -import android.view.MenuItem; -import android.view.View; - -import java.util.ArrayList; - -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; - - -public class PlaylistSongAdapter extends AbsOffsetSongAdapter { - - public static final String TAG = PlaylistSongAdapter.class.getSimpleName(); - - public PlaylistSongAdapter(AppCompatActivity activity, @NonNull ArrayList dataSet, @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder) { - super(activity, dataSet, itemLayoutRes, usePalette, cabHolder, false); - setMultiSelectMenuRes(R.menu.menu_cannot_delete_single_songs_playlist_songs_selection); - } - - @Override - protected SongAdapter.ViewHolder createViewHolder(View view) { - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull final SongAdapter.ViewHolder holder, int position) { - if (holder.getItemViewType() == OFFSET_ITEM) { - int textColor = ThemeStore.textColorSecondary(activity); - if (holder.title != null) { - holder.title.setText(MusicUtil.getPlaylistInfoString(activity, dataSet)); - holder.title.setTextColor(textColor); - } - - - if (holder.text != null) { - holder.text.setVisibility(View.GONE); - } - if (holder.menu != null) { - holder.menu.setVisibility(View.GONE); - } - if (holder.image != null) { - final int padding = activity.getResources().getDimensionPixelSize(R.dimen.default_item_margin) / 2; - holder.image.setPadding(padding, padding, padding, padding); - holder.image.setColorFilter(textColor); - holder.image.setImageResource(R.drawable.ic_timer_white_24dp); - } - if (holder.dragView != null) { - holder.dragView.setVisibility(View.GONE); - } - if (holder.separator != null) { - holder.separator.setVisibility(View.VISIBLE); - } - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.GONE); - } - } else { - super.onBindViewHolder(holder, position - 1); - } - } - - public class ViewHolder extends AbsOffsetSongAdapter.ViewHolder { - public ViewHolder(@NonNull View itemView) { - super(itemView); - - } - - @Override - protected int getSongMenuRes() { - return R.menu.menu_item_cannot_delete_single_songs_playlist_song; - } - - @Override - protected boolean onSongMenuItemClick(MenuItem item) { - if (item.getItemId() == R.id.action_go_to_album) { - Pair[] albumPairs = new Pair[]{ - Pair.create(image, activity.getString(R.string.transition_album_art))}; - NavigationUtil.goToAlbum(activity, dataSet.get(getAdapterPosition() - 1).albumId, albumPairs); - return true; - } - return super.onSongMenuItemClick(item); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlaylistSongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlaylistSongAdapter.kt new file mode 100644 index 00000000..e9a2069a --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/PlaylistSongAdapter.kt @@ -0,0 +1,86 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.view.MenuItem +import android.view.View +import android.widget.ImageView +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import androidx.core.util.Pair +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.PlaylistSong +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import java.util.* + + +open class PlaylistSongAdapter(activity: AppCompatActivity, dataSet: ArrayList, @LayoutRes itemLayoutRes: Int, usePalette: Boolean, cabHolder: CabHolder?) : AbsOffsetSongAdapter(activity, dataSet, itemLayoutRes, usePalette, cabHolder, false) { + + init { + this.setMultiSelectMenuRes(R.menu.menu_cannot_delete_single_songs_playlist_songs_selection) + } + + override fun createViewHolder(view: View): SongAdapter.ViewHolder { + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: SongAdapter.ViewHolder, position: Int) { + if (holder.itemViewType == AbsOffsetSongAdapter.OFFSET_ITEM) { + val textColor = ThemeStore.textColorSecondary(activity) + if (holder.title != null) { + holder.title!!.text = MusicUtil.getPlaylistInfoString(activity, dataSet) + holder.title!!.setTextColor(textColor) + } + + + if (holder.text != null) { + holder.text!!.visibility = View.GONE + } + if (holder.menu != null) { + holder.menu!!.visibility = View.GONE + } + if (holder.image != null) { + val padding = activity.resources.getDimensionPixelSize(R.dimen.default_item_margin) / 2 + holder.image!!.setPadding(padding, padding, padding, padding) + holder.image!!.setColorFilter(textColor) + holder.image!!.setImageResource(R.drawable.ic_timer_white_24dp) + } + if (holder.dragView != null) { + holder.dragView!!.visibility = View.GONE + } + if (holder.separator != null) { + holder.separator!!.visibility = View.VISIBLE + } + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.GONE + } + } else { + super.onBindViewHolder(holder, position - 1) + } + } + + open inner class ViewHolder(itemView: View) : AbsOffsetSongAdapter.ViewHolder(itemView) { + + override var songMenuRes: Int + get() = R.menu.menu_item_cannot_delete_single_songs_playlist_song + set(value) { + super.songMenuRes = value + } + + override fun onSongMenuItemClick(item: MenuItem): Boolean { + if (item.itemId == R.id.action_go_to_album) { + val albumPairs = arrayOf>(Pair.create(image, activity.getString(R.string.transition_album_art))) + NavigationUtil.goToAlbum(activity, dataSet[adapterPosition - 1].albumId, *albumPairs) + return true + } + return super.onSongMenuItemClick(item) + } + } + + companion object { + + val TAG = PlaylistSongAdapter::class.java.simpleName + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/ShuffleButtonSongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/ShuffleButtonSongAdapter.java deleted file mode 100644 index c358cae6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/ShuffleButtonSongAdapter.java +++ /dev/null @@ -1,80 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import android.view.View; - -import java.util.ArrayList; - -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Song; - - -public class ShuffleButtonSongAdapter extends AbsOffsetSongAdapter { - - public ShuffleButtonSongAdapter(AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder) { - super(activity, dataSet, itemLayoutRes, usePalette, cabHolder); - } - - @Override - protected SongAdapter.ViewHolder createViewHolder(View view) { - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull final SongAdapter.ViewHolder holder, int position) { - if (holder.getItemViewType() == OFFSET_ITEM) { - int accentColor = ThemeStore.accentColor(activity); - if (holder.title != null) { - holder.title.setText(activity.getResources().getString(R.string.action_shuffle_all)); - holder.title.setTextColor(accentColor); - /*((GradientTextView) holder.title).setLinearGradient(ThemeStore.accentColor(activity), - PhonographColorUtil.getMatColor(activity, "A400"), GradientTextView.LG_VERTICAL); - */ - } - if (holder.text != null) { - holder.text.setVisibility(View.GONE); - } - if (holder.menu != null) { - holder.menu.setVisibility(View.GONE); - } - if (holder.image != null) { - final int padding = - activity.getResources().getDimensionPixelSize(R.dimen.default_item_margin) / 2; - holder.image.setPadding(padding, padding, padding, padding); - holder.image.setColorFilter(accentColor); - holder.image.setImageResource(R.drawable.ic_shuffle_white_24dp); - } - if (holder.separator != null) { - holder.separator.setVisibility(View.VISIBLE); - } - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.GONE); - } - } else { - super.onBindViewHolder(holder, position - 1); - } - } - - public class ViewHolder extends AbsOffsetSongAdapter.ViewHolder { - - public ViewHolder(@NonNull View itemView) { - super(itemView); - } - - @Override - public void onClick(View v) { - if (getItemViewType() == OFFSET_ITEM) { - MusicPlayerRemote.openAndShuffleQueue(dataSet, true); - return; - } - super.onClick(v); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/ShuffleButtonSongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/ShuffleButtonSongAdapter.kt new file mode 100644 index 00000000..bd344dc6 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/ShuffleButtonSongAdapter.kt @@ -0,0 +1,64 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.view.View +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.Song +import java.util.* + + +class ShuffleButtonSongAdapter(activity: AppCompatActivity, + dataSet: ArrayList, + @LayoutRes itemLayoutRes: Int, + usePalette: Boolean, + cabHolder: CabHolder?) : AbsOffsetSongAdapter(activity, dataSet, itemLayoutRes, usePalette, cabHolder) { + + override fun createViewHolder(view: View): SongAdapter.ViewHolder { + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: SongAdapter.ViewHolder, position: Int) { + if (holder.itemViewType == AbsOffsetSongAdapter.OFFSET_ITEM) { + val accentColor = ThemeStore.accentColor(activity.applicationContext) + if (holder.title != null) { + holder.title!!.text = activity.resources.getString(R.string.action_shuffle_all) + holder.title!!.setTextColor(accentColor) + } + if (holder.text != null) { + holder.text!!.visibility = View.GONE + } + if (holder.menu != null) { + holder.menu!!.visibility = View.GONE + } + if (holder.image != null) { + val padding = activity.resources.getDimensionPixelSize(R.dimen.default_item_margin) / 2 + holder.image!!.setPadding(padding, padding, padding, padding) + holder.image!!.setColorFilter(accentColor) + holder.image!!.setImageResource(R.drawable.ic_shuffle_white_24dp) + } + if (holder.separator != null) { + holder.separator!!.visibility = View.VISIBLE + } + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.GONE + } + } else { + super.onBindViewHolder(holder, position - 1) + } + } + + inner class ViewHolder(itemView: View) : AbsOffsetSongAdapter.ViewHolder(itemView) { + + override fun onClick(v: View?) { + if (itemViewType == AbsOffsetSongAdapter.OFFSET_ITEM) { + MusicPlayerRemote.openAndShuffleQueue(dataSet, true) + return + } + super.onClick(v) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SimpleSongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SimpleSongAdapter.java deleted file mode 100755 index 25923cce..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SimpleSongAdapter.java +++ /dev/null @@ -1,69 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import android.view.LayoutInflater; -import android.view.ViewGroup; - -import java.util.ArrayList; - -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.MusicUtil; - -/** - * Created by Monkey D Luffy on 3/31/2016. - */ -public class SimpleSongAdapter extends SongAdapter { - - private int textColor; - - public SimpleSongAdapter(AppCompatActivity context, ArrayList songs, @LayoutRes int i) { - super(context, songs, i, false, null); - textColor = ThemeStore.textColorPrimary(context); - } - - public void swapDataSet(ArrayList arrayList) { - this.dataSet.clear(); - this.dataSet = arrayList; - notifyDataSetChanged(); - } - - @NonNull - public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - return new ViewHolder(LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)); - } - - @Override - public void onBindViewHolder(@NonNull ViewHolder holder, int position) { - super.onBindViewHolder(holder, position); - int fixedTrackNumber = MusicUtil.getFixedTrackNumber(dataSet.get(position).trackNumber); - - if (holder.imageText != null) { - holder.imageText.setText(fixedTrackNumber > 0 ? String.valueOf(fixedTrackNumber) : "-"); - holder.imageText.setTextColor(textColor); - } - - if (holder.time != null) { - holder.time.setText(MusicUtil.getReadableDurationString(dataSet.get(position).duration)); - holder.time.setTextColor(textColor); - } - if (holder.title != null) { - holder.title.setTextColor(textColor); - } - if (holder.menu != null) { - TintHelper.setTintAuto(holder.menu, textColor, false); - } - } - - public int getItemCount() { - return dataSet.size(); - } - - public void setTextColor(int textColor) { - this.textColor = textColor; - notifyDataSetChanged(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SimpleSongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SimpleSongAdapter.kt new file mode 100755 index 00000000..2d308ce6 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SimpleSongAdapter.kt @@ -0,0 +1,63 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import java.util.* + + +class SimpleSongAdapter(context: AppCompatActivity, + songs: ArrayList, + @LayoutRes i: Int) : SongAdapter(context, songs, i, false, null) { + + private var textColor: Int = 0 + + init { + textColor = ThemeStore.textColorPrimary(context) + } + + override fun swapDataSet(dataSet: ArrayList) { + this.dataSet.clear() + this.dataSet = dataSet + notifyDataSetChanged() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + return ViewHolder(LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false)) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + super.onBindViewHolder(holder, position) + val fixedTrackNumber = MusicUtil.getFixedTrackNumber(dataSet[position].trackNumber) + + if (holder.imageText != null) { + holder.imageText!!.text = if (fixedTrackNumber > 0) fixedTrackNumber.toString() else "-" + holder.imageText!!.setTextColor(textColor) + } + + if (holder.time != null) { + holder.time!!.text = MusicUtil.getReadableDurationString(dataSet[position].duration) + holder.time!!.setTextColor(textColor) + } + if (holder.title != null) { + holder.title!!.setTextColor(textColor) + } + if (holder.menu != null) { + TintHelper.setTintAuto(holder.menu!!, textColor, false) + } + } + + override fun getItemCount(): Int { + return dataSet.size + } + + fun setTextColor(textColor: Int) { + this.textColor = textColor + notifyDataSetChanged() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SongAdapter.java b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SongAdapter.java deleted file mode 100644 index 85623fe6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SongAdapter.java +++ /dev/null @@ -1,295 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter.song; - -import android.graphics.drawable.Drawable; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -import com.afollestad.materialcab.MaterialCab; -import com.bumptech.glide.Glide; -import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; - -import java.util.ArrayList; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.core.util.Pair; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.SortOrder; -import code.name.monkey.retromusic.helper.menu.SongMenuHelper; -import code.name.monkey.retromusic.helper.menu.SongsMenuHelper; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * Created by hemanths on 13/08/17. - */ - -public class SongAdapter extends AbsMultiSelectAdapter - implements MaterialCab.Callback, FastScrollRecyclerView.SectionedAdapter { - - public static final String TAG = SongAdapter.class.getSimpleName(); - - protected final AppCompatActivity activity; - protected ArrayList dataSet; - - protected int itemLayoutRes; - - protected boolean usePalette = false; - private boolean showSectionName = true; - - - public SongAdapter(AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder) { - this(activity, dataSet, itemLayoutRes, usePalette, cabHolder, true); - } - - public SongAdapter(AppCompatActivity activity, ArrayList dataSet, - @LayoutRes int itemLayoutRes, boolean usePalette, @Nullable CabHolder cabHolder, - boolean showSectionName) { - super(activity, cabHolder, R.menu.menu_media_selection); - this.activity = activity; - this.dataSet = dataSet; - this.itemLayoutRes = itemLayoutRes; - this.usePalette = usePalette; - this.showSectionName = showSectionName; - setHasStableIds(true); - } - - public void swapDataSet(ArrayList dataSet) { - this.dataSet = dataSet; - notifyDataSetChanged(); - } - - public void usePalette(boolean usePalette) { - this.usePalette = usePalette; - notifyDataSetChanged(); - } - - public ArrayList getDataSet() { - return dataSet; - } - - @Override - public long getItemId(int position) { - return dataSet.get(position).id; - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View view = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false); - return createViewHolder(view); - } - - protected ViewHolder createViewHolder(View view) { - return new ViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { - final Song song = dataSet.get(position); - - boolean isChecked = isChecked(song); - holder.itemView.setActivated(isChecked); - - if (holder.getAdapterPosition() == getItemCount() - 1) { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.GONE); - } - } else { - if (holder.shortSeparator != null) { - holder.shortSeparator.setVisibility(View.VISIBLE); - } - } - - if (holder.title != null) { - holder.title.setText(getSongTitle(song)); - } - if (holder.text != null) { - holder.text.setText(getSongText(song)); - } - - loadAlbumCover(song, holder); - - } - - private void setColors(int color, ViewHolder holder) { - if (holder.paletteColorContainer != null) { - holder.paletteColorContainer.setBackgroundColor(color); - if (holder.title != null) { - holder.title.setTextColor( - MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))); - } - if (holder.text != null) { - holder.text.setTextColor( - MaterialValueHelper.getSecondaryTextColor(activity, ColorUtil.isColorLight(color))); - } - } - } - - protected void loadAlbumCover(Song song, final ViewHolder holder) { - if (holder.image == null) { - return; - } - SongGlideRequest.Builder.from(Glide.with(activity), song) - .checkIgnoreMediaStore(activity) - .generatePalette(activity).build() - .into(new RetroMusicColoredTarget(holder.image) { - @Override - public void onLoadCleared(Drawable placeholder) { - super.onLoadCleared(placeholder); - setColors(getDefaultFooterColor(), holder); - } - - @Override - public void onColorReady(int color) { - setColors(color, holder); - } - }); - } - - private String getSongTitle(Song song) { - return song.title; - } - - private String getSongText(Song song) { - return song.artistName; - } - - @Override - public int getItemCount() { - return dataSet.size(); - } - - @Override - protected Song getIdentifier(int position) { - return dataSet.get(position); - } - - @Override - protected String getName(Song song) { - return song.title; - } - - @Override - protected void onMultipleItemAction(@NonNull MenuItem menuItem, - @NonNull ArrayList selection) { - SongsMenuHelper.handleMenuClick(activity, selection, menuItem.getItemId()); - } - - @NonNull - @Override - public String getSectionName(int position) { - if (!showSectionName) { - return ""; - } - @Nullable String sectionName = null; - switch (PreferenceUtil.getInstance().getSongSortOrder()) { - case SortOrder.SongSortOrder.SONG_A_Z: - case SortOrder.SongSortOrder.SONG_Z_A: - sectionName = dataSet.get(position).title; - break; - case SortOrder.SongSortOrder.SONG_ALBUM: - sectionName = dataSet.get(position).albumName; - break; - case SortOrder.SongSortOrder.SONG_ARTIST: - sectionName = dataSet.get(position).artistName; - break; - case SortOrder.SongSortOrder.SONG_YEAR: - return MusicUtil.getYearString(dataSet.get(position).year); - - } - - return MusicUtil.getSectionName(sectionName); - } - - public class ViewHolder extends MediaEntryViewHolder { - - int DEFAULT_MENU_RES = SongMenuHelper.MENU_RES; - - public ViewHolder(@NonNull View itemView) { - super(itemView); - setImageTransitionName(activity.getString(R.string.transition_album_art)); - - /*if (mItemView != null) { - mItemView.setOnMenuItemClickListener(new ListItemView.OnMenuItemClickListener() { - @Override - public void onActionMenuItemSelected(MenuItem item) { - SongMenuHelper.handleMenuClick(activity, dataSet.get(getAdapterPosition()), item.getItemId()); - } - }); - }*/ - - if (menu == null) { - return; - } - menu.setOnClickListener(new SongMenuHelper.OnClickSongMenu(activity) { - @Override - public Song getSong() { - return ViewHolder.this.getSong(); - } - - @Override - public int getMenuRes() { - return getSongMenuRes(); - } - - @Override - public boolean onMenuItemClick(MenuItem item) { - return onSongMenuItemClick(item) || super.onMenuItemClick(item); - } - }); - } - - protected Song getSong() { - return dataSet.get(getAdapterPosition()); - } - - protected int getSongMenuRes() { - return DEFAULT_MENU_RES; - } - - protected boolean onSongMenuItemClick(MenuItem item) { - if (image != null && image.getVisibility() == View.VISIBLE) { - switch (item.getItemId()) { - case R.id.action_go_to_album: - Pair[] albumPairs = new Pair[]{ - Pair.create(imageContainer, - activity.getResources().getString(R.string.transition_album_art)) - }; - NavigationUtil.goToAlbum(activity, getSong().albumId, albumPairs); - return true; - } - } - return false; - } - - @Override - public void onClick(View v) { - if (isInQuickSelectMode()) { - toggleChecked(getAdapterPosition()); - } else { - MusicPlayerRemote.openQueue(dataSet, getAdapterPosition(), true); - } - } - - @Override - public boolean onLongClick(View view) { - return toggleChecked(getAdapterPosition()); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SongAdapter.kt new file mode 100644 index 00000000..ee15f1be --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/song/SongAdapter.kt @@ -0,0 +1,224 @@ +package code.name.monkey.retromusic.ui.adapter.song + +import android.graphics.drawable.Drawable +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import androidx.annotation.LayoutRes +import androidx.appcompat.app.AppCompatActivity +import androidx.core.util.Pair +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.MaterialValueHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.SortOrder +import code.name.monkey.retromusic.helper.menu.SongMenuHelper +import code.name.monkey.retromusic.helper.menu.SongsMenuHelper +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.base.AbsMultiSelectAdapter +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import com.afollestad.materialcab.MaterialCab +import com.bumptech.glide.Glide +import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView +import java.util.* + +/** + * Created by hemanths on 13/08/17. + */ + +open class SongAdapter @JvmOverloads constructor(protected val activity: AppCompatActivity, dataSet: ArrayList, + @param:LayoutRes protected var itemLayoutRes: Int, usePalette: Boolean, cabHolder: CabHolder?, + showSectionName: Boolean = true) : AbsMultiSelectAdapter(activity, cabHolder, R.menu.menu_media_selection), MaterialCab.Callback, FastScrollRecyclerView.SectionedAdapter { + var dataSet: ArrayList + protected set + + protected var usePalette = false + private var showSectionName = true + + init { + this.dataSet = dataSet + this.usePalette = usePalette + this.showSectionName = showSectionName + this.setHasStableIds(true) + } + + open fun swapDataSet(dataSet: ArrayList) { + this.dataSet = dataSet + notifyDataSetChanged() + } + + open fun usePalette(usePalette: Boolean) { + this.usePalette = usePalette + notifyDataSetChanged() + } + + override fun getItemId(position: Int): Long { + return dataSet[position].id.toLong() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { + val view = LayoutInflater.from(activity).inflate(itemLayoutRes, parent, false) + return createViewHolder(view) + } + + protected open fun createViewHolder(view: View): ViewHolder { + return ViewHolder(view) + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val song = dataSet[position] + + val isChecked = isChecked(song) + holder.itemView.isActivated = isChecked + + if (holder.adapterPosition == itemCount - 1) { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.GONE + } + } else { + if (holder.shortSeparator != null) { + holder.shortSeparator!!.visibility = View.VISIBLE + } + } + + if (holder.title != null) { + holder.title!!.text = getSongTitle(song) + } + if (holder.text != null) { + holder.text!!.text = getSongText(song) + } + + loadAlbumCover(song, holder) + + } + + private fun setColors(color: Int, holder: ViewHolder) { + if (holder.paletteColorContainer != null) { + holder.paletteColorContainer!!.setBackgroundColor(color) + if (holder.title != null) { + holder.title!!.setTextColor(MaterialValueHelper.getPrimaryTextColor(activity, ColorUtil.isColorLight(color))) + } + if (holder.text != null) { + holder.text!!.setTextColor(MaterialValueHelper.getSecondaryTextColor(activity, ColorUtil.isColorLight(color))) + } + } + } + + protected open fun loadAlbumCover(song: Song, holder: ViewHolder) { + if (holder.image == null) { + return + } + + SongGlideRequest.Builder.from(Glide.with(activity), song) + .checkIgnoreMediaStore(activity) + .generatePalette(activity).build() + .into(object : RetroMusicColoredTarget(holder.image!!) { + override fun onLoadCleared(placeholder: Drawable?) { + super.onLoadCleared(placeholder) + setColors(defaultFooterColor, holder) + } + + override fun onColorReady(color: Int) { + setColors(color, holder) + } + }) + } + + private fun getSongTitle(song: Song): String? { + return song.title + } + + private fun getSongText(song: Song): String? { + return song.artistName + } + + override fun getItemCount(): Int { + return dataSet.size + } + + override fun getIdentifier(position: Int): Song? { + return dataSet[position] + } + + override fun getName(song: Song): String { + return song.title!! + } + + override fun onMultipleItemAction(menuItem: MenuItem, + selection: ArrayList) { + SongsMenuHelper.handleMenuClick(activity, selection, menuItem.itemId) + } + + override fun getSectionName(position: Int): String { + var sectionName: String? = null + when (PreferenceUtil.getInstance().songSortOrder) { + SortOrder.SongSortOrder.SONG_A_Z, SortOrder.SongSortOrder.SONG_Z_A -> sectionName = dataSet[position].title + SortOrder.SongSortOrder.SONG_ALBUM -> sectionName = dataSet[position].albumName + SortOrder.SongSortOrder.SONG_ARTIST -> sectionName = dataSet[position].artistName + SortOrder.SongSortOrder.SONG_YEAR -> return MusicUtil.getYearString(dataSet[position].year) + } + + return MusicUtil.getSectionName(sectionName) + } + + open inner class ViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + protected open var songMenuRes = SongMenuHelper.MENU_RES + + protected open val song: Song + get() = dataSet[adapterPosition] + + init { + setImageTransitionName(activity.getString(R.string.transition_album_art)) + menu!!.setOnClickListener(object : SongMenuHelper.OnClickSongMenu(activity) { + override val song: Song + get() = this@ViewHolder.song + + override val menuRes: Int + get() = songMenuRes + + override fun onMenuItemClick(item: MenuItem): Boolean { + return onSongMenuItemClick(item) || super.onMenuItemClick(item) + } + }) + } + + protected open fun onSongMenuItemClick(item: MenuItem): Boolean { + if (image != null && image!!.visibility == View.VISIBLE) { + when (item.itemId) { + R.id.action_go_to_album -> { + val albumPairs = arrayOf>(Pair.create(imageContainer, + activity.resources.getString(R.string.transition_album_art))) + NavigationUtil.goToAlbum(activity, song.albumId, *albumPairs) + return true + } + } + } + return false + } + + override fun onClick(v: View?) { + if (isInQuickSelectMode) { + toggleChecked(adapterPosition) + } else { + MusicPlayerRemote.openQueue(dataSet, adapterPosition, true) + } + } + + override fun onLongClick(v: View?): Boolean { + return toggleChecked(adapterPosition) + } + } + + companion object { + + val TAG = SongAdapter::class.java.simpleName + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/MiniPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/MiniPlayerFragment.java deleted file mode 100644 index e87e4d34..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/MiniPlayerFragment.java +++ /dev/null @@ -1,228 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments; - -import android.animation.ObjectAnimator; -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.res.ColorStateList; -import android.os.Bundle; -import android.text.SpannableString; -import android.text.SpannableStringBuilder; -import android.text.style.ForegroundColorSpan; -import android.view.GestureDetector; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.DecelerateInterpolator; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.util.Pair; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsMusicServiceFragment; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import me.zhanghai.android.materialprogressbar.MaterialProgressBar; - -public class MiniPlayerFragment extends AbsMusicServiceFragment implements MusicProgressViewUpdateHelper.Callback { - - @BindView(R.id.mini_player_title) - TextView miniPlayerTitle; - - @BindView(R.id.mini_player_play_pause_button) - ImageView miniPlayerPlayPauseButton; - - @BindView(R.id.action_next) - View next; - - @BindView(R.id.action_prev) - View previous; - - @BindView(R.id.action_playing_queue) - View playingQueue; - - @BindView(R.id.progress_bar) - MaterialProgressBar progressBar; - - private Unbinder unbinder; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View layout = inflater.inflate(R.layout.fragment_mini_player, container, false); - unbinder = ButterKnife.bind(this, layout); - return layout; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - //noinspection ConstantConditions - view.setBackgroundColor(ThemeStore.primaryColor(getContext())); - view.setOnTouchListener(new FlingPlayBackController(getActivity())); - //view.setOnClickListener(v -> NavigationUtil.gotoNowPlayingActivity(getContext())); - setUpMiniPlayer(); - - if (RetroUtil.isTablet()) { - next.setVisibility(View.VISIBLE); - previous.setVisibility(View.VISIBLE); - playingQueue.setVisibility(View.VISIBLE); - } else{ - next.setVisibility(PreferenceUtil.getInstance().isExtraMiniExtraControls() ? View.VISIBLE : View.GONE); - playingQueue.setVisibility(PreferenceUtil.getInstance().isExtraMiniExtraControls() ? View.GONE : View.VISIBLE); - previous.setVisibility(PreferenceUtil.getInstance().isExtraMiniExtraControls() ? View.VISIBLE : View.GONE); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @SuppressWarnings({"ConstantConditions"}) - private void setUpMiniPlayer() { - setUpPlayPauseButton(); - progressBar.setProgressTintList(ColorStateList.valueOf(ThemeStore.accentColor(getActivity()))); - } - - private void setUpPlayPauseButton() { - //noinspection ConstantConditions - miniPlayerPlayPauseButton.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - private void updateSongTitle() { - SpannableStringBuilder builder = new SpannableStringBuilder(); - - Song song = MusicPlayerRemote.getCurrentSong(); - if (song == null) { - return; - } - SpannableString title = new SpannableString(song.title); - title.setSpan(new ForegroundColorSpan(ThemeStore.textColorPrimary(getContext())), 0, title.length(), 0); - - SpannableString text = new SpannableString(song.artistName); - text.setSpan(new ForegroundColorSpan(ThemeStore.textColorSecondary(getContext())), 0, text.length(), 0); - - builder.append(title).append(" • ").append(text); - - miniPlayerTitle.setSelected(true); - miniPlayerTitle.setText(builder); - } - - @Override - public void onServiceConnected() { - updateSongTitle(); - updatePlayPauseDrawableState(); - } - - @Override - public void onPlayingMetaChanged() { - updateSongTitle(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressBar.setMax(total); - ObjectAnimator animator = ObjectAnimator.ofInt(progressBar, "progress", progress); - animator.setDuration(1000); - animator.setInterpolator(new DecelerateInterpolator()); - animator.start(); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - miniPlayerPlayPauseButton.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - miniPlayerPlayPauseButton.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - public void setColor(int playerFragmentColor) { - //noinspection ConstantConditions - getView().setBackgroundColor(playerFragmentColor); - } - - @OnClick({R.id.action_prev, R.id.action_playing_queue, R.id.action_next}) - void onClicks(View view) { - switch (view.getId()) { - case R.id.action_playing_queue: - NavigationUtil.goToPlayingQueue(getActivity()); - break; - case R.id.action_next: - MusicPlayerRemote.playNextSong(); - break; - case R.id.action_prev: - MusicPlayerRemote.back(); - break; - } - } - - public static class FlingPlayBackController implements View.OnTouchListener { - - GestureDetector flingPlayBackController; - - public FlingPlayBackController(Context context) { - flingPlayBackController = new GestureDetector(context, - new GestureDetector.SimpleOnGestureListener() { - @Override - public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, - float velocityY) { - if (Math.abs(velocityX) > Math.abs(velocityY)) { - if (velocityX < 0) { - MusicPlayerRemote.playNextSong(); - return true; - } else if (velocityX > 0) { - MusicPlayerRemote.playPreviousSong(); - return true; - } - } - return false; - } - }); - } - - @SuppressLint("ClickableViewAccessibility") - @Override - public boolean onTouch(View v, MotionEvent event) { - return flingPlayBackController.onTouchEvent(event); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/MiniPlayerFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/MiniPlayerFragment.kt new file mode 100644 index 00000000..d627fd68 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/MiniPlayerFragment.kt @@ -0,0 +1,165 @@ +package code.name.monkey.retromusic.ui.fragments + +import android.animation.ObjectAnimator +import android.annotation.SuppressLint +import android.content.Context +import android.content.res.ColorStateList +import android.os.Bundle +import android.text.SpannableString +import android.text.SpannableStringBuilder +import android.text.style.ForegroundColorSpan +import android.view.* +import android.view.animation.DecelerateInterpolator +import butterknife.OnClick +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper +import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler +import code.name.monkey.retromusic.ui.fragments.base.AbsMusicServiceFragment +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import kotlinx.android.synthetic.main.fragment_mini_player.* + +open class MiniPlayerFragment : AbsMusicServiceFragment(), MusicProgressViewUpdateHelper.Callback, View.OnClickListener { + private var progressViewUpdateHelper: MusicProgressViewUpdateHelper? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + progressViewUpdateHelper = MusicProgressViewUpdateHelper(this) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_mini_player, container, false) + } + override fun onClick(view: View) { + when (view.id) { + R.id.actionPlayingQueue -> NavigationUtil.goToPlayingQueue(activity!!) + R.id.actionNext -> MusicPlayerRemote.playNextSong() + R.id.actionPrevious -> MusicPlayerRemote.back() + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + view.setBackgroundColor(ThemeStore.primaryColor(context!!)) + view.setOnTouchListener(FlingPlayBackController(context!!)) + //view.setOnClickListener(v -> NavigationUtil.gotoNowPlayingActivity(getContext())); + setUpMiniPlayer() + + if (RetroUtil.isTablet()) { + actionNext!!.visibility = View.VISIBLE + actionPrevious!!.visibility = View.VISIBLE + actionPlayingQueue!!.visibility = View.VISIBLE + } else { + actionNext!!.visibility = if (PreferenceUtil.getInstance().isExtraMiniExtraControls) View.VISIBLE else View.GONE + actionPlayingQueue!!.visibility = if (PreferenceUtil.getInstance().isExtraMiniExtraControls) View.GONE else View.VISIBLE + actionPrevious!!.visibility = if (PreferenceUtil.getInstance().isExtraMiniExtraControls) View.VISIBLE else View.GONE + } + + actionPlayingQueue.setOnClickListener(this) + actionNext.setOnClickListener(this) + actionPrevious.setOnClickListener(this) + } + + private fun setUpMiniPlayer() { + setUpPlayPauseButton() + progressBar!!.progressTintList = ColorStateList.valueOf(ThemeStore.accentColor(activity!!)) + } + + private fun setUpPlayPauseButton() { + miniPlayerPlayPauseButton.setOnClickListener(PlayPauseButtonOnClickHandler()) + } + + private fun updateSongTitle() { + val builder = SpannableStringBuilder() + + val song = MusicPlayerRemote.currentSong ?: return + val title = SpannableString(song.title) + title.setSpan(ForegroundColorSpan(ThemeStore.textColorPrimary(context!!)), 0, title.length, 0) + + val text = SpannableString(song.artistName) + text.setSpan(ForegroundColorSpan(ThemeStore.textColorSecondary(context!!)), 0, text.length, 0) + + builder.append(title).append(" • ").append(text) + + miniPlayerTitle.isSelected = true + miniPlayerTitle.text = builder + } + + override fun onServiceConnected() { + updateSongTitle() + updatePlayPauseDrawableState() + } + + override fun onPlayingMetaChanged() { + updateSongTitle() + } + + override fun onPlayStateChanged() { + updatePlayPauseDrawableState() + } + + override fun onUpdateProgressViews(progress: Int, total: Int) { + progressBar.max = total + val animator = ObjectAnimator.ofInt(progressBar, "progress", progress) + animator.duration = 1000 + animator.interpolator = DecelerateInterpolator() + animator.start() + } + + override fun onResume() { + super.onResume() + progressViewUpdateHelper!!.start() + } + + override fun onPause() { + super.onPause() + progressViewUpdateHelper!!.stop() + } + + protected fun updatePlayPauseDrawableState() { + if (MusicPlayerRemote.isPlaying) { + miniPlayerPlayPauseButton!!.setImageResource(R.drawable.ic_pause_white_24dp) + } else { + miniPlayerPlayPauseButton!!.setImageResource(R.drawable.ic_play_arrow_white_24dp) + } + } + + fun setColor(playerFragmentColor: Int) { + + view!!.setBackgroundColor(playerFragmentColor) + } + + + class FlingPlayBackController(context: Context) : View.OnTouchListener { + + internal var flingPlayBackController: GestureDetector + + init { + flingPlayBackController = GestureDetector(context, + object : GestureDetector.SimpleOnGestureListener() { + override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, + velocityY: Float): Boolean { + if (Math.abs(velocityX) > Math.abs(velocityY)) { + if (velocityX < 0) { + MusicPlayerRemote.playNextSong() + return true + } else if (velocityX > 0) { + MusicPlayerRemote.playPreviousSong() + return true + } + } + return false + } + }) + } + + @SuppressLint("ClickableViewAccessibility") + override fun onTouch(v: View, event: MotionEvent): Boolean { + return flingPlayBackController.onTouchEvent(event) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/NowPlayingScreen.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/NowPlayingScreen.java index 237fcbe0..59f4288e 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/NowPlayingScreen.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/NowPlayingScreen.java @@ -8,18 +8,7 @@ import code.name.monkey.retromusic.R; public enum NowPlayingScreen { ADAPTIVE(R.string.adaptive, R.drawable.np_adaptive, 10), - BLUR(R.string.blur, R.drawable.np_blur, 4), - CARD(R.string.card, R.drawable.np_card, 6), - COLOR(R.string.color, R.drawable.np_color, 5), - BLUR_CARD(R.string.blur_card, R.drawable.np_blur_card, 9), - FIT(R.string.fit, R.drawable.np_adaptive, 12), - FLAT(R.string.flat, R.drawable.np_flat, 1), - FULL(R.string.full, R.drawable.np_full, 2), - TINY(R.string.tiny, R.drawable.np_tiny, 7), - MATERIAL(R.string.material, R.drawable.np_material, 11), - NORMAL(R.string.normal, R.drawable.np_normal, 0), - PLAIN(R.string.plain, R.drawable.np_plain, 3), - SIMPLE(R.string.simple, R.drawable.np_simple, 8); + BLUR(R.string.blur, R.drawable.np_blur, 4); @StringRes public final int titleRes; diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/PlayingQueueFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/PlayingQueueFragment.java index ab68d10e..6f6865d7 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/PlayingQueueFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/PlayingQueueFragment.java @@ -58,8 +58,8 @@ public class PlayingQueueFragment extends AbsMusicServiceFragment { mPlayingQueueAdapter = new PlayingQueueAdapter( (AppCompatActivity) getActivity(), - MusicPlayerRemote.getPlayingQueue(), - MusicPlayerRemote.getPosition(), + MusicPlayerRemote.INSTANCE.getPlayingQueue(), + MusicPlayerRemote.INSTANCE.getPosition(), R.layout.item_queue); mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(mPlayingQueueAdapter); @@ -69,7 +69,7 @@ public class PlayingQueueFragment extends AbsMusicServiceFragment { mRecyclerView.setAdapter(mWrappedAdapter); mRecyclerView.setItemAnimator(animator); mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView); - mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); + mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.INSTANCE.getPosition() + 1, 0); } @@ -98,7 +98,7 @@ public class PlayingQueueFragment extends AbsMusicServiceFragment { } private void updateQueuePosition() { - mPlayingQueueAdapter.setCurrent(MusicPlayerRemote.getPosition()); + mPlayingQueueAdapter.setCurrent(MusicPlayerRemote.INSTANCE.getPosition()); // if (slidingUpPanelLayout.getPanelState() == SlidingUpPanelLayout.PanelState.COLLAPSED) { resetToCurrentPosition(); //} @@ -106,13 +106,13 @@ public class PlayingQueueFragment extends AbsMusicServiceFragment { private void updateQueue() { mPlayingQueueAdapter - .swapDataSet(MusicPlayerRemote.getPlayingQueue(), MusicPlayerRemote.getPosition()); + .swapDataSet(MusicPlayerRemote.INSTANCE.getPlayingQueue(), MusicPlayerRemote.INSTANCE.getPosition()); resetToCurrentPosition(); } private void resetToCurrentPosition() { mRecyclerView.stopScroll(); - mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); + mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.INSTANCE.getPosition() + 1, 0); } @Override diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/VolumeFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/VolumeFragment.java deleted file mode 100755 index a314fd92..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/VolumeFragment.java +++ /dev/null @@ -1,172 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments; - -import android.content.Context; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.media.AudioManager; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.SeekBar; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.volume.AudioVolumeObserver; -import code.name.monkey.retromusic.volume.OnAudioVolumeChangedListener; - -public class VolumeFragment extends Fragment implements SeekBar.OnSeekBarChangeListener, - OnAudioVolumeChangedListener { - - @BindView(R.id.volume_seekbar) - SeekBar volumeSeekbar; - - @BindView(R.id.volume_down) - ImageView volumeDown; - - @BindView(R.id.container) - ViewGroup viewGroup; - - @BindView(R.id.volume_up) - ImageView volumeUp; - - private Unbinder unbinder; - private AudioVolumeObserver mAudioVolumeObserver; - - public static VolumeFragment newInstance() { - return new VolumeFragment(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_volume, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - //noinspection ConstantConditions - setTintable(ATHUtil.resolveColor(getContext(), R.attr.iconColor)); - } - - @Override - public void onResume() { - super.onResume(); - if (mAudioVolumeObserver == null) { - //noinspection ConstantConditions - mAudioVolumeObserver = new AudioVolumeObserver(getActivity()); - } - mAudioVolumeObserver.register(AudioManager.STREAM_MUSIC, this); - - AudioManager audioManager = getAudioManager(); - if (audioManager != null) { - volumeSeekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)); - volumeSeekbar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)); - } - volumeSeekbar.setOnSeekBarChangeListener(this); - } - - @Override - public void onAudioVolumeChanged(int currentVolume, int maxVolume) { - if (volumeSeekbar == null) { - return; - } - volumeSeekbar.setMax(maxVolume); - volumeSeekbar.setProgress(currentVolume); - volumeDown.setImageResource(currentVolume == 0 ? R.drawable.ic_volume_off_white_24dp : R.drawable.ic_volume_down_white_24dp); - } - - private AudioManager getAudioManager() { - //noinspection ConstantConditions - return (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - if (mAudioVolumeObserver != null) { - mAudioVolumeObserver.unregister(); - } - } - - @Override - public void onProgressChanged(SeekBar seekBar, int i, boolean b) { - AudioManager audioManager = getAudioManager(); - if (audioManager != null) { - audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0); - } - setPauseWhenZeroVolume(i < 1); - volumeDown.setImageResource(i == 0 ? R.drawable.ic_volume_off_white_24dp : R.drawable.ic_volume_down_white_24dp); - - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - - @OnClick({R.id.volume_down, R.id.volume_up}) - public void onViewClicked(View view) { - AudioManager audioManager = getAudioManager(); - switch (view.getId()) { - case R.id.volume_down: - if (audioManager != null) { - audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0); - } - break; - case R.id.volume_up: - if (audioManager != null) { - audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0); - } - break; - } - } - - public void tintWhiteColor() { - setProgressBarColor(Color.WHITE); - } - - private void setProgressBarColor(int newColor) { - TintHelper.setTintAuto(volumeSeekbar, newColor, false); - volumeDown.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); - volumeUp.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); - } - - public void setTintable(int color) { - setProgressBarColor(color); - } - - public void removeThumb() { - volumeSeekbar.setThumb(null); - } - - private void setPauseWhenZeroVolume(boolean pauseWhenZeroVolume) { - if (PreferenceUtil.getInstance().pauseOnZeroVolume() && pauseWhenZeroVolume) - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/VolumeFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/VolumeFragment.kt new file mode 100755 index 00000000..3fb07eea --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/VolumeFragment.kt @@ -0,0 +1,129 @@ +package code.name.monkey.retromusic.ui.fragments + +import android.content.Context +import android.graphics.Color +import android.graphics.PorterDuff +import android.media.AudioManager +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.SeekBar +import androidx.fragment.app.Fragment +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.volume.AudioVolumeObserver +import code.name.monkey.retromusic.volume.OnAudioVolumeChangedListener +import kotlinx.android.synthetic.main.fragment_volume.* + +class VolumeFragment : Fragment(), SeekBar.OnSeekBarChangeListener, OnAudioVolumeChangedListener, View.OnClickListener { + + private var audioVolumeObserver: AudioVolumeObserver? = null + + private val audioManager: AudioManager? + get() = context!!.getSystemService(Context.AUDIO_SERVICE) as AudioManager + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_volume, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setTintable(ATHUtil.resolveColor(context, R.attr.iconColor)) + volumeDown.setOnClickListener(this) + volumeUp.setOnClickListener(this) + } + + override fun onResume() { + super.onResume() + if (audioVolumeObserver == null) { + audioVolumeObserver = AudioVolumeObserver(activity!!) + } + audioVolumeObserver!!.register(AudioManager.STREAM_MUSIC, this) + + val audioManager = audioManager + if (audioManager != null) { + volumeSeekBar!!.max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) + volumeSeekBar!!.progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) + } + volumeSeekBar!!.setOnSeekBarChangeListener(this) + } + + override fun onAudioVolumeChanged(currentVolume: Int, maxVolume: Int) { + if (volumeSeekBar == null) { + return + } + volumeSeekBar!!.max = maxVolume + volumeSeekBar!!.progress = currentVolume + volumeDown!!.setImageResource(if (currentVolume == 0) R.drawable.ic_volume_off_white_24dp else R.drawable.ic_volume_down_white_24dp) + } + + override fun onDestroyView() { + super.onDestroyView() + if (audioVolumeObserver != null) { + audioVolumeObserver!!.unregister() + } + } + + override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { + val audioManager = audioManager + audioManager?.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0) + setPauseWhenZeroVolume(i < 1) + volumeDown!!.setImageResource(if (i == 0) R.drawable.ic_volume_off_white_24dp else R.drawable.ic_volume_down_white_24dp) + + } + + override fun onStartTrackingTouch(seekBar: SeekBar) { + + } + + override fun onStopTrackingTouch(seekBar: SeekBar) { + + } + + override fun onClick(view: View) { + val audioManager = audioManager + when (view.id) { + R.id.volumeDown -> audioManager?.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0) + R.id.volumeUp -> audioManager?.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0) + } + } + + fun tintWhiteColor() { + setProgressBarColor(Color.WHITE) + } + + private fun setProgressBarColor(newColor: Int) { + TintHelper.setTintAuto(volumeSeekBar!!, newColor, false) + volumeDown!!.setColorFilter(newColor, PorterDuff.Mode.SRC_IN) + volumeUp!!.setColorFilter(newColor, PorterDuff.Mode.SRC_IN) + } + + private fun setTintable(color: Int) { + setProgressBarColor(color) + } + + fun removeThumb() { + volumeSeekBar!!.thumb = null + } + + private fun setPauseWhenZeroVolume(pauseWhenZeroVolume: Boolean) { + if (PreferenceUtil.getInstance().pauseOnZeroVolume() && pauseWhenZeroVolume) + if (MusicPlayerRemote.isPlaying) { + MusicPlayerRemote.pauseSong() + } else { + MusicPlayerRemote.resumePlaying() + } + } + + companion object { + + fun newInstance(): VolumeFragment { + return VolumeFragment() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerFragment.java deleted file mode 100644 index 724a78fe..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerFragment.java +++ /dev/null @@ -1,19 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.os.Bundle; - -import code.name.monkey.retromusic.ui.fragments.mainactivity.LibraryFragment; - -public class AbsLibraryPagerFragment extends AbsMusicServiceFragment { - - - public LibraryFragment getLibraryFragment() { - return (LibraryFragment) getParentFragment(); - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - setHasOptionsMenu(true); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerFragment.kt new file mode 100644 index 00000000..b5b5123d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerFragment.kt @@ -0,0 +1,17 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.os.Bundle + +import code.name.monkey.retromusic.ui.fragments.mainactivity.LibraryFragment + +open class AbsLibraryPagerFragment : AbsMusicServiceFragment() { + + + val libraryFragment: LibraryFragment + get() = parentFragment as LibraryFragment + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + setHasOptionsMenu(true) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewCustomGridSizeFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewCustomGridSizeFragment.java deleted file mode 100644 index 3c1a4dc5..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewCustomGridSizeFragment.java +++ /dev/null @@ -1,169 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.os.Bundle; -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import android.view.View; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.util.RetroUtil; - - -public abstract class AbsLibraryPagerRecyclerViewCustomGridSizeFragment extends - AbsLibraryPagerRecyclerViewFragment { - - private int gridSize; - private String sortOrder; - - private boolean usePaletteInitialized; - private boolean usePalette; - private int currentLayoutRes; - - public final int getGridSize() { - if (gridSize == 0) { - if (isLandscape()) { - gridSize = loadGridSizeLand(); - } else { - gridSize = loadGridSize(); - } - } - return gridSize; - } - - protected abstract void setGridSize(int gridSize); - - public final String getSortOrder() { - if (sortOrder == null) { - sortOrder = loadSortOrder(); - } - return sortOrder; - } - - protected abstract void setSortOrder(String sortOrder); - - public void setAndSaveSortOrder(final String sortOrder) { - this.sortOrder = sortOrder; - saveSortOrder(sortOrder); - setSortOrder(sortOrder); - } - - public int getMaxGridSize() { - if (isLandscape()) { - return getResources().getInteger(R.integer.max_columns_land); - } else { - return getResources().getInteger(R.integer.max_columns); - } - } - - /** - * @return whether the palette should be used at all or not - */ - public final boolean usePalette() { - if (!usePaletteInitialized) { - usePalette = loadUsePalette(); - usePaletteInitialized = true; - } - return usePalette; - } - - public void setAndSaveGridSize(final int gridSize) { - int oldLayoutRes = getItemLayoutRes(); - this.gridSize = gridSize; - if (isLandscape()) { - saveGridSizeLand(gridSize); - } else { - saveGridSize(gridSize); - } - // only recreate the adapter and layout manager if the layout currentLayoutRes has changed - if (oldLayoutRes != getItemLayoutRes()) { - invalidateLayoutManager(); - invalidateAdapter(); - } else { - setGridSize(gridSize); - } - } - - public void setAndSaveUsePalette(final boolean usePalette) { - this.usePalette = usePalette; - saveUsePalette(usePalette); - setUsePalette(usePalette); - } - - /** - * @return whether the palette option should be available for the current item layout or not - */ - public boolean canUsePalette() { - return getItemLayoutRes() == R.layout.item_color; - } - - /** - * Override to customize which item layout currentLayoutRes should be used. You might also want to - * override {@link #canUsePalette()} then. - * - * @see #getGridSize() - */ - @LayoutRes - protected int getItemLayoutRes() { - if (getGridSize() > getMaxGridSizeForList()) { - return R.layout.item_grid; - } - return R.layout.item_list; - } - - protected final void notifyLayoutResChanged(@LayoutRes int res) { - this.currentLayoutRes = res; - RecyclerView recyclerView = getRecyclerView(); - if (recyclerView != null) { - applyRecyclerViewPaddingForLayoutRes(recyclerView, currentLayoutRes); - } - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - applyRecyclerViewPaddingForLayoutRes(getRecyclerView(), currentLayoutRes); - } - - protected void applyRecyclerViewPaddingForLayoutRes(@NonNull RecyclerView recyclerView, - @LayoutRes int res) { - int padding; - if (res == R.layout.item_grid) { - padding = (int) (getResources().getDisplayMetrics().density * 2); - } else { - padding = 0; - } - recyclerView.setPadding(padding, padding, padding, padding); - } - - protected abstract String loadSortOrder(); - - protected abstract void saveSortOrder(String sortOrder); - - protected abstract int loadGridSize(); - - protected abstract void saveGridSize(int gridColumns); - - protected abstract int loadGridSizeLand(); - - protected abstract void saveGridSizeLand(int gridColumns); - - protected abstract void saveUsePalette(boolean usePalette); - - protected abstract boolean loadUsePalette(); - - protected abstract void setUsePalette(boolean usePalette); - - protected int getMaxGridSizeForList() { - if (isLandscape()) { - return getActivity().getResources().getInteger(R.integer.default_list_columns_land); - } - return getActivity().getResources().getInteger(R.integer.default_list_columns); - } - - protected final boolean isLandscape() { - return RetroUtil.isLandscape( ); - } - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewCustomGridSizeFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewCustomGridSizeFragment.kt new file mode 100644 index 00000000..e2c8ad05 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewCustomGridSizeFragment.kt @@ -0,0 +1,157 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.os.Bundle +import android.view.View +import androidx.annotation.LayoutRes +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.util.RetroUtil + + +abstract class AbsLibraryPagerRecyclerViewCustomGridSizeFragment, LM : RecyclerView.LayoutManager> : AbsLibraryPagerRecyclerViewFragment() { + + private var gridSize: Int = 0 + private var sortOrder: String? = null + + private var usePaletteInitialized: Boolean = false + private var usePalette: Boolean = false + private var currentLayoutRes: Int = 0 + + val maxGridSize: Int + get() = if (isLandscape) { + resources.getInteger(R.integer.max_columns_land) + } else { + resources.getInteger(R.integer.max_columns) + } + + /** + * Override to customize which item layout currentLayoutRes should be used. You might also want to + * override [.canUsePalette] then. + * + * @see .getGridSize + */ + protected val itemLayoutRes: Int + @LayoutRes + get() = if (getGridSize() > maxGridSizeForList) { + R.layout.item_grid + } else R.layout.item_list + + protected val maxGridSizeForList: Int + get() = if (isLandscape) { + activity!!.resources.getInteger(R.integer.default_list_columns_land) + } else activity!!.resources.getInteger(R.integer.default_list_columns) + + protected val isLandscape: Boolean + get() = RetroUtil.isLandscape() + + fun getGridSize(): Int { + if (gridSize == 0) { + if (isLandscape) { + gridSize = loadGridSizeLand() + } else { + gridSize = loadGridSize() + } + } + return gridSize + } + + protected abstract fun setGridSize(gridSize: Int) + + fun getSortOrder(): String? { + if (sortOrder == null) { + sortOrder = loadSortOrder() + } + return sortOrder + } + + protected abstract fun setSortOrder(sortOrder: String) + + fun setAndSaveSortOrder(sortOrder: String) { + this.sortOrder = sortOrder + saveSortOrder(sortOrder) + setSortOrder(sortOrder) + } + + /** + * @return whether the palette should be used at all or not + */ + fun usePalette(): Boolean { + if (!usePaletteInitialized) { + usePalette = loadUsePalette() + usePaletteInitialized = true + } + return usePalette + } + + fun setAndSaveGridSize(gridSize: Int) { + val oldLayoutRes = itemLayoutRes + this.gridSize = gridSize + if (isLandscape) { + saveGridSizeLand(gridSize) + } else { + saveGridSize(gridSize) + } + // only recreate the adapter and layout manager if the layout currentLayoutRes has changed + if (oldLayoutRes != itemLayoutRes) { + invalidateLayoutManager() + invalidateAdapter() + } else { + setGridSize(gridSize) + } + } + + fun setAndSaveUsePalette(usePalette: Boolean) { + this.usePalette = usePalette + saveUsePalette(usePalette) + setUsePalette(usePalette) + } + + /** + * @return whether the palette option should be available for the current item layout or not + */ + fun canUsePalette(): Boolean { + return itemLayoutRes == R.layout.item_color + } + + protected fun notifyLayoutResChanged(@LayoutRes res: Int) { + this.currentLayoutRes = res + val recyclerView = recyclerView() + applyRecyclerViewPaddingForLayoutRes(recyclerView, currentLayoutRes) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + applyRecyclerViewPaddingForLayoutRes(recyclerView(), currentLayoutRes) + } + + private fun applyRecyclerViewPaddingForLayoutRes(recyclerView: RecyclerView, + @LayoutRes res: Int) { + val padding: Int + if (res == R.layout.item_grid) { + padding = (resources.displayMetrics.density * 2).toInt() + } else { + padding = 0 + } + recyclerView.setPadding(padding, padding, padding, padding) + } + + protected abstract fun loadSortOrder(): String + + protected abstract fun saveSortOrder(sortOrder: String) + + protected abstract fun loadGridSize(): Int + + protected abstract fun saveGridSize(gridColumns: Int) + + protected abstract fun loadGridSizeLand(): Int + + protected abstract fun saveGridSizeLand(gridColumns: Int) + + protected abstract fun saveUsePalette(usePalette: Boolean) + + protected abstract fun loadUsePalette(): Boolean + + protected abstract fun setUsePalette(usePalette: Boolean) + + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewFragment.java deleted file mode 100644 index 4f96cbe4..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewFragment.java +++ /dev/null @@ -1,162 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener; -import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.util.ViewUtil; - - -public abstract class AbsLibraryPagerRecyclerViewFragment extends - AbsLibraryPagerFragment implements OnOffsetChangedListener { - - public static final String TAG = AbsLibraryPagerRecyclerViewFragment.class.getSimpleName(); - @BindView(R.id.container) - ViewGroup container; - @BindView(R.id.recycler_view) - RecyclerView recyclerView; - @BindView(android.R.id.empty) - TextView empty; - - private Unbinder unbinder; - private A adapter; - private LM layoutManager; - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(getLayoutRes(), container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - getLibraryFragment().addOnAppBarOffsetChangedListener(this); - initLayoutManager(); - initAdapter(); - setUpRecyclerView(); - } - - private void setUpRecyclerView() { - if (recyclerView instanceof FastScrollRecyclerView) { - //noinspection ConstantConditions - ViewUtil.setUpFastScrollRecyclerViewColor(getActivity(), - ((FastScrollRecyclerView) recyclerView), ThemeStore.accentColor(getActivity())); - } - recyclerView.setLayoutManager(layoutManager); - recyclerView.setAdapter(adapter); - } - - @Override - public void onQueueChanged() { - super.onQueueChanged(); - checkForPadding(); - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - checkForPadding(); - } - - private void checkForPadding() { - int height = (MusicPlayerRemote.getPlayingQueue().isEmpty() ? getResources() - .getDimensionPixelSize(R.dimen.mini_player_height) : 0); - recyclerView.setPadding(0, 0, 0, height); - } - - protected void invalidateLayoutManager() { - initLayoutManager(); - recyclerView.setLayoutManager(layoutManager); - } - - protected void invalidateAdapter() { - initAdapter(); - checkIsEmpty(); - recyclerView.setAdapter(adapter); - } - - private void initAdapter() { - adapter = createAdapter(); - adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { - @Override - public void onChanged() { - super.onChanged(); - checkIsEmpty(); - checkForPadding(); - } - }); - } - - private void initLayoutManager() { - layoutManager = createLayoutManager(); - } - - protected A getAdapter() { - return adapter; - } - - protected LM getLayoutManager() { - return layoutManager; - } - - protected RecyclerView getRecyclerView() { - return recyclerView; - } - - public ViewGroup getContainer() { - return container; - } - - @Override - public void onOffsetChanged(AppBarLayout appBarLayout, int i) { - container.setPadding(container.getPaddingLeft(), container.getPaddingTop(), - container.getPaddingRight(), getLibraryFragment().getTotalAppBarScrollingRange() + i); - } - - private void checkIsEmpty() { - empty.setText(getEmptyMessage()); - empty.setVisibility(adapter == null || adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE); - } - - @StringRes - protected int getEmptyMessage() { - return R.string.empty; - } - - @LayoutRes - protected int getLayoutRes() { - return R.layout.fragment_main_activity_recycler_view; - } - - protected abstract LM createLayoutManager(); - - @NonNull - protected abstract A createAdapter(); - - @Override - public void onDestroyView() { - super.onDestroyView(); - getLibraryFragment().removeOnAppBarOffsetChangedListener(this); - unbinder.unbind(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewFragment.kt new file mode 100644 index 00000000..4e833d14 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsLibraryPagerRecyclerViewFragment.kt @@ -0,0 +1,116 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.annotation.NonNull +import androidx.annotation.StringRes +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.util.ViewUtil +import com.google.android.material.appbar.AppBarLayout +import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView +import kotlinx.android.synthetic.main.fragment_main_activity_recycler_view.* + +abstract class AbsLibraryPagerRecyclerViewFragment, LM : RecyclerView.LayoutManager> : AbsLibraryPagerFragment(), AppBarLayout.OnOffsetChangedListener { + + protected var adapter: A? = null + protected var layoutManager: LM? = null + + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val view = inflater.inflate(R.layout.fragment_main_activity_recycler_view, container, false); + return view + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + libraryFragment.addOnAppBarOffsetChangedListener(this) + initLayoutManager() + initAdapter() + setUpRecyclerView() + } + + private fun setUpRecyclerView() { + if (recyclerView is FastScrollRecyclerView) { + ViewUtil.setUpFastScrollRecyclerViewColor(activity, recyclerView as FastScrollRecyclerView, ThemeStore.accentColor(activity!!)) + } + recyclerView.layoutManager = layoutManager + recyclerView.adapter = adapter + } + + private fun initAdapter() { + adapter = createAdapter() + adapter!!.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { + override fun onChanged() { + super.onChanged() + checkIsEmpty() + checkForPadding() + } + }) + } + + protected open val emptyMessage: Int + @StringRes + get() = R.string.empty + + private fun checkIsEmpty() { + empty.setText(emptyMessage) + empty.visibility = if (adapter!!.itemCount == 0) View.VISIBLE else View.GONE + } + + private fun checkForPadding() { + val height = if (MusicPlayerRemote.playingQueue.isEmpty()) + resources.getDimensionPixelSize(R.dimen.mini_player_height) + else + 0 + recyclerView.setPadding(0, 0, 0, height) + } + + private fun initLayoutManager() { + layoutManager = createLayoutManager() + } + + protected abstract fun createLayoutManager(): LM + + @NonNull + protected abstract fun createAdapter(): A + + override fun onOffsetChanged(p0: AppBarLayout?, i: Int) { + container.setPadding(container.paddingLeft, container.paddingTop, + container.paddingRight, libraryFragment.totalAppBarScrollingRange + i) + } + + override fun onQueueChanged() { + super.onQueueChanged() + checkForPadding() + } + + override fun onServiceConnected() { + super.onServiceConnected() + checkForPadding() + } + + protected fun invalidateLayoutManager() { + initLayoutManager() + recyclerView.layoutManager = layoutManager + } + + protected fun invalidateAdapter() { + initAdapter() + checkIsEmpty() + recyclerView.adapter = adapter + } + + override fun onDestroyView() { + super.onDestroyView() + libraryFragment.removeOnAppBarOffsetChangedListener(this) + } + + fun recyclerView(): RecyclerView { + return recyclerView + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMainActivityFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMainActivityFragment.java deleted file mode 100644 index 56d0699a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMainActivityFragment.java +++ /dev/null @@ -1,58 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.os.Build; -import android.os.Bundle; -import android.view.View; - -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.VersionUtils; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.MainOptionsBottomSheetDialogFragment; -import code.name.monkey.retromusic.ui.activities.MainActivity; - - -public abstract class AbsMainActivityFragment extends AbsMusicServiceFragment { - - public MainActivity getMainActivity() { - return (MainActivity) getActivity(); - } - - @Override - public void onActivityCreated(Bundle savedInstanceState) { - super.onActivityCreated(savedInstanceState); - setHasOptionsMenu(true); - - getMainActivity().setNavigationbarColorAuto(); - getMainActivity().setLightNavigationBar(true); - getMainActivity().setTaskDescriptionColorAuto(); - getMainActivity().hideStatusBar(); - getMainActivity().setBottomBarVisibility(View.VISIBLE); - } - - private void setStatusbarColor(View view, int color) { - final View statusBar = view.findViewById(R.id.status_bar); - if (statusBar != null) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - statusBar.setBackgroundColor(color); - getMainActivity().setLightStatusbarAuto(color); - } else { - statusBar.setBackgroundColor(color); - } - } - } - - public void setStatusbarColorAuto(View view) { - // we don't want to use statusbar color because we are doing the color darkening on our own to support KitKat - //noinspection ConstantConditions - if (VersionUtils.hasMarshmallow()) { - setStatusbarColor(view, ThemeStore.primaryColor(getContext())); - } else { - setStatusbarColor(view, ColorUtil.darkenColor(ThemeStore.primaryColor(getContext()))); - } - } - - protected void showMainMenu() { - MainOptionsBottomSheetDialogFragment.newInstance().show(getChildFragmentManager(), "Main Menu"); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMainActivityFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMainActivityFragment.kt new file mode 100644 index 00000000..f0a231f4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMainActivityFragment.kt @@ -0,0 +1,56 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.os.Build +import android.os.Bundle +import android.view.View + +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.VersionUtils +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.MainOptionsBottomSheetDialogFragment +import code.name.monkey.retromusic.ui.activities.MainActivity + + +abstract class AbsMainActivityFragment : AbsMusicServiceFragment() { + + val mainActivity: MainActivity + get() = activity as MainActivity + + override fun onActivityCreated(savedInstanceState: Bundle?) { + super.onActivityCreated(savedInstanceState) + setHasOptionsMenu(true) + + mainActivity.setNavigationbarColorAuto() + mainActivity.setLightNavigationBar(true) + mainActivity.setTaskDescriptionColorAuto() + mainActivity.hideStatusBar() + mainActivity.setBottomBarVisibility(View.VISIBLE) + } + + private fun setStatusbarColor(view: View, color: Int) { + val statusBar = view.findViewById(R.id.status_bar) + if (statusBar != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + statusBar.setBackgroundColor(color) + mainActivity.setLightStatusbarAuto(color) + } else { + statusBar.setBackgroundColor(color) + } + } + } + + fun setStatusbarColorAuto(view: View) { + // we don't want to use statusbar color because we are doing the color darkening on our own to support KitKat + + if (VersionUtils.hasMarshmallow()) { + setStatusbarColor(view, ThemeStore.primaryColor(context!!)) + } else { + setStatusbarColor(view, ColorUtil.darkenColor(ThemeStore.primaryColor(context!!))) + } + } + + protected fun showMainMenu() { + MainOptionsBottomSheetDialogFragment.newInstance().show(childFragmentManager, "Main Menu") + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMusicServiceFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMusicServiceFragment.java deleted file mode 100644 index 71b9d11c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMusicServiceFragment.java +++ /dev/null @@ -1,93 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.content.Context; -import android.os.Bundle; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import code.name.monkey.retromusic.interfaces.MusicServiceEventListener; -import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity; - -/** - * Created by hemanths on 18/08/17. - */ - -public class AbsMusicServiceFragment extends Fragment implements MusicServiceEventListener { - - private AbsMusicServiceActivity activity; - - @Nullable - public AbsMusicServiceActivity getPlayerActivity() { - return activity; - } - - @Override - public void onAttach(Context context) { - super.onAttach(context); - try { - activity = (AbsMusicServiceActivity) context; - } catch (ClassCastException e) { - throw new RuntimeException(context.getClass().getSimpleName() + " must be an instance of " + AbsMusicServiceActivity.class.getSimpleName()); - } - } - - @Override - public void onDetach() { - super.onDetach(); - activity = null; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - activity.addMusicServiceEventListener(this); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - activity.removeMusicServiceEventListener(this); - } - - @Override - public void onPlayingMetaChanged() { - - } - - @Override - public void onServiceConnected() { - - } - - @Override - public void onServiceDisconnected() { - - } - - @Override - public void onQueueChanged() { - - } - - @Override - public void onPlayStateChanged() { - - } - - @Override - public void onRepeatModeChanged() { - - } - - @Override - public void onShuffleModeChanged() { - - } - - @Override - public void onMediaStoreChanged() { - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMusicServiceFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMusicServiceFragment.kt new file mode 100644 index 00000000..48778ec9 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsMusicServiceFragment.kt @@ -0,0 +1,75 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.content.Context +import android.os.Bundle +import android.view.View +import androidx.fragment.app.Fragment +import code.name.monkey.retromusic.interfaces.MusicServiceEventListener +import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity + +/** + * Created by hemanths on 18/08/17. + */ + +open class AbsMusicServiceFragment : Fragment(), MusicServiceEventListener { + + var playerActivity: AbsMusicServiceActivity? = null + private set + + override fun onAttach(context: Context?) { + super.onAttach(context) + try { + playerActivity = context as AbsMusicServiceActivity? + } catch (e: ClassCastException) { + throw RuntimeException(context!!.javaClass.simpleName + " must be an instance of " + AbsMusicServiceActivity::class.java.simpleName) + } + + } + + override fun onDetach() { + super.onDetach() + playerActivity = null + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + playerActivity!!.addMusicServiceEventListener(this) + } + + override fun onDestroyView() { + super.onDestroyView() + playerActivity!!.removeMusicServiceEventListener(this) + } + + override fun onPlayingMetaChanged() { + + } + + override fun onServiceConnected() { + + } + + override fun onServiceDisconnected() { + + } + + override fun onQueueChanged() { + + } + + override fun onPlayStateChanged() { + + } + + override fun onRepeatModeChanged() { + + } + + override fun onShuffleModeChanged() { + + } + + override fun onMediaStoreChanged() { + + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerControlsFragment.java deleted file mode 100644 index 8948f591..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerControlsFragment.java +++ /dev/null @@ -1,52 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.view.View; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; - -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; - -/** - * Created by hemanths on 24/09/17. - */ - -public abstract class AbsPlayerControlsFragment extends AbsMusicServiceFragment - implements MusicProgressViewUpdateHelper.Callback { - - protected abstract void show(); - - protected abstract void hide(); - - protected abstract void updateShuffleState(); - - protected abstract void updateRepeatState(); - - protected abstract void setUpProgressSlider(); - - public abstract void setDark(int color); - - public void showBouceAnimation(View view) { - view.clearAnimation(); - - view.setScaleX(0.9f); - view.setScaleY(0.9f); - view.setVisibility(View.VISIBLE); - view.setPivotX(view.getWidth() / 2); - view.setPivotY(view.getHeight() / 2); - - view.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> view.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerControlsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerControlsFragment.kt new file mode 100644 index 00000000..efe3631c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerControlsFragment.kt @@ -0,0 +1,80 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.os.Bundle +import android.view.View +import android.view.animation.AccelerateInterpolator +import android.view.animation.DecelerateInterpolator +import android.widget.ImageButton +import android.widget.TextView +import androidx.appcompat.widget.AppCompatSeekBar +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper + +/** + * Created by hemanths on 24/09/17. + */ + +abstract class AbsPlayerControlsFragment : AbsMusicServiceFragment(), MusicProgressViewUpdateHelper.Callback { + + protected abstract fun show() + + protected abstract fun hide() + + protected abstract fun updateShuffleState() + + protected abstract fun updateRepeatState() + + protected abstract fun setUpProgressSlider() + + abstract fun setDark(color: Int) + + fun showBouceAnimation(view: View) { + view.clearAnimation() + + view.scaleX = 0.9f + view.scaleY = 0.9f + view.visibility = View.VISIBLE + view.pivotX = (view.width / 2).toFloat() + view.pivotY = (view.height / 2).toFloat() + + view.animate() + .setDuration(200) + .setInterpolator(DecelerateInterpolator()) + .scaleX(1.1f) + .scaleY(1.1f) + .withEndAction { + view.animate() + .setDuration(200) + .setInterpolator(AccelerateInterpolator()) + .scaleX(1f) + .scaleY(1f) + .alpha(1f) + .start() + } + .start() + } + + + var prevButton: ImageButton? = null + var nextButton: ImageButton? = null + var repeatButton: ImageButton? = null + var shuffleButton: ImageButton? = null + var progressSlider: AppCompatSeekBar? = null + var songTotalTime: TextView? = null + var songCurrentProgress: TextView? = null + var volumeContainer: View? = null + var playPauseFab: ImageButton? = null + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + playPauseFab = view.findViewById(R.id.player_play_pause_button) + prevButton = view.findViewById(R.id.player_prev_button) + nextButton = view.findViewById(R.id.player_next_button) + repeatButton = view.findViewById(R.id.player_repeat_button) + shuffleButton = view.findViewById(R.id.player_shuffle_button) + progressSlider = view.findViewById(R.id.player_progress_slider) + songTotalTime = view.findViewById(R.id.player_song_total_time) + songCurrentProgress = view.findViewById(R.id.player_song_current_progress) + volumeContainer = view.findViewById(R.id.volume_fragment_container) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerFragment.java deleted file mode 100644 index 6ffd741a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerFragment.java +++ /dev/null @@ -1,231 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.base; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.content.ContentUris; -import android.content.Context; -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.media.MediaMetadataRetriever; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Bundle; -import android.provider.MediaStore; -import android.view.MenuItem; -import android.view.View; -import android.widget.Toast; - -import androidx.annotation.NonNull; -import androidx.appcompat.widget.Toolbar; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.AddToPlaylistDialog; -import code.name.monkey.retromusic.dialogs.CreatePlaylistDialog; -import code.name.monkey.retromusic.dialogs.DeleteSongsDialog; -import code.name.monkey.retromusic.dialogs.SleepTimerDialog; -import code.name.monkey.retromusic.dialogs.SongDetailDialog; -import code.name.monkey.retromusic.dialogs.SongShareDialog; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.interfaces.PaletteColorHolder; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.activities.tageditor.AbsTagEditorActivity; -import code.name.monkey.retromusic.ui.activities.tageditor.SongTagEditorActivity; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.views.FitSystemWindowsLayout; - -public abstract class AbsPlayerFragment extends AbsMusicServiceFragment implements Toolbar.OnMenuItemClickListener, PaletteColorHolder { - public static final String TAG = AbsPlayerFragment.class.getSimpleName(); - private Callbacks callbacks; - private AsyncTask updateIsFavoriteTask; - - - @Override - public void onAttach(Context context) { - super.onAttach(context); - try { - callbacks = (Callbacks) context; - } catch (ClassCastException e) { - throw new RuntimeException(context.getClass().getSimpleName() + " must implement " + Callbacks.class.getSimpleName()); - } - } - - @Override - public void onDetach() { - super.onDetach(); - callbacks = null; - } - - @SuppressWarnings("ConstantConditions") - @Override - public boolean onMenuItemClick(MenuItem item) { - final Song song = MusicPlayerRemote.getCurrentSong(); - switch (item.getItemId()) { - case R.id.action_toggle_favorite: - toggleFavorite(song); - return true; - case R.id.action_share: - if (getFragmentManager() != null) { - SongShareDialog.create(song).show(getFragmentManager(), "SHARE_SONG"); - } - return true; - case R.id.action_delete_from_device: - DeleteSongsDialog.create(song) - .show(getActivity().getSupportFragmentManager(), "DELETE_SONGS"); - return true; - case R.id.action_add_to_playlist: - if (getFragmentManager() != null) { - AddToPlaylistDialog.create(song).show(getFragmentManager(), "ADD_PLAYLIST"); - } - return true; - case R.id.action_clear_playing_queue: - MusicPlayerRemote.clearQueue(); - return true; - case R.id.action_save_playing_queue: - CreatePlaylistDialog.create(MusicPlayerRemote.getPlayingQueue()) - .show(getActivity().getSupportFragmentManager(), "ADD_TO_PLAYLIST"); - return true; - case R.id.action_tag_editor: - Intent intent = new Intent(getActivity(), SongTagEditorActivity.class); - intent.putExtra(AbsTagEditorActivity.EXTRA_ID, song.id); - startActivity(intent); - return true; - case R.id.action_details: - if (getFragmentManager() != null) { - SongDetailDialog.create(song).show(getFragmentManager(), "SONG_DETAIL"); - } - return true; - case R.id.action_go_to_album: - NavigationUtil.goToAlbum(getActivity(), song.albumId); - return true; - case R.id.action_go_to_artist: - NavigationUtil.goToArtist(getActivity(), song.artistId); - return true; - case R.id.now_playing: - NavigationUtil.goToPlayingQueue(getActivity()); - return true; - case R.id.action_show_lyrics: - NavigationUtil.goToLyrics(getActivity()); - return true; - case R.id.action_equalizer: - NavigationUtil.openEqualizer(getActivity()); - return true; - case R.id.action_sleep_timer: - new SleepTimerDialog().show(getFragmentManager(), TAG); - return true; - case R.id.action_set_as_ringtone: - MusicUtil.setRingtone(getActivity(), song.id); - return true; - case R.id.action_settings: - NavigationUtil.goToSettings(getActivity()); - return true; - case R.id.action_go_to_genre: - MediaMetadataRetriever retriever = new MediaMetadataRetriever(); - Uri trackUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, song.id); - retriever.setDataSource(getActivity(), trackUri); - String genre = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE); - if (genre == null) { - genre = "Not Specified"; - } - Toast.makeText(getContext(), genre, Toast.LENGTH_SHORT).show(); - return true; - } - return false; - } - - protected void toggleFavorite(Song song) { - MusicUtil.toggleFavorite(getActivity(), song); - } - - public abstract void onShow(); - - public abstract void onHide(); - - public abstract boolean onBackPressed(); - - public abstract Toolbar getToolbar(); - - public abstract int toolbarIconColor(); - - @Override - public void onServiceConnected() { - updateIsFavorite(); - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - } - - @Override - public void onDestroyView() { - if (updateIsFavoriteTask != null && !updateIsFavoriteTask.isCancelled()) { - updateIsFavoriteTask.cancel(true); - } - super.onDestroyView(); - } - - @SuppressLint("StaticFieldLeak") - public void updateIsFavorite() { - if (updateIsFavoriteTask != null) { - updateIsFavoriteTask.cancel(false); - } - updateIsFavoriteTask = new AsyncTask() { - @Override - protected Boolean doInBackground(Song... params) { - Activity activity = getActivity(); - if (activity != null) { - return MusicUtil.isFavorite(getActivity(), params[0]); - } else { - cancel(false); - return null; - } - } - - @Override - protected void onPostExecute(Boolean isFavorite) { - Activity activity = getActivity(); - if (activity != null) { - int res = isFavorite ? R.drawable.ic_favorite_white_24dp - : R.drawable.ic_favorite_border_white_24dp; - Drawable drawable = RetroUtil.getTintedVectorDrawable(activity, res, toolbarIconColor()); - getToolbar().getMenu().findItem(R.id.action_toggle_favorite) - .setIcon(drawable) - .setTitle(isFavorite ? getString(R.string.action_remove_from_favorites) : getString(R.string.action_add_to_favorites)); - } - } - }.execute(MusicPlayerRemote.getCurrentSong()); - } - - public Callbacks getCallbacks() { - return callbacks; - } - - - @SuppressWarnings("ConstantConditions") - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - view.setBackgroundColor(ThemeStore.primaryColor(getActivity())); - - if (PreferenceUtil.getInstance().getFullScreenMode()) { - if (view.findViewById(R.id.status_bar) != null) - view.findViewById(R.id.status_bar).setVisibility(View.GONE); - } - } - - public void setSafeArea(View safeArea) { - FitSystemWindowsLayout layout = safeArea.findViewById(R.id.safeArea); - if (layout != null) { - layout.setFit(!PreferenceUtil.getInstance().getFullScreenMode()); - } - } - - public interface Callbacks { - - void onPaletteColorChanged(); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerFragment.kt new file mode 100644 index 00000000..4eff06f4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/base/AbsPlayerFragment.kt @@ -0,0 +1,227 @@ +package code.name.monkey.retromusic.ui.fragments.base + +import android.annotation.SuppressLint +import android.content.ContentUris +import android.content.Context +import android.content.Intent +import android.media.MediaMetadataRetriever +import android.os.AsyncTask +import android.os.Bundle +import android.provider.MediaStore +import android.view.MenuItem +import android.view.View +import android.widget.Toast +import androidx.appcompat.widget.Toolbar +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.* +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.interfaces.PaletteColorHolder +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.activities.tageditor.AbsTagEditorActivity +import code.name.monkey.retromusic.ui.activities.tageditor.SongTagEditorActivity +import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import code.name.monkey.retromusic.views.FitSystemWindowsLayout + +abstract class AbsPlayerFragment : AbsMusicServiceFragment(), Toolbar.OnMenuItemClickListener, PaletteColorHolder, PlayerAlbumCoverFragment.Callbacks { + var callbacks: Callbacks? = null + private set + private var updateIsFavoriteTask: AsyncTask<*, *, *>? = null + + protected var toolbar: Toolbar? = null + + + override fun onAttach(context: Context?) { + super.onAttach(context) + try { + callbacks = context as Callbacks? + } catch (e: ClassCastException) { + throw RuntimeException(context!!.javaClass.simpleName + " must implement " + Callbacks::class.java.simpleName) + } + + } + + override fun onDetach() { + super.onDetach() + callbacks = null + } + + override fun onMenuItemClick(item: MenuItem): Boolean { + val song = MusicPlayerRemote.currentSong + when (item.itemId) { + R.id.action_toggle_favorite -> { + toggleFavorite(song) + return true + } + R.id.action_share -> { + if (fragmentManager != null) { + SongShareDialog.create(song).show(fragmentManager!!, "SHARE_SONG") + } + return true + } + R.id.action_delete_from_device -> { + DeleteSongsDialog.create(song) + .show(activity!!.supportFragmentManager, "DELETE_SONGS") + return true + } + R.id.action_add_to_playlist -> { + if (fragmentManager != null) { + AddToPlaylistDialog.create(song).show(fragmentManager!!, "ADD_PLAYLIST") + } + return true + } + R.id.action_clear_playing_queue -> { + MusicPlayerRemote.clearQueue() + return true + } + R.id.action_save_playing_queue -> { + CreatePlaylistDialog.create(MusicPlayerRemote.playingQueue) + .show(activity!!.supportFragmentManager, "ADD_TO_PLAYLIST") + return true + } + R.id.action_tag_editor -> { + val intent = Intent(activity, SongTagEditorActivity::class.java) + intent.putExtra(AbsTagEditorActivity.EXTRA_ID, song.id) + startActivity(intent) + return true + } + R.id.action_details -> { + if (fragmentManager != null) { + SongDetailDialog.create(song).show(fragmentManager!!, "SONG_DETAIL") + } + return true + } + R.id.action_go_to_album -> { + NavigationUtil.goToAlbum(activity!!, song.albumId) + return true + } + R.id.action_go_to_artist -> { + NavigationUtil.goToArtist(activity!!, song.artistId) + return true + } + R.id.now_playing -> { + NavigationUtil.goToPlayingQueue(activity!!) + return true + } + R.id.action_show_lyrics -> { + NavigationUtil.goToLyrics(activity!!) + return true + } + R.id.action_equalizer -> { + NavigationUtil.openEqualizer(activity!!) + return true + } + R.id.action_sleep_timer -> { + SleepTimerDialog().show(fragmentManager!!, TAG) + return true + } + R.id.action_set_as_ringtone -> { + MusicUtil.setRingtone(activity!!, song.id) + return true + } + R.id.action_settings -> { + NavigationUtil.goToSettings(activity!!) + return true + } + R.id.action_go_to_genre -> { + val retriever = MediaMetadataRetriever() + val trackUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, song.id.toLong()) + retriever.setDataSource(activity, trackUri) + var genre: String? = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE) + if (genre == null) { + genre = "Not Specified" + } + Toast.makeText(context, genre, Toast.LENGTH_SHORT).show() + return true + } + } + return false + } + + protected open fun toggleFavorite(song: Song) { + MusicUtil.toggleFavorite(activity!!, song) + } + + abstract fun onShow() + + abstract fun onHide() + + abstract fun onBackPressed(): Boolean + + abstract fun toolbarIconColor(): Int + + override fun onServiceConnected() { + updateIsFavorite() + } + + override fun onPlayingMetaChanged() { + updateIsFavorite() + } + + override fun onDestroyView() { + if (updateIsFavoriteTask != null && !updateIsFavoriteTask!!.isCancelled) { + updateIsFavoriteTask!!.cancel(true) + } + super.onDestroyView() + } + + @SuppressLint("StaticFieldLeak") + fun updateIsFavorite() { + if (updateIsFavoriteTask != null) { + updateIsFavoriteTask!!.cancel(false) + } + updateIsFavoriteTask = object : AsyncTask() { + override fun doInBackground(vararg params: Song): Boolean? { + val activity = activity + if (activity != null) { + return MusicUtil.isFavorite(getActivity()!!, params[0]) + } else { + cancel(false) + return null + } + } + + override fun onPostExecute(isFavorite: Boolean?) { + val activity = activity + if (activity != null) { + val res = if (isFavorite!!) + R.drawable.ic_favorite_white_24dp + else + R.drawable.ic_favorite_border_white_24dp + val drawable = RetroUtil.getTintedVectorDrawable(activity, res, toolbarIconColor()) + //toolbar!!.menu.findItem(R.id.action_toggle_favorite).setIcon(drawable).title = if (isFavorite) getString(R.string.action_remove_from_favorites) else getString(R.string.action_add_to_favorites) + } + } + }.execute(MusicPlayerRemote.currentSong) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + view.setBackgroundColor(ThemeStore.primaryColor(activity!!)) + if (PreferenceUtil.getInstance().fullScreenMode) { + if (view.findViewById(R.id.status_bar) != null) + view.findViewById(R.id.status_bar).visibility = View.GONE + } + } + + fun setSafeArea(safeArea: View) { + val layout = safeArea.findViewById(R.id.safeArea) + if (layout != null) { + layout.isFit = !PreferenceUtil.getInstance().fullScreenMode + } + } + + interface Callbacks { + + fun onPaletteColorChanged() + } + + companion object { + val TAG: String = AbsPlayerFragment::class.java.simpleName + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/AlbumsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/AlbumsFragment.java deleted file mode 100644 index eb70040a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/AlbumsFragment.java +++ /dev/null @@ -1,175 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity; - -import android.os.Bundle; - -import java.util.ArrayList; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.GridLayoutManager; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.mvp.contract.AlbumContract; -import code.name.monkey.retromusic.mvp.presenter.AlbumPresenter; -import code.name.monkey.retromusic.ui.adapter.album.AlbumAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class AlbumsFragment extends AbsLibraryPagerRecyclerViewCustomGridSizeFragment implements AlbumContract.AlbumView { - - public static final String TAG = AlbumsFragment.class.getSimpleName(); - - private AlbumPresenter presenter; - - public static AlbumsFragment newInstance() { - Bundle args = new Bundle(); - AlbumsFragment fragment = new AlbumsFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - protected GridLayoutManager createLayoutManager() { - return new GridLayoutManager(getActivity(), getGridSize()); - } - - @NonNull - @Override - protected AlbumAdapter createAdapter() { - int itemLayoutRes = getItemLayoutRes(); - notifyLayoutResChanged(itemLayoutRes); - if (itemLayoutRes != R.layout.item_list) { - //noinspection ConstantConditions - itemLayoutRes = PreferenceUtil.getInstance().getAlbumGridStyle(getContext()); - } - ArrayList dataSet = getAdapter() == null ? new ArrayList<>() : getAdapter().getDataSet(); - return new AlbumAdapter(getLibraryFragment().getMainActivity(), dataSet, itemLayoutRes, loadUsePalette(), getLibraryFragment()); - } - - @Override - protected int getEmptyMessage() { - return R.string.no_albums; - } - - @Override - public boolean loadUsePalette() { - //noinspection ConstantConditions - return PreferenceUtil.getInstance().albumColoredFooters(); - } - - @Override - protected void setUsePalette(boolean usePalette) { - getAdapter().usePalette(usePalette); - } - - @Override - protected void setGridSize(int gridSize) { - getLayoutManager().setSpanCount(gridSize); - getAdapter().notifyDataSetChanged(); - } - - @Override - protected void setSortOrder(String sortOrder) { - presenter.loadAlbums(); - } - - @Override - protected String loadSortOrder() { - //noinspection ConstantConditions - return PreferenceUtil.getInstance().getAlbumSortOrder(); - } - - @Override - protected void saveSortOrder(String sortOrder) { - //noinspection ConstantConditions - PreferenceUtil.getInstance().setAlbumSortOrder(sortOrder); - } - - @Override - protected int loadGridSize() { - //noinspection ConstantConditions - return PreferenceUtil.getInstance().getAlbumGridSize(getActivity()); - } - - @Override - protected void saveGridSize(int gridSize) { - //noinspection ConstantConditions - PreferenceUtil.getInstance().setAlbumGridSize(gridSize); - } - - @Override - protected int loadGridSizeLand() { - //noinspection ConstantConditions - return PreferenceUtil.getInstance().getAlbumGridSizeLand(getActivity()); - } - - @Override - protected void saveGridSizeLand(int gridSize) { - //noinspection ConstantConditions - PreferenceUtil.getInstance().setAlbumGridSizeLand(gridSize); - } - - @Override - protected void saveUsePalette(boolean usePalette) { - //noinspection ConstantConditions - PreferenceUtil.getInstance().setAlbumColoredFooters(usePalette); - } - - @Override - public void onMediaStoreChanged() { - presenter.loadAlbums(); - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - presenter = new AlbumPresenter(this); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (menuVisible) { - //noinspection ConstantConditions - getLibraryFragment().setTitle( - PreferenceUtil.getInstance().tabTitles() ? R.string.library - : R.string.albums); - } - } - - @Override - public void onResume() { - super.onResume(); - //noinspection ConstantConditions - getLibraryFragment().setTitle( - PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.albums); - if (getAdapter().getDataSet().isEmpty()) { - presenter.subscribe(); - } - } - - @Override - public void onDestroy() { - super.onDestroy(); - presenter.unsubscribe(); - } - - @Override - public void loading() { - } - - @Override - public void showEmptyView() { - getAdapter().swapDataSet(new ArrayList<>()); - } - - @Override - public void completed() { - } - - @Override - public void showData(ArrayList albums) { - getAdapter().swapDataSet(albums); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/AlbumsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/AlbumsFragment.kt new file mode 100644 index 00000000..d8695449 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/AlbumsFragment.kt @@ -0,0 +1,149 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity + +import android.os.Bundle +import androidx.recyclerview.widget.GridLayoutManager +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.mvp.contract.AlbumContract +import code.name.monkey.retromusic.mvp.presenter.AlbumPresenter +import code.name.monkey.retromusic.ui.adapter.album.AlbumAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment +import code.name.monkey.retromusic.util.PreferenceUtil + +open class AlbumsFragment : AbsLibraryPagerRecyclerViewCustomGridSizeFragment(), AlbumContract.AlbumView { + + private var presenter: AlbumPresenter? = null + + + override val emptyMessage: Int + get() = R.string.no_albums + + override fun createLayoutManager(): GridLayoutManager { + return GridLayoutManager(activity, getGridSize()) + } + + override fun createAdapter(): AlbumAdapter { + var itemLayoutRes = itemLayoutRes + notifyLayoutResChanged(itemLayoutRes) + if (itemLayoutRes != R.layout.item_list) { + + itemLayoutRes = PreferenceUtil.getInstance().getAlbumGridStyle(context!!) + } + val dataSet = if (adapter == null) ArrayList() else adapter!!.dataSet + return AlbumAdapter(libraryFragment.mainActivity, dataSet, itemLayoutRes, loadUsePalette(), libraryFragment) + } + + public override fun loadUsePalette(): Boolean { + + return PreferenceUtil.getInstance().albumColoredFooters() + } + + override fun setUsePalette(usePalette: Boolean) { + adapter!!.usePalette(usePalette) + } + + override fun setGridSize(gridSize: Int) { + layoutManager!!.spanCount = gridSize + adapter!!.notifyDataSetChanged() + } + + override fun setSortOrder(sortOrder: String) { + presenter!!.loadAlbums() + } + + override fun loadSortOrder(): String { + + return PreferenceUtil.getInstance().albumSortOrder + } + + override fun saveSortOrder(sortOrder: String) { + + PreferenceUtil.getInstance().albumSortOrder = sortOrder + } + + override fun loadGridSize(): Int { + + return PreferenceUtil.getInstance().getAlbumGridSize(activity!!) + } + + override fun saveGridSize(gridColumns: Int) { + + PreferenceUtil.getInstance().setAlbumGridSize(gridColumns) + } + + override fun loadGridSizeLand(): Int { + + return PreferenceUtil.getInstance().getAlbumGridSizeLand(activity!!) + } + + override fun saveGridSizeLand(gridColumns: Int) { + + PreferenceUtil.getInstance().setAlbumGridSizeLand(gridColumns) + } + + override fun saveUsePalette(usePalette: Boolean) { + + PreferenceUtil.getInstance().setAlbumColoredFooters(usePalette) + } + + override fun onMediaStoreChanged() { + presenter!!.loadAlbums() + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + presenter = AlbumPresenter(this) + } + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + if (menuVisible) { + + libraryFragment.setTitle( + if (PreferenceUtil.getInstance().tabTitles()) + R.string.library + else + R.string.albums) + } + } + + override fun onResume() { + super.onResume() + + libraryFragment.setTitle( + if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.albums) + if (adapter!!.dataSet.isEmpty()) { + presenter!!.subscribe() + } + } + + override fun onDestroy() { + super.onDestroy() + presenter!!.unsubscribe() + } + + override fun loading() {} + + override fun showEmptyView() { + adapter!!.swapDataSet(ArrayList()) + } + + override fun completed() {} + + override fun showData(albums: ArrayList) { + adapter!!.swapDataSet(albums) + } + + companion object { + + val TAG = AlbumsFragment::class.java.simpleName + + fun newInstance(): AlbumsFragment { + val args = Bundle() + val fragment = AlbumsFragment() + fragment.arguments = args + return fragment + } + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/ArtistsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/ArtistsFragment.java deleted file mode 100644 index 5ef3f6b9..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/ArtistsFragment.java +++ /dev/null @@ -1,173 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.GridLayoutManager; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.mvp.contract.ArtistContract; -import code.name.monkey.retromusic.mvp.presenter.ArtistPresenter; -import code.name.monkey.retromusic.ui.adapter.artist.ArtistAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class ArtistsFragment extends - AbsLibraryPagerRecyclerViewCustomGridSizeFragment implements - ArtistContract.ArtistView { - - public static final String TAG = ArtistsFragment.class.getSimpleName(); - private ArtistPresenter presenter; - - public static ArtistsFragment newInstance() { - - Bundle args = new Bundle(); - - ArtistsFragment fragment = new ArtistsFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - presenter = new ArtistPresenter(this); - } - - @NonNull - @Override - protected GridLayoutManager createLayoutManager() { - return new GridLayoutManager(getActivity(), getGridSize()); - } - - @NonNull - @Override - protected ArtistAdapter createAdapter() { - int itemLayoutRes = getItemLayoutRes(); - notifyLayoutResChanged(itemLayoutRes); - if (itemLayoutRes != R.layout.item_list) { - itemLayoutRes = PreferenceUtil.getInstance().getArtistGridStyle(getContext()); - } - ArrayList dataSet = - getAdapter() == null ? new ArrayList<>() : getAdapter().getDataSet(); - return new ArtistAdapter(getLibraryFragment().getMainActivity(), dataSet, itemLayoutRes, - loadUsePalette(), getLibraryFragment()); - } - - @Override - protected int getEmptyMessage() { - return R.string.no_artists; - } - - @Override - public void onMediaStoreChanged() { - presenter.loadArtists(); - } - - @Override - protected int loadGridSize() { - return PreferenceUtil.getInstance().getArtistGridSize(getActivity()); - } - - @Override - protected void saveGridSize(int gridSize) { - PreferenceUtil.getInstance().setArtistGridSize(gridSize); - } - - @Override - protected int loadGridSizeLand() { - return PreferenceUtil.getInstance().getArtistGridSizeLand(getActivity()); - } - - @Override - protected void saveGridSizeLand(int gridSize) { - PreferenceUtil.getInstance().setArtistGridSizeLand(gridSize); - } - - @Override - protected void saveUsePalette(boolean usePalette) { - PreferenceUtil.getInstance().setArtistColoredFooters(usePalette); - } - - @Override - public boolean loadUsePalette() { - return PreferenceUtil.getInstance().artistColoredFooters(); - } - - @Override - protected void setUsePalette(boolean usePalette) { - getAdapter().usePalette(usePalette); - } - - @Override - protected void setGridSize(int gridSize) { - getLayoutManager().setSpanCount(gridSize); - getAdapter().notifyDataSetChanged(); - } - - - @Override - protected String loadSortOrder() { - return PreferenceUtil.getInstance().getArtistSortOrder(); - } - - @Override - protected void saveSortOrder(String sortOrder) { - PreferenceUtil.getInstance().setArtistSortOrder(sortOrder); - } - - @Override - protected void setSortOrder(String sortOrder) { - presenter.loadArtists(); - } - - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (menuVisible) { - getLibraryFragment().setTitle( - PreferenceUtil.getInstance().tabTitles() ? R.string.library - : R.string.artists); - } - } - - @Override - public void onResume() { - super.onResume(); - getLibraryFragment().setTitle( - PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.artists); - if (getAdapter().getDataSet().isEmpty()) { - presenter.subscribe(); - } - } - - @Override - public void onDestroy() { - super.onDestroy(); - presenter.unsubscribe(); - } - - @Override - public void loading() { - } - - @Override - public void showEmptyView() { - getAdapter().swapDataSet(new ArrayList<>()); - } - - @Override - public void completed() { - - } - - @Override - public void showData(ArrayList artists) { - getAdapter().swapDataSet(artists); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/ArtistsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/ArtistsFragment.kt new file mode 100644 index 00000000..cb67e5ba --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/ArtistsFragment.kt @@ -0,0 +1,143 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity + +import android.os.Bundle +import androidx.recyclerview.widget.GridLayoutManager +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.mvp.contract.ArtistContract +import code.name.monkey.retromusic.mvp.presenter.ArtistPresenter +import code.name.monkey.retromusic.ui.adapter.artist.ArtistAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment +import code.name.monkey.retromusic.util.PreferenceUtil +import java.util.* + +class ArtistsFragment : AbsLibraryPagerRecyclerViewCustomGridSizeFragment(), ArtistContract.ArtistView { + private var presenter: ArtistPresenter? = null + + override val emptyMessage: Int + get() = R.string.no_artists + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + presenter = ArtistPresenter(this) + } + + override fun createLayoutManager(): GridLayoutManager { + return GridLayoutManager(activity, getGridSize()) + } + + override fun createAdapter(): ArtistAdapter { + var itemLayoutRes = itemLayoutRes + notifyLayoutResChanged(itemLayoutRes) + if (itemLayoutRes != R.layout.item_list) { + itemLayoutRes = PreferenceUtil.getInstance().getArtistGridStyle(context!!) + } + val dataSet = if (adapter == null) ArrayList() else adapter!!.dataSet + return ArtistAdapter(libraryFragment.mainActivity, dataSet, itemLayoutRes, loadUsePalette(), libraryFragment) + } + + override fun onMediaStoreChanged() { + presenter!!.loadArtists() + } + + override fun loadGridSize(): Int { + return PreferenceUtil.getInstance().getArtistGridSize(activity!!) + } + + override fun saveGridSize(gridColumns: Int) { + PreferenceUtil.getInstance().setArtistGridSize(gridColumns) + } + + override fun loadGridSizeLand(): Int { + return PreferenceUtil.getInstance().getArtistGridSizeLand(activity!!) + } + + override fun saveGridSizeLand(gridColumns: Int) { + PreferenceUtil.getInstance().setArtistGridSizeLand(gridColumns) + } + + override fun saveUsePalette(usePalette: Boolean) { + PreferenceUtil.getInstance().setArtistColoredFooters(usePalette) + } + + public override fun loadUsePalette(): Boolean { + return PreferenceUtil.getInstance().artistColoredFooters() + } + + override fun setUsePalette(usePalette: Boolean) { + adapter!!.usePalette(usePalette) + } + + override fun setGridSize(gridSize: Int) { + layoutManager!!.spanCount = gridSize + adapter!!.notifyDataSetChanged() + } + + + override fun loadSortOrder(): String { + return PreferenceUtil.getInstance().artistSortOrder + } + + override fun saveSortOrder(sortOrder: String) { + PreferenceUtil.getInstance().artistSortOrder = sortOrder + } + + override fun setSortOrder(sortOrder: String) { + presenter!!.loadArtists() + } + + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + if (menuVisible) { + libraryFragment.setTitle( + if (PreferenceUtil.getInstance().tabTitles()) + R.string.library + else + R.string.artists) + } + } + + override fun onResume() { + super.onResume() + libraryFragment.setTitle( + if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.artists) + if (adapter!!.dataSet.isEmpty()) { + presenter!!.subscribe() + } + } + + override fun onDestroy() { + super.onDestroy() + presenter!!.unsubscribe() + } + + override fun loading() {} + + override fun showEmptyView() { + adapter!!.swapDataSet(ArrayList()) + } + + override fun completed() { + + } + + override fun showData(artists: ArrayList) { + adapter!!.swapDataSet(artists) + } + + companion object { + + val TAG = ArtistsFragment::class.java.simpleName + + fun newInstance(): ArtistsFragment { + + val args = Bundle() + + val fragment = ArtistsFragment() + fragment.arguments = args + return fragment + } + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/GenreFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/GenreFragment.java deleted file mode 100644 index 0ac8a9a1..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/GenreFragment.java +++ /dev/null @@ -1,110 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import android.view.Menu; -import android.view.MenuInflater; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.mvp.contract.GenreContract; -import code.name.monkey.retromusic.mvp.presenter.GenrePresenter; -import code.name.monkey.retromusic.ui.adapter.GenreAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class GenreFragment extends - AbsLibraryPagerRecyclerViewFragment implements - GenreContract.GenreView { - - private GenrePresenter mPresenter; - - public static GenreFragment newInstance() { - Bundle args = new Bundle(); - GenreFragment fragment = new GenreFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - mPresenter = new GenrePresenter(this); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (menuVisible) { - getLibraryFragment().setTitle(PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.genres); - } - } - - @Override - public void onResume() { - super.onResume(); - getLibraryFragment().setTitle(PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.genres); - if (getAdapter().getDataSet().isEmpty()) { - mPresenter.subscribe(); - } - } - - - @Override - public void onDestroy() { - super.onDestroy(); - mPresenter.unsubscribe(); - } - - @NonNull - @Override - protected LinearLayoutManager createLayoutManager() { - return new LinearLayoutManager(getActivity()); - } - - @NonNull - @Override - protected GenreAdapter createAdapter() { - ArrayList dataSet = getAdapter() == null ? new ArrayList() : getAdapter().getDataSet(); - return new GenreAdapter(getLibraryFragment().getMainActivity(), dataSet, R.layout.item_list); - } - - @Override - public void loading() { - - } - - @Override - public void showData(ArrayList songs) { - getAdapter().swapDataSet(songs); - } - - @Override - public void showEmptyView() { - getAdapter().swapDataSet(new ArrayList()); - } - - @Override - public void completed() { - - } - - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - menu.removeItem(R.id.action_sort_order); - menu.removeItem(R.id.action_grid_size); - menu.removeItem(R.id.action_new_playlist); - } - - @Override - protected int getEmptyMessage() { - return R.string.no_genres; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/GenreFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/GenreFragment.kt new file mode 100644 index 00000000..84054572 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/GenreFragment.kt @@ -0,0 +1,94 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity + +import android.os.Bundle +import androidx.recyclerview.widget.LinearLayoutManager +import android.view.Menu +import android.view.MenuInflater + +import java.util.ArrayList + +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Genre +import code.name.monkey.retromusic.mvp.contract.GenreContract +import code.name.monkey.retromusic.mvp.presenter.GenrePresenter +import code.name.monkey.retromusic.ui.adapter.GenreAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewFragment +import code.name.monkey.retromusic.util.PreferenceUtil + +class GenreFragment : AbsLibraryPagerRecyclerViewFragment(), GenreContract.GenreView { + + private var mPresenter: GenrePresenter? = null + + override val emptyMessage: Int + get() = R.string.no_genres + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + mPresenter = GenrePresenter(this) + } + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + if (menuVisible) { + libraryFragment.setTitle(if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.genres) + } + } + + override fun onResume() { + super.onResume() + libraryFragment.setTitle(if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.genres) + if (adapter!!.dataSet.isEmpty()) { + mPresenter!!.subscribe() + } + } + + + override fun onDestroy() { + super.onDestroy() + mPresenter!!.unsubscribe() + } + + override fun createLayoutManager(): LinearLayoutManager { + return LinearLayoutManager(activity) + } + + override fun createAdapter(): GenreAdapter { + val dataSet = adapter!!.dataSet + return GenreAdapter(libraryFragment.mainActivity, dataSet, R.layout.item_list) + } + + override fun loading() { + + } + + override fun showData(songs: ArrayList) { + adapter!!.swapDataSet(songs) + } + + override fun showEmptyView() { + adapter!!.swapDataSet(ArrayList()) + } + + override fun completed() { + + } + + + override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { + super.onCreateOptionsMenu(menu, inflater) + menu!!.removeItem(R.id.action_sort_order) + menu.removeItem(R.id.action_grid_size) + menu.removeItem(R.id.action_new_playlist) + } + + companion object { + + fun newInstance(): GenreFragment { + val args = Bundle() + val fragment = GenreFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/LibraryFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/LibraryFragment.java deleted file mode 100644 index efdd1d01..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/LibraryFragment.java +++ /dev/null @@ -1,476 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity; - -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.SubMenu; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.afollestad.materialcab.MaterialCab; -import com.google.android.material.appbar.AppBarLayout; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; -import androidx.appcompat.widget.Toolbar; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentManager; -import androidx.fragment.app.FragmentTransaction; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.common.ATHToolbarActivity; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.dialogs.CreatePlaylistDialog; -import code.name.monkey.retromusic.dialogs.SleepTimerDialog; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.SortOrder; -import code.name.monkey.retromusic.interfaces.CabHolder; -import code.name.monkey.retromusic.interfaces.MainActivityFragmentCallbacks; -import code.name.monkey.retromusic.loaders.SongLoader; -import code.name.monkey.retromusic.ui.activities.SettingsActivity; -import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment; -import code.name.monkey.retromusic.ui.fragments.base.AbsMainActivityFragment; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.RetroColorUtil; -import code.name.monkey.retromusic.util.RetroUtil; - -public class LibraryFragment extends AbsMainActivityFragment implements CabHolder, MainActivityFragmentCallbacks { - - public static final String TAG = "LibraryFragment"; - private static final String CURRENT_TAB_ID = "current_tab_id"; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.app_bar) - AppBarLayout appbar; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.fragment_container) - View contentContainer; - - - private Unbinder unBinder; - private MaterialCab cab; - private FragmentManager fragmentManager; - - public static Fragment newInstance(int tab) { - Bundle args = new Bundle(); - args.putInt(CURRENT_TAB_ID, tab); - LibraryFragment fragment = new LibraryFragment(); - fragment.setArguments(args); - return fragment; - } - - public static Fragment newInstance() { - return new LibraryFragment(); - } - - - public void setTitle(@StringRes int name) { - title.setText(getString(name)); - } - - public void addOnAppBarOffsetChangedListener(AppBarLayout.OnOffsetChangedListener onOffsetChangedListener) { - appbar.addOnOffsetChangedListener(onOffsetChangedListener); - } - - public void removeOnAppBarOffsetChangedListener(AppBarLayout.OnOffsetChangedListener onOffsetChangedListener) { - appbar.removeOnOffsetChangedListener(onOffsetChangedListener); - } - - public int getTotalAppBarScrollingRange() { - return appbar.getTotalScrollRange(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_library, container, false); - unBinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setStatusbarColorAuto(view); - setupToolbar(); - inflateFragment(); - - } - - private void inflateFragment() { - if (getArguments() == null) { - selectedFragment(SongsFragment.newInstance()); - return; - } - switch (getArguments().getInt(CURRENT_TAB_ID)) { - default: - case R.id.action_song: - selectedFragment(SongsFragment.newInstance()); - break; - case R.id.action_album: - selectedFragment(AlbumsFragment.newInstance()); - break; - case R.id.action_artist: - selectedFragment(ArtistsFragment.newInstance()); - break; - case R.id.action_playlist: - selectedFragment(PlaylistsFragment.newInstance()); - break; - } - } - - @SuppressWarnings("ConstantConditions") - private void setupToolbar() { - title.setTextColor(ThemeStore.textColorPrimary(getContext())); - - int primaryColor = ThemeStore.primaryColor(getContext()); - TintHelper.setTintAuto(contentContainer, primaryColor, true); - - toolbar.setBackgroundColor(primaryColor); - appbar.setBackgroundColor(primaryColor); - appbar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> - getMainActivity().setLightStatusbar(!ATHUtil.isWindowBackgroundDark(getContext()))); - getMainActivity().setTitle(null); - getMainActivity().setSupportActionBar(toolbar); - toolbar.setNavigationOnClickListener(v -> NavigationUtil.goToSearch(getMainActivity())); - toolbar.setOnClickListener(v -> showMainMenu()); - toolbar.setNavigationIcon(RetroUtil.getTintedDrawable(getMainActivity(), R.drawable.ic_search_white_24dp, ThemeStore.textColorPrimary(getMainActivity()))); - } - - private Fragment getCurrentFragment() { - if (fragmentManager == null) { - return SongsFragment.newInstance(); - } - return fragmentManager.findFragmentByTag(LibraryFragment.TAG); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unBinder.unbind(); - } - - @Override - public boolean handleBackPress() { - if (cab != null && cab.isActive()) { - cab.finish(); - return true; - } - return false; - } - - private void selectedFragment(Fragment fragment) { - fragmentManager = getChildFragmentManager(); - FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); - - fragmentTransaction - .replace(R.id.fragment_container, fragment, TAG) - .commit(); - } - - @NonNull - @Override - public MaterialCab openCab(int menuRes, MaterialCab.Callback callback) { - if (cab != null && cab.isActive()) { - cab.finish(); - } - //noinspection ConstantConditions - cab = new MaterialCab(getMainActivity(), R.id.cab_stub) - .setMenu(menuRes) - .setCloseDrawableRes(R.drawable.ic_close_white_24dp) - .setBackgroundColor( - RetroColorUtil.shiftBackgroundColorForLightText(ThemeStore.primaryColor(getActivity()))) - .start(callback); - return cab; - } - - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - inflater.inflate(R.menu.menu_main, menu); - - Fragment currentFragment = getCurrentFragment(); - if (currentFragment instanceof AbsLibraryPagerRecyclerViewCustomGridSizeFragment - && currentFragment.isAdded()) { - AbsLibraryPagerRecyclerViewCustomGridSizeFragment fragment = (AbsLibraryPagerRecyclerViewCustomGridSizeFragment) currentFragment; - - MenuItem gridSizeItem = menu.findItem(R.id.action_grid_size); - if (RetroUtil.isLandscape()) { - gridSizeItem.setTitle(R.string.action_grid_size_land); - } - setUpGridSizeMenu(fragment, gridSizeItem.getSubMenu()); - - setUpSortOrderMenu(fragment, menu.findItem(R.id.action_sort_order).getSubMenu()); - - } else { - menu.add(0, R.id.action_new_playlist, 0, R.string.new_playlist_title); - menu.removeItem(R.id.action_grid_size); - } - Activity activity = getActivity(); - if (activity == null) { - return; - } - ToolbarContentTintHelper.handleOnCreateOptionsMenu(getActivity(), toolbar, menu, ATHToolbarActivity.getToolbarBackgroundColor(toolbar)); - } - - @Override - public void onPrepareOptionsMenu(Menu menu) { - super.onPrepareOptionsMenu(menu); - Activity activity = getActivity(); - if (activity == null) { - return; - } - ToolbarContentTintHelper.handleOnPrepareOptionsMenu(activity, toolbar); - } - - - private void setUpSortOrderMenu( - @NonNull AbsLibraryPagerRecyclerViewCustomGridSizeFragment fragment, - @NonNull SubMenu sortOrderMenu) { - String currentSortOrder = fragment.getSortOrder(); - sortOrderMenu.clear(); - - if (fragment instanceof AlbumsFragment) { - sortOrderMenu.add(0, R.id.action_album_sort_order_asc, 0, R.string.sort_order_a_z) - .setChecked(currentSortOrder.equals(SortOrder.AlbumSortOrder.ALBUM_A_Z)); - sortOrderMenu.add(0, R.id.action_album_sort_order_desc, 1, R.string.sort_order_z_a) - .setChecked(currentSortOrder.equals(SortOrder.AlbumSortOrder.ALBUM_Z_A)); - sortOrderMenu.add(0, R.id.action_album_sort_order_artist, 2, R.string.sort_order_artist) - .setChecked(currentSortOrder.equals(SortOrder.AlbumSortOrder.ALBUM_ARTIST)); - sortOrderMenu.add(0, R.id.action_album_sort_order_year, 3, R.string.sort_order_year) - .setChecked(currentSortOrder.equals(SortOrder.AlbumSortOrder.ALBUM_YEAR)); - } else if (fragment instanceof ArtistsFragment) { - sortOrderMenu.add(0, R.id.action_artist_sort_order_asc, 0, R.string.sort_order_a_z) - .setChecked(currentSortOrder.equals(SortOrder.ArtistSortOrder.ARTIST_A_Z)); - sortOrderMenu.add(0, R.id.action_artist_sort_order_desc, 1, R.string.sort_order_z_a) - .setChecked(currentSortOrder.equals(SortOrder.ArtistSortOrder.ARTIST_Z_A)); - } else if (fragment instanceof SongsFragment) { - sortOrderMenu.add(0, R.id.action_song_sort_order_asc, 0, R.string.sort_order_a_z) - .setChecked(currentSortOrder.equals(SortOrder.SongSortOrder.SONG_A_Z)); - sortOrderMenu.add(0, R.id.action_song_sort_order_desc, 1, R.string.sort_order_z_a) - .setChecked(currentSortOrder.equals(SortOrder.SongSortOrder.SONG_Z_A)); - sortOrderMenu.add(0, R.id.action_song_sort_order_artist, 2, R.string.sort_order_artist) - .setChecked(currentSortOrder.equals(SortOrder.SongSortOrder.SONG_ARTIST)); - sortOrderMenu.add(0, R.id.action_song_sort_order_album, 3, R.string.sort_order_album) - .setChecked(currentSortOrder.equals(SortOrder.SongSortOrder.SONG_ALBUM)); - sortOrderMenu.add(0, R.id.action_song_sort_order_year, 4, R.string.sort_order_year) - .setChecked(currentSortOrder.equals(SortOrder.SongSortOrder.SONG_YEAR)); - sortOrderMenu.add(0, R.id.action_song_sort_order_date, 4, R.string.sort_order_date) - .setChecked(currentSortOrder.equals(SortOrder.SongSortOrder.SONG_DATE)); - - } - - sortOrderMenu.setGroupCheckable(0, true, true); - } - - private boolean handleSortOrderMenuItem( - @NonNull AbsLibraryPagerRecyclerViewCustomGridSizeFragment - fragment, @NonNull MenuItem item) { - String sortOrder = null; - if (fragment instanceof AlbumsFragment) { - switch (item.getItemId()) { - case R.id.action_album_sort_order_asc: - sortOrder = SortOrder.AlbumSortOrder.ALBUM_A_Z; - break; - case R.id.action_album_sort_order_desc: - sortOrder = SortOrder.AlbumSortOrder.ALBUM_Z_A; - break; - case R.id.action_album_sort_order_artist: - sortOrder = SortOrder.AlbumSortOrder.ALBUM_ARTIST; - break; - case R.id.action_album_sort_order_year: - sortOrder = SortOrder.AlbumSortOrder.ALBUM_YEAR; - break; - } - } else if (fragment instanceof ArtistsFragment) { - switch (item.getItemId()) { - case R.id.action_artist_sort_order_asc: - sortOrder = SortOrder.ArtistSortOrder.ARTIST_A_Z; - break; - case R.id.action_artist_sort_order_desc: - sortOrder = SortOrder.ArtistSortOrder.ARTIST_Z_A; - break; - } - } else if (fragment instanceof SongsFragment) { - switch (item.getItemId()) { - case R.id.action_song_sort_order_asc: - sortOrder = SortOrder.SongSortOrder.SONG_A_Z; - break; - case R.id.action_song_sort_order_desc: - sortOrder = SortOrder.SongSortOrder.SONG_Z_A; - break; - case R.id.action_song_sort_order_artist: - sortOrder = SortOrder.SongSortOrder.SONG_ARTIST; - break; - case R.id.action_song_sort_order_album: - sortOrder = SortOrder.SongSortOrder.SONG_ALBUM; - break; - case R.id.action_song_sort_order_year: - sortOrder = SortOrder.SongSortOrder.SONG_YEAR; - break; - case R.id.action_song_sort_order_date: - sortOrder = SortOrder.SongSortOrder.SONG_DATE; - break; - - } - } - - if (sortOrder != null) { - item.setChecked(true); - fragment.setAndSaveSortOrder(sortOrder); - return true; - } - - return false; - } - - - @SuppressWarnings("ConstantConditions") - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - //if (pager == null) return false; - Fragment currentFragment = getCurrentFragment(); - if (currentFragment instanceof AbsLibraryPagerRecyclerViewCustomGridSizeFragment) { - AbsLibraryPagerRecyclerViewCustomGridSizeFragment fragment = (AbsLibraryPagerRecyclerViewCustomGridSizeFragment) currentFragment; - if (handleGridSizeMenuItem(fragment, item)) { - return true; - } - if (handleSortOrderMenuItem(fragment, item)) { - return true; - } - } - int id = item.getItemId(); - switch (id) { - case R.id.action_new_playlist: - CreatePlaylistDialog.create().show(getChildFragmentManager(), "CREATE_PLAYLIST"); - return true; - case R.id.action_shuffle_all: - MusicPlayerRemote.openAndShuffleQueue(SongLoader.Companion.getAllSongs(getContext()) - .blockingFirst(), true); - return true; - case R.id.action_equalizer: - NavigationUtil.openEqualizer(getActivity()); - return true; - case R.id.action_sleep_timer: - if (getFragmentManager() != null) { - new SleepTimerDialog().show(getFragmentManager(), TAG); - } - return true; - case R.id.action_settings: - startActivity(new Intent(getContext(), SettingsActivity.class)); - break; - } - return super.onOptionsItemSelected(item); - } - - - private void setUpGridSizeMenu( - @NonNull AbsLibraryPagerRecyclerViewCustomGridSizeFragment fragment, - @NonNull SubMenu gridSizeMenu) { - switch (fragment.getGridSize()) { - case 1: - gridSizeMenu.findItem(R.id.action_grid_size_1).setChecked(true); - break; - case 2: - gridSizeMenu.findItem(R.id.action_grid_size_2).setChecked(true); - break; - case 3: - gridSizeMenu.findItem(R.id.action_grid_size_3).setChecked(true); - break; - case 4: - gridSizeMenu.findItem(R.id.action_grid_size_4).setChecked(true); - break; - case 5: - gridSizeMenu.findItem(R.id.action_grid_size_5).setChecked(true); - break; - case 6: - gridSizeMenu.findItem(R.id.action_grid_size_6).setChecked(true); - break; - case 7: - gridSizeMenu.findItem(R.id.action_grid_size_7).setChecked(true); - break; - case 8: - gridSizeMenu.findItem(R.id.action_grid_size_8).setChecked(true); - break; - } - int maxGridSize = fragment.getMaxGridSize(); - if (maxGridSize < 8) { - gridSizeMenu.findItem(R.id.action_grid_size_8).setVisible(false); - } - if (maxGridSize < 7) { - gridSizeMenu.findItem(R.id.action_grid_size_7).setVisible(false); - } - if (maxGridSize < 6) { - gridSizeMenu.findItem(R.id.action_grid_size_6).setVisible(false); - } - if (maxGridSize < 5) { - gridSizeMenu.findItem(R.id.action_grid_size_5).setVisible(false); - } - if (maxGridSize < 4) { - gridSizeMenu.findItem(R.id.action_grid_size_4).setVisible(false); - } - if (maxGridSize < 3) { - gridSizeMenu.findItem(R.id.action_grid_size_3).setVisible(false); - } - } - - - private boolean handleGridSizeMenuItem( - @NonNull AbsLibraryPagerRecyclerViewCustomGridSizeFragment - fragment, @NonNull MenuItem item) { - int gridSize = 0; - switch (item.getItemId()) { - case R.id.action_grid_size_1: - gridSize = 1; - break; - case R.id.action_grid_size_2: - gridSize = 2; - break; - case R.id.action_grid_size_3: - gridSize = 3; - break; - case R.id.action_grid_size_4: - gridSize = 4; - break; - case R.id.action_grid_size_5: - gridSize = 5; - break; - case R.id.action_grid_size_6: - gridSize = 6; - break; - case R.id.action_grid_size_7: - gridSize = 7; - break; - case R.id.action_grid_size_8: - gridSize = 8; - break; - } - - if (gridSize > 0) { - item.setChecked(true); - fragment.setAndSaveGridSize(gridSize); - return true; - } - return false; - } - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/LibraryFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/LibraryFragment.kt new file mode 100644 index 00000000..a9d4b4e0 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/LibraryFragment.kt @@ -0,0 +1,360 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity + +import android.content.Intent +import android.os.Bundle +import android.view.* +import android.widget.TextView +import androidx.annotation.StringRes +import androidx.appcompat.widget.Toolbar +import androidx.fragment.app.Fragment +import butterknife.Unbinder +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.common.ATHToolbarActivity +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.dialogs.CreatePlaylistDialog +import code.name.monkey.retromusic.dialogs.SleepTimerDialog +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.SortOrder +import code.name.monkey.retromusic.interfaces.CabHolder +import code.name.monkey.retromusic.interfaces.MainActivityFragmentCallbacks +import code.name.monkey.retromusic.loaders.SongLoader +import code.name.monkey.retromusic.ui.activities.SettingsActivity +import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment +import code.name.monkey.retromusic.ui.fragments.base.AbsMainActivityFragment +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.RetroColorUtil +import code.name.monkey.retromusic.util.RetroUtil +import com.afollestad.materialcab.MaterialCab +import com.google.android.material.appbar.AppBarLayout + +class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragmentCallbacks, AppBarLayout.OnOffsetChangedListener { + override fun onOffsetChanged(p0: AppBarLayout?, p1: Int) { + mainActivity.setLightStatusbar(!ATHUtil.isWindowBackgroundDark(context)) + } + + + lateinit var toolbar: Toolbar + lateinit var appbar: AppBarLayout + lateinit var title: TextView + lateinit var contentContainer: View + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + val view = inflater.inflate(R.layout.fragment_library, container, false) + toolbar = view.findViewById(R.id.toolbar) + appbar = view.findViewById(R.id.app_bar) + title = view.findViewById(R.id.title) + contentContainer = view.findViewById(R.id.fragment_container) + return view + } + + private var cab: MaterialCab? = null + + + val totalAppBarScrollingRange: Int + get() = appbar.totalScrollRange + + private val currentFragment: Fragment? + get() = if (fragmentManager == null) { + SongsFragment.newInstance() + } else fragmentManager!!.findFragmentByTag(LibraryFragment.TAG) + + + fun setTitle(@StringRes name: Int) { + title.text = getString(name) + } + + fun addOnAppBarOffsetChangedListener(onOffsetChangedListener: AppBarLayout.OnOffsetChangedListener) { + appbar.addOnOffsetChangedListener(onOffsetChangedListener) + } + + fun removeOnAppBarOffsetChangedListener(onOffsetChangedListener: AppBarLayout.OnOffsetChangedListener) { + appbar.removeOnOffsetChangedListener(onOffsetChangedListener) + } + + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setStatusbarColorAuto(view) + setupToolbar() + inflateFragment() + + } + + private fun inflateFragment() { + if (arguments == null) { + selectedFragment(SongsFragment.newInstance()) + return + } + when (arguments!!.getInt(CURRENT_TAB_ID)) { + R.id.action_song -> selectedFragment(SongsFragment.newInstance()) + R.id.action_album -> selectedFragment(AlbumsFragment.newInstance()) + R.id.action_artist -> selectedFragment(ArtistsFragment.newInstance()) + R.id.action_playlist -> selectedFragment(PlaylistsFragment.newInstance()) + else -> selectedFragment(SongsFragment.newInstance()) + } + } + + private fun setupToolbar() { + title.setTextColor(ThemeStore.textColorPrimary(context!!)) + + val primaryColor = ThemeStore.primaryColor(context!!) + TintHelper.setTintAuto(contentContainer, primaryColor, true) + + toolbar.setBackgroundColor(primaryColor) + appbar.setBackgroundColor(primaryColor) + appbar.addOnOffsetChangedListener(this) + mainActivity.title = null + mainActivity.setSupportActionBar(toolbar) + + toolbar.setNavigationOnClickListener { NavigationUtil.goToSearch(mainActivity) } + toolbar.setOnClickListener { showMainMenu() } + toolbar.navigationIcon = RetroUtil.getTintedDrawable(mainActivity, R.drawable.ic_search_white_24dp, ThemeStore.textColorPrimary(mainActivity)) + } + + + override fun handleBackPress(): Boolean { + if (cab != null && cab!!.isActive) { + cab!!.finish() + return true + } + return false + } + + private fun selectedFragment(fragment: Fragment) { + val fragmentManager = childFragmentManager + val fragmentTransaction = fragmentManager.beginTransaction() + + fragmentTransaction + .replace(R.id.fragment_container, fragment, TAG) + .commit() + } + + override fun openCab(menuRes: Int, callback: MaterialCab.Callback): MaterialCab { + if (cab != null && cab!!.isActive) { + cab!!.finish() + } + + cab = MaterialCab(mainActivity, R.id.cab_stub) + .setMenu(menuRes) + .setCloseDrawableRes(R.drawable.ic_close_white_24dp) + .setBackgroundColor( + RetroColorUtil.shiftBackgroundColorForLightText(ThemeStore.primaryColor(activity!!))) + .start(callback) + return cab as MaterialCab + } + + + override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { + super.onCreateOptionsMenu(menu, inflater) + inflater!!.inflate(R.menu.menu_main, menu) + + val currentFragment = currentFragment + if (currentFragment is AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *> && currentFragment.isAdded) { + val fragment = currentFragment as AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>? + + val gridSizeItem = menu!!.findItem(R.id.action_grid_size) + if (RetroUtil.isLandscape()) { + gridSizeItem.setTitle(R.string.action_grid_size_land) + } + setUpGridSizeMenu(fragment!!, gridSizeItem.subMenu) + + setUpSortOrderMenu(fragment, menu.findItem(R.id.action_sort_order).subMenu) + + } else { + menu!!.add(0, R.id.action_new_playlist, 0, R.string.new_playlist_title) + menu.removeItem(R.id.action_grid_size) + } + activity ?: return + ToolbarContentTintHelper.handleOnCreateOptionsMenu(getActivity(), toolbar, menu, ATHToolbarActivity.getToolbarBackgroundColor(toolbar)) + } + + override fun onPrepareOptionsMenu(menu: Menu?) { + super.onPrepareOptionsMenu(menu) + val activity = activity ?: return + ToolbarContentTintHelper.handleOnPrepareOptionsMenu(activity, toolbar) + } + + + private fun setUpSortOrderMenu( + fragment: AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>, + sortOrderMenu: SubMenu) { + val currentSortOrder = fragment.getSortOrder() + sortOrderMenu.clear() + + if (fragment is AlbumsFragment) { + sortOrderMenu.add(0, R.id.action_album_sort_order_asc, 0, R.string.sort_order_a_z).isChecked = currentSortOrder == SortOrder.AlbumSortOrder.ALBUM_A_Z + sortOrderMenu.add(0, R.id.action_album_sort_order_desc, 1, R.string.sort_order_z_a).isChecked = currentSortOrder == SortOrder.AlbumSortOrder.ALBUM_Z_A + sortOrderMenu.add(0, R.id.action_album_sort_order_artist, 2, R.string.sort_order_artist).isChecked = currentSortOrder == SortOrder.AlbumSortOrder.ALBUM_ARTIST + sortOrderMenu.add(0, R.id.action_album_sort_order_year, 3, R.string.sort_order_year).isChecked = currentSortOrder == SortOrder.AlbumSortOrder.ALBUM_YEAR + } else if (fragment is ArtistsFragment) { + sortOrderMenu.add(0, R.id.action_artist_sort_order_asc, 0, R.string.sort_order_a_z).isChecked = currentSortOrder == SortOrder.ArtistSortOrder.ARTIST_A_Z + sortOrderMenu.add(0, R.id.action_artist_sort_order_desc, 1, R.string.sort_order_z_a).isChecked = currentSortOrder == SortOrder.ArtistSortOrder.ARTIST_Z_A + } else if (fragment is SongsFragment) { + sortOrderMenu.add(0, R.id.action_song_sort_order_asc, 0, R.string.sort_order_a_z).isChecked = currentSortOrder == SortOrder.SongSortOrder.SONG_A_Z + sortOrderMenu.add(0, R.id.action_song_sort_order_desc, 1, R.string.sort_order_z_a).isChecked = currentSortOrder == SortOrder.SongSortOrder.SONG_Z_A + sortOrderMenu.add(0, R.id.action_song_sort_order_artist, 2, R.string.sort_order_artist).isChecked = currentSortOrder == SortOrder.SongSortOrder.SONG_ARTIST + sortOrderMenu.add(0, R.id.action_song_sort_order_album, 3, R.string.sort_order_album).isChecked = currentSortOrder == SortOrder.SongSortOrder.SONG_ALBUM + sortOrderMenu.add(0, R.id.action_song_sort_order_year, 4, R.string.sort_order_year).isChecked = currentSortOrder == SortOrder.SongSortOrder.SONG_YEAR + sortOrderMenu.add(0, R.id.action_song_sort_order_date, 4, R.string.sort_order_date).isChecked = currentSortOrder == SortOrder.SongSortOrder.SONG_DATE + + } + + sortOrderMenu.setGroupCheckable(0, true, true) + } + + private fun handleSortOrderMenuItem( + fragment: AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>, item: MenuItem): Boolean { + var sortOrder: String? = null + if (fragment is AlbumsFragment) { + when (item.itemId) { + R.id.action_album_sort_order_asc -> sortOrder = SortOrder.AlbumSortOrder.ALBUM_A_Z + R.id.action_album_sort_order_desc -> sortOrder = SortOrder.AlbumSortOrder.ALBUM_Z_A + R.id.action_album_sort_order_artist -> sortOrder = SortOrder.AlbumSortOrder.ALBUM_ARTIST + R.id.action_album_sort_order_year -> sortOrder = SortOrder.AlbumSortOrder.ALBUM_YEAR + } + } else if (fragment is ArtistsFragment) { + when (item.itemId) { + R.id.action_artist_sort_order_asc -> sortOrder = SortOrder.ArtistSortOrder.ARTIST_A_Z + R.id.action_artist_sort_order_desc -> sortOrder = SortOrder.ArtistSortOrder.ARTIST_Z_A + } + } else if (fragment is SongsFragment) { + when (item.itemId) { + R.id.action_song_sort_order_asc -> sortOrder = SortOrder.SongSortOrder.SONG_A_Z + R.id.action_song_sort_order_desc -> sortOrder = SortOrder.SongSortOrder.SONG_Z_A + R.id.action_song_sort_order_artist -> sortOrder = SortOrder.SongSortOrder.SONG_ARTIST + R.id.action_song_sort_order_album -> sortOrder = SortOrder.SongSortOrder.SONG_ALBUM + R.id.action_song_sort_order_year -> sortOrder = SortOrder.SongSortOrder.SONG_YEAR + R.id.action_song_sort_order_date -> sortOrder = SortOrder.SongSortOrder.SONG_DATE + } + } + + if (sortOrder != null) { + item.isChecked = true + fragment.setAndSaveSortOrder(sortOrder) + return true + } + + return false + } + + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + //if (pager == null) return false; + val currentFragment = currentFragment + if (currentFragment is AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>) { + val fragment = currentFragment as AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>? + if (handleGridSizeMenuItem(fragment!!, item)) { + return true + } + if (handleSortOrderMenuItem(fragment, item)) { + return true + } + } + val id = item.itemId + when (id) { + R.id.action_new_playlist -> { + CreatePlaylistDialog.create().show(childFragmentManager, "CREATE_PLAYLIST") + return true + } + R.id.action_shuffle_all -> { + MusicPlayerRemote.openAndShuffleQueue(SongLoader.getAllSongs(context!!).blockingFirst(), true) + return true + } + R.id.action_equalizer -> { + NavigationUtil.openEqualizer(activity!!) + return true + } + R.id.action_sleep_timer -> { + if (fragmentManager != null) { + SleepTimerDialog().show(fragmentManager!!, TAG) + } + return true + } + R.id.action_settings -> startActivity(Intent(context, SettingsActivity::class.java)) + } + return super.onOptionsItemSelected(item) + } + + + private fun setUpGridSizeMenu( + fragment: AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>, + gridSizeMenu: SubMenu) { + when (fragment.getGridSize()) { + 1 -> gridSizeMenu.findItem(R.id.action_grid_size_1).isChecked = true + 2 -> gridSizeMenu.findItem(R.id.action_grid_size_2).isChecked = true + 3 -> gridSizeMenu.findItem(R.id.action_grid_size_3).isChecked = true + 4 -> gridSizeMenu.findItem(R.id.action_grid_size_4).isChecked = true + 5 -> gridSizeMenu.findItem(R.id.action_grid_size_5).isChecked = true + 6 -> gridSizeMenu.findItem(R.id.action_grid_size_6).isChecked = true + 7 -> gridSizeMenu.findItem(R.id.action_grid_size_7).isChecked = true + 8 -> gridSizeMenu.findItem(R.id.action_grid_size_8).isChecked = true + } + val maxGridSize = fragment.maxGridSize + if (maxGridSize < 8) { + gridSizeMenu.findItem(R.id.action_grid_size_8).isVisible = false + } + if (maxGridSize < 7) { + gridSizeMenu.findItem(R.id.action_grid_size_7).isVisible = false + } + if (maxGridSize < 6) { + gridSizeMenu.findItem(R.id.action_grid_size_6).isVisible = false + } + if (maxGridSize < 5) { + gridSizeMenu.findItem(R.id.action_grid_size_5).isVisible = false + } + if (maxGridSize < 4) { + gridSizeMenu.findItem(R.id.action_grid_size_4).isVisible = false + } + if (maxGridSize < 3) { + gridSizeMenu.findItem(R.id.action_grid_size_3).isVisible = false + } + } + + + private fun handleGridSizeMenuItem( + fragment: AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>, item: MenuItem): Boolean { + var gridSize = 0 + when (item.itemId) { + R.id.action_grid_size_1 -> gridSize = 1 + R.id.action_grid_size_2 -> gridSize = 2 + R.id.action_grid_size_3 -> gridSize = 3 + R.id.action_grid_size_4 -> gridSize = 4 + R.id.action_grid_size_5 -> gridSize = 5 + R.id.action_grid_size_6 -> gridSize = 6 + R.id.action_grid_size_7 -> gridSize = 7 + R.id.action_grid_size_8 -> gridSize = 8 + } + + if (gridSize > 0) { + item.isChecked = true + fragment.setAndSaveGridSize(gridSize) + return true + } + return false + } + + companion object { + + const val TAG: String = "LibraryFragment" + private const val CURRENT_TAB_ID = "current_tab_id" + + fun newInstance(tab: Int): Fragment { + val args = Bundle() + args.putInt(CURRENT_TAB_ID, tab) + val fragment = LibraryFragment() + fragment.arguments = args + return fragment + } + + fun newInstance(): Fragment { + return LibraryFragment() + } + } + + +} + diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/PlaylistsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/PlaylistsFragment.java deleted file mode 100644 index 19c2d8f2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/PlaylistsFragment.java +++ /dev/null @@ -1,120 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.View; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.mvp.contract.PlaylistContract; -import code.name.monkey.retromusic.mvp.presenter.PlaylistPresenter; -import code.name.monkey.retromusic.ui.adapter.playlist.PlaylistAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - - -public class PlaylistsFragment extends AbsLibraryPagerRecyclerViewFragment implements - PlaylistContract.PlaylistView { - - private PlaylistPresenter presenter; - - public static PlaylistsFragment newInstance() { - Bundle args = new Bundle(); - PlaylistsFragment fragment = new PlaylistsFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setHasOptionsMenu(true); - presenter = new PlaylistPresenter(this); - } - - @Override - protected LinearLayoutManager createLayoutManager() { - return new LinearLayoutManager(getActivity()); - } - - @NonNull - @Override - protected PlaylistAdapter createAdapter() { - return new PlaylistAdapter(getLibraryFragment().getMainActivity(), new ArrayList<>(), - R.layout.item_list, getLibraryFragment()); - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (menuVisible) { - getLibraryFragment().setTitle(PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.playlists); - } - } - - @Override - public void onResume() { - super.onResume(); - getLibraryFragment().setTitle(PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.playlists); - if (getAdapter().getDataSet().isEmpty()) { - presenter.subscribe(); - } - } - - @Override - public void onDestroy() { - presenter.unsubscribe(); - super.onDestroy(); - } - - @Override - public void onMediaStoreChanged() { - super.onMediaStoreChanged(); - presenter.loadPlaylists(); - } - - @Override - public void loading() { - - } - - @Override - public void showEmptyView() { - getAdapter().swapDataSet(new ArrayList<>()); - } - - @Override - public void completed() { - - } - - @Override - public void showData(ArrayList playlists) { - getAdapter().swapDataSet(playlists); - } - - @Override - public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - super.onCreateOptionsMenu(menu, inflater); - menu.removeItem(R.id.action_shuffle_all); - menu.removeItem(R.id.action_sort_order); - menu.removeItem(R.id.action_grid_size); - } - - @Override - protected int getEmptyMessage() { - return R.string.no_playlists; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/PlaylistsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/PlaylistsFragment.kt new file mode 100644 index 00000000..76181522 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/PlaylistsFragment.kt @@ -0,0 +1,99 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity + +import android.os.Bundle +import androidx.recyclerview.widget.LinearLayoutManager +import android.view.Menu +import android.view.MenuInflater +import android.view.View + +import java.util.ArrayList + +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.mvp.contract.PlaylistContract +import code.name.monkey.retromusic.mvp.presenter.PlaylistPresenter +import code.name.monkey.retromusic.ui.adapter.playlist.PlaylistAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewFragment +import code.name.monkey.retromusic.util.PreferenceUtil + + +class PlaylistsFragment : AbsLibraryPagerRecyclerViewFragment(), PlaylistContract.PlaylistView { + + private var presenter: PlaylistPresenter? = null + + override val emptyMessage: Int + get() = R.string.no_playlists + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setHasOptionsMenu(true) + presenter = PlaylistPresenter(this) + } + + override fun createLayoutManager(): LinearLayoutManager { + return LinearLayoutManager(activity) + } + + override fun createAdapter(): PlaylistAdapter { + return PlaylistAdapter(libraryFragment.mainActivity, ArrayList(), + R.layout.item_list, libraryFragment) + } + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + if (menuVisible) { + libraryFragment.setTitle(if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.playlists) + } + } + + override fun onResume() { + super.onResume() + libraryFragment.setTitle(if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.playlists) + if (adapter!!.dataSet.isEmpty()) { + presenter!!.subscribe() + } + } + + override fun onDestroy() { + presenter!!.unsubscribe() + super.onDestroy() + } + + override fun onMediaStoreChanged() { + super.onMediaStoreChanged() + presenter!!.loadPlaylists() + } + + override fun loading() { + + } + + override fun showEmptyView() { + adapter!!.swapDataSet(ArrayList()) + } + + override fun completed() { + + } + + override fun showData(playlists: ArrayList) { + adapter!!.swapDataSet(playlists) + } + + override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { + super.onCreateOptionsMenu(menu, inflater) + menu!!.removeItem(R.id.action_shuffle_all) + menu.removeItem(R.id.action_sort_order) + menu.removeItem(R.id.action_grid_size) + } + + companion object { + + fun newInstance(): PlaylistsFragment { + val args = Bundle() + val fragment = PlaylistsFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/SongsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/SongsFragment.java deleted file mode 100644 index 69fe954d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/SongsFragment.java +++ /dev/null @@ -1,177 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.GridLayoutManager; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.contract.SongContract; -import code.name.monkey.retromusic.mvp.presenter.SongPresenter; -import code.name.monkey.retromusic.ui.adapter.song.ShuffleButtonSongAdapter; -import code.name.monkey.retromusic.ui.adapter.song.SongAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - -@SuppressWarnings("ConstantConditions") -public class SongsFragment extends - AbsLibraryPagerRecyclerViewCustomGridSizeFragment implements - SongContract.SongView { - - private SongPresenter presenter; - - public SongsFragment() { - // Required empty public constructor - } - - public static SongsFragment newInstance() { - Bundle args = new Bundle(); - SongsFragment fragment = new SongsFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - presenter = new SongPresenter(this); - } - - @NonNull - @Override - protected GridLayoutManager createLayoutManager() { - return new GridLayoutManager(getActivity(), getGridSize()); - } - - @Override - protected int getEmptyMessage() { - return R.string.no_songs; - } - - @NonNull - @Override - protected SongAdapter createAdapter() { - int itemLayoutRes = getItemLayoutRes(); - notifyLayoutResChanged(itemLayoutRes); - boolean usePalette = loadUsePalette(); - ArrayList dataSet = - getAdapter() == null ? new ArrayList() : getAdapter().getDataSet(); - - if (getGridSize() <= getMaxGridSizeForList()) { - return new ShuffleButtonSongAdapter(getLibraryFragment().getMainActivity(), dataSet, - itemLayoutRes, usePalette, getLibraryFragment()); - } - return new SongAdapter(getLibraryFragment().getMainActivity(), dataSet, itemLayoutRes, - usePalette, getLibraryFragment()); - } - - @Override - public void onMediaStoreChanged() { - presenter.loadSongs(); - } - - @Override - protected int loadGridSize() { - return PreferenceUtil.getInstance().getSongGridSize(getActivity()); - } - - @Override - protected void saveGridSize(int gridSize) { - PreferenceUtil.getInstance().setSongGridSize(gridSize); - } - - @Override - protected int loadGridSizeLand() { - return PreferenceUtil.getInstance().getSongGridSizeLand(getActivity()); - } - - @Override - protected void saveGridSizeLand(int gridSize) { - PreferenceUtil.getInstance().setSongGridSizeLand(gridSize); - } - - @Override - public void saveUsePalette(boolean usePalette) { - PreferenceUtil.getInstance().setSongColoredFooters(usePalette); - } - - @Override - public boolean loadUsePalette() { - return PreferenceUtil.getInstance().songColoredFooters(); - } - - @Override - public void setUsePalette(boolean usePalette) { - getAdapter().usePalette(usePalette); - } - - @Override - protected void setGridSize(int gridSize) { - getLayoutManager().setSpanCount(gridSize); - getAdapter().notifyDataSetChanged(); - } - - @Override - public void onResume() { - super.onResume(); - getLibraryFragment().setTitle( - PreferenceUtil.getInstance().tabTitles() ? R.string.library : R.string.songs); - if (getAdapter().getDataSet().isEmpty()) { - presenter.subscribe(); - } - } - - @Override - public void setMenuVisibility(boolean menuVisible) { - super.setMenuVisibility(menuVisible); - if (menuVisible) { - getLibraryFragment().setTitle( - PreferenceUtil.getInstance().tabTitles() ? R.string.library - : R.string.songs); - } - } - - @Override - public void onDestroy() { - presenter.unsubscribe(); - super.onDestroy(); - } - - @Override - public void loading() { - - } - - @Override - public void showData(ArrayList songs) { - getAdapter().swapDataSet(songs); - } - - @Override - public void showEmptyView() { - getAdapter().swapDataSet(new ArrayList()); - } - - @Override - public void completed() { - - } - - @Override - protected String loadSortOrder() { - return PreferenceUtil.getInstance().getSongSortOrder(); - } - - @Override - protected void saveSortOrder(String sortOrder) { - PreferenceUtil.getInstance().setSongSortOrder(sortOrder); - } - - @Override - protected void setSortOrder(String sortOrder) { - presenter.loadSongs(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/SongsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/SongsFragment.kt new file mode 100644 index 00000000..63bfc9d6 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/SongsFragment.kt @@ -0,0 +1,141 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity + +import android.os.Bundle +import androidx.recyclerview.widget.GridLayoutManager +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.mvp.contract.SongContract +import code.name.monkey.retromusic.mvp.presenter.SongPresenter +import code.name.monkey.retromusic.ui.adapter.song.ShuffleButtonSongAdapter +import code.name.monkey.retromusic.ui.adapter.song.SongAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsLibraryPagerRecyclerViewCustomGridSizeFragment +import code.name.monkey.retromusic.util.PreferenceUtil +import java.util.* + +class SongsFragment : AbsLibraryPagerRecyclerViewCustomGridSizeFragment(), SongContract.SongView { + + private var presenter: SongPresenter? = null + + override val emptyMessage: Int + get() = R.string.no_songs + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + presenter = SongPresenter(this) + } + + override fun createLayoutManager(): GridLayoutManager { + return GridLayoutManager(activity, getGridSize()) + } + + override fun createAdapter(): SongAdapter { + val itemLayoutRes = itemLayoutRes + notifyLayoutResChanged(itemLayoutRes) + val usePalette = loadUsePalette() + + val dataSet = if (adapter == null) ArrayList() else adapter!!.dataSet + + return if (getGridSize() <= maxGridSizeForList) { + ShuffleButtonSongAdapter(libraryFragment.mainActivity, dataSet, itemLayoutRes, usePalette, libraryFragment) + } else SongAdapter(libraryFragment.mainActivity, dataSet, itemLayoutRes, usePalette, libraryFragment) + } + + override fun onMediaStoreChanged() { + presenter!!.loadSongs() + } + + override fun loadGridSize(): Int { + return PreferenceUtil.getInstance().getSongGridSize(activity!!) + } + + override fun saveGridSize(gridColumns: Int) { + PreferenceUtil.getInstance().setSongGridSize(gridColumns) + } + + override fun loadGridSizeLand(): Int { + return PreferenceUtil.getInstance().getSongGridSizeLand(activity!!) + } + + override fun saveGridSizeLand(gridColumns: Int) { + PreferenceUtil.getInstance().setSongGridSizeLand(gridColumns) + } + + public override fun saveUsePalette(usePalette: Boolean) { + PreferenceUtil.getInstance().setSongColoredFooters(usePalette) + } + + public override fun loadUsePalette(): Boolean { + return PreferenceUtil.getInstance().songColoredFooters() + } + + public override fun setUsePalette(usePalette: Boolean) { + adapter!!.usePalette(usePalette) + } + + override fun setGridSize(gridSize: Int) { + layoutManager!!.spanCount = gridSize + adapter!!.notifyDataSetChanged() + } + + override fun onResume() { + super.onResume() + libraryFragment.setTitle(if (PreferenceUtil.getInstance().tabTitles()) R.string.library else R.string.songs) + if (adapter!!.dataSet.isEmpty()) { + presenter!!.subscribe() + } + } + + override fun setMenuVisibility(menuVisible: Boolean) { + super.setMenuVisibility(menuVisible) + if (menuVisible) { + libraryFragment.setTitle( + if (PreferenceUtil.getInstance().tabTitles()) + R.string.library + else + R.string.songs) + } + } + + override fun onDestroy() { + presenter!!.unsubscribe() + super.onDestroy() + } + + override fun loading() { + + } + + override fun showData(songs: ArrayList) { + adapter!!.swapDataSet(songs) + } + + override fun showEmptyView() { + adapter!!.swapDataSet(ArrayList()) + } + + override fun completed() { + + } + + override fun loadSortOrder(): String { + return PreferenceUtil.getInstance().songSortOrder + } + + override fun saveSortOrder(sortOrder: String) { + PreferenceUtil.getInstance().songSortOrder = sortOrder + } + + override fun setSortOrder(sortOrder: String) { + presenter!!.loadSongs() + } + + companion object { + + fun newInstance(): SongsFragment { + val args = Bundle() + val fragment = SongsFragment() + fragment.arguments = args + return fragment + } + } +}// Required empty public constructor diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/folders/FoldersFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/folders/FoldersFragment.java index a9e57f44..1fd8b121 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/folders/FoldersFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/folders/FoldersFragment.java @@ -82,7 +82,7 @@ public class FoldersFragment extends AbsMainActivityFragment implements private static final String PATH = "path"; private static final String CRUMBS = "crumbs"; - private static final int LOADER_ID = LoaderIds.FOLDERS_FRAGMENT; + private static final int LOADER_ID = LoaderIds.Companion.getFOLDERS_FRAGMENT(); @BindView(R.id.coordinator_layout) View coordinatorLayout; @@ -370,13 +370,13 @@ public class FoldersFragment extends AbsMainActivityFragment implements File file1 = (File) extra; int startIndex = -1; for (int i = 0; i < songs.size(); i++) { - if (file1.getPath().equals(songs.get(i).data)) { // path is already canonical here + if (file1.getPath().equals(songs.get(i).getData())) { // path is already canonical here startIndex = i; break; } } if (startIndex > -1) { - MusicPlayerRemote.openQueue(songs, startIndex, true); + MusicPlayerRemote.INSTANCE.openQueue(songs, startIndex, true); } else { final File finalFile = file1; Snackbar.make(coordinatorLayout, Html.fromHtml( @@ -397,7 +397,7 @@ public class FoldersFragment extends AbsMainActivityFragment implements public void onMultipleItemAction(MenuItem item, ArrayList files) { final int itemId = item.getItemId(); new ListSongsAsyncTask(getActivity(), null, - (songs, extra) -> SongsMenuHelper.handleMenuClick(getActivity(), songs, itemId)) + (songs, extra) -> SongsMenuHelper.INSTANCE.handleMenuClick(getActivity(), songs, itemId)) .execute(new ListSongsAsyncTask.LoadingInfo(files, AUDIO_FILE_FILTER, getFileComparator())); } @@ -425,7 +425,7 @@ public class FoldersFragment extends AbsMainActivityFragment implements case R.id.action_delete_from_device: new ListSongsAsyncTask(getActivity(), null, (songs, extra) -> { if (!songs.isEmpty()) { - SongsMenuHelper.handleMenuClick(getActivity(), songs, itemId); + SongsMenuHelper.INSTANCE.handleMenuClick(getActivity(), songs, itemId); } }).execute(new ListSongsAsyncTask.LoadingInfo(toList(file), AUDIO_FILE_FILTER, getFileComparator())); @@ -458,7 +458,7 @@ public class FoldersFragment extends AbsMainActivityFragment implements case R.id.action_details: case R.id.action_set_as_ringtone: case R.id.action_delete_from_device: - new ListSongsAsyncTask(getActivity(), null, (songs, extra) -> SongMenuHelper.handleMenuClick(getActivity(), songs.get(0), itemId)).execute(new ListSongsAsyncTask.LoadingInfo(toList(file), AUDIO_FILE_FILTER, getFileComparator())); + new ListSongsAsyncTask(getActivity(), null, (songs, extra) -> SongMenuHelper.INSTANCE.handleMenuClick(getActivity(), songs.get(0), itemId)).execute(new ListSongsAsyncTask.LoadingInfo(toList(file), AUDIO_FILE_FILTER, getFileComparator())); return true; case R.id.action_scan: new ListPathsAsyncTask(getActivity(), this::scanPaths).execute(new ListPathsAsyncTask.LoadingInfo(file, AUDIO_FILE_FILTER)); diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/home/BannerHomeFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/home/BannerHomeFragment.java deleted file mode 100644 index 5bb83674..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/home/BannerHomeFragment.java +++ /dev/null @@ -1,361 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.mainactivity.home; - -import android.app.Activity; -import android.graphics.Bitmap; -import android.os.Bundle; -import android.util.DisplayMetrics; -import android.view.Display; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.LinearLayout; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.load.engine.DiskCacheStrategy; - -import java.io.File; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Random; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; -import androidx.recyclerview.widget.GridLayoutManager; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.interfaces.MainActivityFragmentCallbacks; -import code.name.monkey.retromusic.loaders.SongLoader; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.model.smartplaylist.HistoryPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist; -import code.name.monkey.retromusic.model.smartplaylist.MyTopTracksPlaylist; -import code.name.monkey.retromusic.mvp.contract.HomeContract; -import code.name.monkey.retromusic.mvp.presenter.HomePresenter; -import code.name.monkey.retromusic.ui.adapter.CollageSongAdapter; -import code.name.monkey.retromusic.ui.adapter.GenreAdapter; -import code.name.monkey.retromusic.ui.adapter.album.AlbumFullWithAdapter; -import code.name.monkey.retromusic.ui.adapter.artist.ArtistAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsMainActivityFragment; -import code.name.monkey.retromusic.util.Compressor; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.views.CircularImageView; -import code.name.monkey.retromusic.views.MetalRecyclerViewPager; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - -import static code.name.monkey.retromusic.Constants.USER_BANNER; -import static code.name.monkey.retromusic.Constants.USER_PROFILE; - -public class BannerHomeFragment extends AbsMainActivityFragment implements MainActivityFragmentCallbacks, HomeContract.HomeView { - - public static final String TAG = "BannerHomeFragment"; - - @BindView(R.id.image) - @Nullable - ImageView imageView; - - @BindView(R.id.user_image) - CircularImageView userImage; - - @BindView(R.id.recycler_view) - RecyclerView recentArtistRV; - - @BindView(R.id.recent_album) - RecyclerView recentAlbumRV; - - @BindView(R.id.top_artist) - RecyclerView topArtistRV; - - @BindView(R.id.top_album) - MetalRecyclerViewPager topAlbumRV; - - @BindView(R.id.recent_artist_container) - View recentArtistContainer; - - @BindView(R.id.recent_albums_container) - View recentAlbumsContainer; - - @BindView(R.id.top_artist_container) - View topArtistContainer; - - @BindView(R.id.top_albums_container) - View topAlbumContainer; - - @BindView(R.id.genres) - RecyclerView genresRecyclerView; - - @BindView(R.id.genre_container) - LinearLayout genreContainer; - - @BindView(R.id.container) - View container; - - @BindView(R.id.content_container) - View contentContainer; - - @BindView(R.id.suggestion_songs) - RecyclerView suggestionsSongs; - - @BindView(R.id.suggestion_container) - LinearLayout suggestionsContainer; - - private Unbinder unbinder; - private HomePresenter homePresenter; - private CompositeDisposable disposable; - - public static BannerHomeFragment newInstance() { - Bundle args = new Bundle(); - BannerHomeFragment fragment = new BannerHomeFragment(); - fragment.setArguments(args); - return fragment; - } - - private void getTimeOfTheDay(boolean b) { - Calendar c = Calendar.getInstance(); - int timeOfDay = c.get(Calendar.HOUR_OF_DAY); - - String[] images = new String[]{}; - if (timeOfDay >= 0 && timeOfDay < 6) { - images = getResources().getStringArray(R.array.night); - } else if (timeOfDay >= 6 && timeOfDay < 12) { - images = getResources().getStringArray(R.array.morning); - } else if (timeOfDay >= 12 && timeOfDay < 16) { - images = getResources().getStringArray(R.array.after_noon); - } else if (timeOfDay >= 16 && timeOfDay < 20) { - images = getResources().getStringArray(R.array.evening); - } else if (timeOfDay >= 20 && timeOfDay < 24) { - images = getResources().getStringArray(R.array.night); - } - - String day = images[new Random().nextInt(images.length)]; - loadTimeImage(day); - } - - - private void loadTimeImage(String day) { - //noinspection ConstantConditions - if (imageView != null) { - if (PreferenceUtil.getInstance().getBannerImage().isEmpty()) { - Glide.with(getActivity()).load(day) - .asBitmap() - .placeholder(R.drawable.material_design_default) - .diskCacheStrategy(DiskCacheStrategy.SOURCE) - .into(imageView); - } else { - loadBannerFromStorage(); - } - } - } - - private void loadBannerFromStorage() { - //noinspection ConstantConditions - disposable.add(new Compressor(getContext()) - .setQuality(100) - .setCompressFormat(Bitmap.CompressFormat.WEBP) - .compressToBitmapAsFlowable( - new File(PreferenceUtil.getInstance().getBannerImage(), USER_BANNER)) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(imageView::setImageBitmap)); - } - - private void loadImageFromStorage(ImageView imageView) { - //noinspection ConstantConditions - disposable.add(new Compressor(getContext()) - .setMaxHeight(300) - .setMaxWidth(300) - .setQuality(75) - .setCompressFormat(Bitmap.CompressFormat.WEBP) - .compressToBitmapAsFlowable( - new File(PreferenceUtil.getInstance().getProfileImage(), USER_PROFILE)) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(imageView::setImageBitmap, - throwable -> imageView.setImageDrawable(ContextCompat - .getDrawable(getContext(), R.drawable.ic_person_flat)))); - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - disposable = new CompositeDisposable(); - //noinspection ConstantConditions - homePresenter = new HomePresenter(this); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(PreferenceUtil.getInstance().isHomeBanner() ? R.layout.fragment_banner_home : R.layout.fragment_home, - container, false); - unbinder = ButterKnife.bind(this, view); - if (!PreferenceUtil.getInstance().isHomeBanner()) - setStatusbarColorAuto(view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setupToolbar(); - loadImageFromStorage(userImage); - homePresenter.subscribe(); - getTimeOfTheDay(PreferenceUtil.getInstance().isHomeBanner()); - } - - @SuppressWarnings("ConstantConditions") - private void setupToolbar() { - userImage.setOnClickListener(v -> showMainMenu()); - contentContainer.setBackgroundColor(ThemeStore.primaryColor(getMainActivity())); - } - - @OnClick(R.id.searchIcon) - void search() { - NavigationUtil.goToSearch(getMainActivity()); - } - - @Override - public boolean handleBackPress() { - return false; - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - disposable.clear(); - homePresenter.unsubscribe(); - } - - @Override - public void loading() { - - } - - @Override - public void showEmptyView() { - - } - - @Override - public void completed() { - - } - - @Override - public void showData(ArrayList homes) { - //homeAdapter.swapDataSet(homes); - } - - @Override - public void recentArtist(ArrayList artists) { - recentArtistContainer.setVisibility(View.VISIBLE); - recentArtistRV.setLayoutManager(new GridLayoutManager(getMainActivity(), - 1, GridLayoutManager.HORIZONTAL, false)); - ArtistAdapter artistAdapter = new ArtistAdapter(getMainActivity(), artists, - PreferenceUtil.getInstance().getHomeGridStyle(getContext()), false, null); - recentArtistRV.setAdapter(artistAdapter); - } - - @Override - public void recentAlbum(ArrayList albums) { - recentAlbumsContainer.setVisibility(View.VISIBLE); - AlbumFullWithAdapter artistAdapter = new AlbumFullWithAdapter(getMainActivity(), - getDisplayMetrics()); - artistAdapter.swapData(albums); - recentAlbumRV.setAdapter(artistAdapter); - } - - @Override - public void topArtists(ArrayList artists) { - topArtistContainer.setVisibility(View.VISIBLE); - topArtistRV.setLayoutManager(new GridLayoutManager(getMainActivity(), - 1, GridLayoutManager.HORIZONTAL, false)); - ArtistAdapter artistAdapter = new ArtistAdapter(getMainActivity(), artists, - PreferenceUtil.getInstance().getHomeGridStyle(getContext()), false, null); - topArtistRV.setAdapter(artistAdapter); - - } - - @Override - public void topAlbums(ArrayList albums) { - topAlbumContainer.setVisibility(View.VISIBLE); - AlbumFullWithAdapter artistAdapter = new AlbumFullWithAdapter(getMainActivity(), - getDisplayMetrics()); - artistAdapter.swapData(albums); - topAlbumRV.setAdapter(artistAdapter); - } - - @Override - public void suggestions(ArrayList songs) { - if (!songs.isEmpty()) { - suggestionsContainer.setVisibility(View.VISIBLE); - CollageSongAdapter artistAdapter = new CollageSongAdapter(getMainActivity(), songs); - suggestionsSongs.setLayoutManager(RetroUtil.isTablet() ? new GridLayoutManager(getMainActivity(), 2) : new LinearLayoutManager(getMainActivity())); - suggestionsSongs.setAdapter(artistAdapter); - } - } - - @Override - public void playlists(ArrayList playlists) { - - } - - private DisplayMetrics getDisplayMetrics() { - Display display = getMainActivity().getWindowManager().getDefaultDisplay(); - DisplayMetrics metrics = new DisplayMetrics(); - display.getMetrics(metrics); - return metrics; - } - - @Override - public void geners(ArrayList genres) { - genreContainer.setVisibility(View.VISIBLE); - genresRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); - //noinspection ConstantConditions - GenreAdapter genreAdapter = new GenreAdapter(getActivity(), genres, R.layout.item_list); - genresRecyclerView.setAdapter(genreAdapter); - } - - @OnClick({R.id.last_added, R.id.top_played, R.id.action_shuffle, R.id.history, - R.id.user_image}) - void startUserInfo(View view) { - Activity activity = getActivity(); - if (activity != null) { - switch (view.getId()) { - case R.id.action_shuffle: - MusicPlayerRemote.openAndShuffleQueue(SongLoader.Companion.getAllSongs(activity).blockingFirst(), true); - break; - case R.id.last_added: - NavigationUtil.goToPlaylistNew(activity, new LastAddedPlaylist(activity)); - break; - case R.id.top_played: - NavigationUtil.goToPlaylistNew(activity, new MyTopTracksPlaylist(activity)); - break; - case R.id.history: - NavigationUtil.goToPlaylistNew(activity, new HistoryPlaylist(activity)); - break; - case R.id.user_image: - NavigationUtil.goToUserInfo(getActivity()); - break; - } - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/home/BannerHomeFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/home/BannerHomeFragment.kt new file mode 100644 index 00000000..4b56b5b4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/mainactivity/home/BannerHomeFragment.kt @@ -0,0 +1,302 @@ +package code.name.monkey.retromusic.ui.fragments.mainactivity.home + +import android.graphics.Bitmap +import android.os.Bundle +import android.util.DisplayMetrics +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import butterknife.OnClick +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.Constants.USER_BANNER +import code.name.monkey.retromusic.Constants.USER_PROFILE +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.interfaces.MainActivityFragmentCallbacks +import code.name.monkey.retromusic.loaders.SongLoader +import code.name.monkey.retromusic.model.* +import code.name.monkey.retromusic.model.smartplaylist.HistoryPlaylist +import code.name.monkey.retromusic.model.smartplaylist.LastAddedPlaylist +import code.name.monkey.retromusic.model.smartplaylist.MyTopTracksPlaylist +import code.name.monkey.retromusic.mvp.contract.HomeContract +import code.name.monkey.retromusic.mvp.presenter.HomePresenter +import code.name.monkey.retromusic.ui.adapter.CollageSongAdapter +import code.name.monkey.retromusic.ui.adapter.GenreAdapter +import code.name.monkey.retromusic.ui.adapter.album.AlbumFullWithAdapter +import code.name.monkey.retromusic.ui.adapter.artist.ArtistAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsMainActivityFragment +import code.name.monkey.retromusic.util.Compressor +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import code.name.monkey.retromusic.views.CircularImageView +import code.name.monkey.retromusic.views.MetalRecyclerViewPager +import com.bumptech.glide.Glide +import com.bumptech.glide.load.engine.DiskCacheStrategy +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import kotlinx.android.synthetic.main.abs_playlists.* +import java.io.File +import java.util.* + +class BannerHomeFragment : AbsMainActivityFragment(), MainActivityFragmentCallbacks, HomeContract.HomeView { + + + override fun onCreateView(inflater: LayoutInflater, viewGroup: ViewGroup?, + savedInstanceState: Bundle?): View? { + val view = inflater.inflate(if (PreferenceUtil.getInstance().isHomeBanner) R.layout.fragment_banner_home else R.layout.fragment_home, viewGroup, false) + + if (!PreferenceUtil.getInstance().isHomeBanner) + setStatusbarColorAuto(view) + + imageView = view.findViewById(R.id.image) + userImage = view.findViewById(R.id.user_image) + recentArtistRV = view.findViewById(R.id.recycler_view) + recentAlbumRV = view.findViewById(R.id.recent_album) + topArtistRV = view.findViewById(R.id.top_artist) + topAlbumRV = view.findViewById(R.id.top_album) + recentArtistContainer = view.findViewById(R.id.recent_artist_container) + recentAlbumsContainer = view.findViewById(R.id.recent_albums_container) + topArtistContainer = view.findViewById(R.id.top_artist_container) + topAlbumContainer = view.findViewById(R.id.top_albums_container) + genresRecyclerView = view.findViewById(R.id.genres) + genreContainer = view.findViewById(R.id.genre_container) + contentContainer = view.findViewById(R.id.content_container) + container = view.findViewById(R.id.container) + suggestionsSongs = view.findViewById(R.id.suggestion_songs) + suggestionsContainer = view.findViewById(R.id.suggestion_container) + + /* lastAdded.setOnClickListener { + NavigationUtil.goToPlaylistNew(activity!!, LastAddedPlaylist(activity!!)) + } + topPlayed.setOnClickListener { + NavigationUtil.goToPlaylistNew(activity!!, MyTopTracksPlaylist(activity!!)) + } + actionShuffle.setOnClickListener { + MusicPlayerRemote.openAndShuffleQueue(SongLoader.getAllSongs(activity!!).blockingFirst(), true) + } + history.setOnClickListener { + NavigationUtil.goToPlaylistNew(activity!!, HistoryPlaylist(activity!!)) + }*/ + userImage.setOnClickListener { + NavigationUtil.goToUserInfo(activity!!) + } + return view + } + + private var imageView: ImageView? = null + private lateinit var userImage: CircularImageView + private lateinit var recentAlbumRV: MetalRecyclerViewPager + private lateinit var topAlbumRV: MetalRecyclerViewPager + private lateinit var topArtistRV: RecyclerView + private lateinit var genresRecyclerView: RecyclerView + private lateinit var suggestionsSongs: RecyclerView + private lateinit var recentArtistRV: RecyclerView + private lateinit var recentArtistContainer: View + private lateinit var recentAlbumsContainer: View + private lateinit var topArtistContainer: View + private lateinit var topAlbumContainer: View + private lateinit var genreContainer: View + private lateinit var container: View + private lateinit var contentContainer: View + private lateinit var suggestionsContainer: View + private lateinit var homePresenter: HomePresenter + val disposable: CompositeDisposable = CompositeDisposable() + + private val displayMetrics: DisplayMetrics + get() { + val display = mainActivity.windowManager.defaultDisplay + val metrics = DisplayMetrics() + display.getMetrics(metrics) + return metrics + } + + private fun getTimeOfTheDay() { + val c = Calendar.getInstance() + val timeOfDay = c.get(Calendar.HOUR_OF_DAY) + + var images = arrayOf() + if (timeOfDay in 0..5) { + images = resources.getStringArray(R.array.night) + } else if (timeOfDay in 6..11) { + images = resources.getStringArray(R.array.morning) + } else if (timeOfDay in 12..15) { + images = resources.getStringArray(R.array.after_noon) + } else if (timeOfDay in 16..19) { + images = resources.getStringArray(R.array.evening) + } else if (timeOfDay in 20..23) { + images = resources.getStringArray(R.array.night) + } + + val day = images[Random().nextInt(images.size)] + loadTimeImage(day) + } + + + private fun loadTimeImage(day: String) { + + if (imageView != null) { + if (PreferenceUtil.getInstance().bannerImage.isEmpty()) { + Glide.with(activity).load(day) + .asBitmap() + .placeholder(R.drawable.material_design_default) + .diskCacheStrategy(DiskCacheStrategy.SOURCE) + .into(imageView!!) + } else { + loadBannerFromStorage() + } + } + } + + private fun loadBannerFromStorage() { + + disposable.add(Compressor(context!!) + .setQuality(100) + .setCompressFormat(Bitmap.CompressFormat.WEBP) + .compressToBitmapAsFlowable( + File(PreferenceUtil.getInstance().bannerImage, USER_BANNER)) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe { imageView!!.setImageBitmap(it) }) + } + + private fun loadImageFromStorage(imageView: ImageView) { + + disposable.add(Compressor(context!!) + .setMaxHeight(300) + .setMaxWidth(300) + .setQuality(75) + .setCompressFormat(Bitmap.CompressFormat.WEBP) + .compressToBitmapAsFlowable( + File(PreferenceUtil.getInstance().profileImage, USER_PROFILE)) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + imageView.setImageBitmap(it) + }) { + imageView.setImageDrawable(ContextCompat + .getDrawable(context!!, R.drawable.ic_person_flat)) + }) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + homePresenter = HomePresenter(this) + } + + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setupToolbar() + loadImageFromStorage(userImage) + homePresenter.subscribe() + getTimeOfTheDay() + } + + private fun setupToolbar() { + userImage.setOnClickListener { showMainMenu() } + contentContainer.setBackgroundColor(ThemeStore.primaryColor(mainActivity)) + } + + @OnClick(R.id.searchIcon) + internal fun search() { + NavigationUtil.goToSearch(mainActivity) + } + + override fun handleBackPress(): Boolean { + return false + } + + override fun onDestroyView() { + super.onDestroyView() + disposable.clear() + homePresenter.unsubscribe() + } + + override fun loading() { + + } + + override fun showEmptyView() { + + } + + override fun completed() { + + } + + override fun showData(homes: ArrayList) { + //homeAdapter.swapDataSet(homes); + } + + override fun recentArtist(artists: ArrayList) { + recentArtistContainer.visibility = View.VISIBLE + recentArtistRV.layoutManager = GridLayoutManager(mainActivity, 1, GridLayoutManager.HORIZONTAL, false) + val artistAdapter = ArtistAdapter(mainActivity, artists, PreferenceUtil.getInstance().getHomeGridStyle(context!!), false, null) + recentArtistRV.adapter = artistAdapter + } + + override fun recentAlbum(albums: ArrayList) { + recentAlbumsContainer.visibility = View.VISIBLE + val artistAdapter = AlbumFullWithAdapter(mainActivity, + displayMetrics) + artistAdapter.swapData(albums) + recentAlbumRV.adapter = artistAdapter + } + + override fun topArtists(artists: ArrayList) { + topArtistContainer.visibility = View.VISIBLE + topArtistRV.layoutManager = GridLayoutManager(mainActivity, 1, GridLayoutManager.HORIZONTAL, false) + val artistAdapter = ArtistAdapter(mainActivity, artists, PreferenceUtil.getInstance().getHomeGridStyle(context!!), false, null) + topArtistRV.adapter = artistAdapter + + } + + override fun topAlbums(albums: ArrayList) { + topAlbumContainer.visibility = View.VISIBLE + val artistAdapter = AlbumFullWithAdapter(mainActivity, + displayMetrics) + artistAdapter.swapData(albums) + topAlbumRV.adapter = artistAdapter + } + + override fun suggestions(songs: ArrayList) { + if (!songs.isEmpty()) { + suggestionsContainer.visibility = View.VISIBLE + val artistAdapter = CollageSongAdapter(mainActivity, songs) + suggestionsSongs.layoutManager = if (RetroUtil.isTablet()) GridLayoutManager(mainActivity, 2) else LinearLayoutManager(mainActivity) + suggestionsSongs.adapter = artistAdapter + } + } + + override fun playlists(playlists: ArrayList) { + + } + + override fun geners(genres: ArrayList) { + genreContainer.visibility = View.VISIBLE + genresRecyclerView.layoutManager = LinearLayoutManager(context) + + val genreAdapter = GenreAdapter(activity!!, genres, R.layout.item_list) + genresRecyclerView.adapter = genreAdapter + } + + + companion object { + + const val TAG: String = "BannerHomeFragment" + + fun newInstance(): BannerHomeFragment { + val args = Bundle() + val fragment = BannerHomeFragment() + fragment.arguments = args + return fragment + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/PlayerAlbumCoverFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/PlayerAlbumCoverFragment.java deleted file mode 100644 index 280c3e60..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/PlayerAlbumCoverFragment.java +++ /dev/null @@ -1,151 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.transform.CarousalPagerTransformer; -import code.name.monkey.retromusic.transform.ParallaxPagerTransformer; -import code.name.monkey.retromusic.ui.adapter.album.AlbumCoverPagerAdapter; -import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen; -import code.name.monkey.retromusic.ui.fragments.base.AbsMusicServiceFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; - - -public class PlayerAlbumCoverFragment extends AbsMusicServiceFragment implements - ViewPager.OnPageChangeListener { - - public static final String TAG = PlayerAlbumCoverFragment.class.getSimpleName(); - public static final long VISIBILITY_ANIM_DURATION = 300; - @BindView(R.id.player_album_cover_viewpager) - ViewPager viewPager; - private Unbinder unbinder; - private Callbacks callbacks; - private int currentPosition; - private AlbumCoverPagerAdapter.AlbumCoverFragment.ColorReceiver colorReceiver = - new AlbumCoverPagerAdapter.AlbumCoverFragment.ColorReceiver() { - @Override - public void onColorReady(int color, int requestCode) { - if (currentPosition == requestCode) { - notifyColorChange(color); - } - } - }; - - public void removeSlideEffect() { - ParallaxPagerTransformer transformer = new ParallaxPagerTransformer(R.id.player_image); - transformer.setSpeed(0.3f); - viewPager.setPageTransformer(true, transformer); - - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_player_album_cover, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - viewPager.addOnPageChangeListener(this); - - //noinspection ConstantConditions - if (PreferenceUtil.getInstance().carouselEffect() && - !((PreferenceUtil.getInstance().getNowPlayingScreen() == NowPlayingScreen.FULL) || (PreferenceUtil.getInstance().getNowPlayingScreen() == NowPlayingScreen.FIT))) { - viewPager.setClipToPadding(false); - viewPager.setPadding(96, 0, 96, 0); - viewPager.setPageMargin(18); - viewPager.setPageTransformer(false, new CarousalPagerTransformer(getContext())); - } else { - viewPager.setPageTransformer(true, PreferenceUtil.getInstance().getAlbumCoverTransform(getContext())); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - viewPager.removeOnPageChangeListener(this); - unbinder.unbind(); - } - - @Override - public void onServiceConnected() { - updatePlayingQueue(); - } - - @Override - public void onPlayingMetaChanged() { - viewPager.setCurrentItem(MusicPlayerRemote.getPosition()); - } - - @Override - public void onQueueChanged() { - updatePlayingQueue(); - } - - private void updatePlayingQueue() { - viewPager.setAdapter( - new AlbumCoverPagerAdapter(getFragmentManager(), MusicPlayerRemote.getPlayingQueue())); - //noinspection ConstantConditions - viewPager.getAdapter().notifyDataSetChanged(); - viewPager.setCurrentItem(MusicPlayerRemote.getPosition()); - onPageSelected(MusicPlayerRemote.getPosition()); - - } - - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - - } - - @Override - public void onPageSelected(int position) { - currentPosition = position; - if (viewPager.getAdapter() != null) { - ((AlbumCoverPagerAdapter) viewPager.getAdapter()).receiveColor(colorReceiver, position); - } - if (position != MusicPlayerRemote.getPosition()) { - MusicPlayerRemote.playSongAt(position); - } - } - - @Override - public void onPageScrollStateChanged(int state) { - - } - - - private void notifyColorChange(int color) { - if (callbacks != null) { - callbacks.onColorChanged(color); - } - } - - public void setCallbacks(Callbacks listener) { - callbacks = listener; - } - - public void removeEffect() { - viewPager.setPageTransformer(false, null); - } - - - public interface Callbacks { - - void onColorChanged(int color); - - void onFavoriteToggled(); - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/PlayerAlbumCoverFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/PlayerAlbumCoverFragment.kt new file mode 100644 index 00000000..6739497f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/PlayerAlbumCoverFragment.kt @@ -0,0 +1,119 @@ +package code.name.monkey.retromusic.ui.fragments.player + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.viewpager.widget.ViewPager +import butterknife.Unbinder +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.transform.ParallaxPagerTransformer +import code.name.monkey.retromusic.ui.adapter.album.AlbumCoverPagerAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsMusicServiceFragment +import code.name.monkey.retromusic.util.PreferenceUtil +import kotlinx.android.synthetic.main.fragment_player_album_cover.* + + +class PlayerAlbumCoverFragment : AbsMusicServiceFragment(), ViewPager.OnPageChangeListener { + private var callbacks: Callbacks? = null + private var currentPosition: Int = 0 + private val colorReceiver = object : AlbumCoverPagerAdapter.AlbumCoverFragment.ColorReceiver { + override fun onColorReady(color: Int, request: Int) { + if (currentPosition == request) { + notifyColorChange(color) + } + } + } + + fun removeSlideEffect() { + val transformer = ParallaxPagerTransformer(R.id.player_image) + transformer.setSpeed(0.3f) + viewPager.setPageTransformer(true, transformer) + + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_player_album_cover, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + viewPager.addOnPageChangeListener(this) + viewPager.setPageTransformer(true, PreferenceUtil.getInstance().getAlbumCoverTransform(context)) + } + + override fun onDestroyView() { + super.onDestroyView() + viewPager.removeOnPageChangeListener(this) + } + + override fun onServiceConnected() { + updatePlayingQueue() + } + + override fun onPlayingMetaChanged() { + viewPager.currentItem = MusicPlayerRemote.position + } + + override fun onQueueChanged() { + updatePlayingQueue() + } + + private fun updatePlayingQueue() { + viewPager.apply { + adapter = AlbumCoverPagerAdapter(fragmentManager!!, MusicPlayerRemote.playingQueue) + viewPager.adapter!!.notifyDataSetChanged() + viewPager.currentItem = MusicPlayerRemote.position + onPageSelected(MusicPlayerRemote.position) + } + } + + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { + + } + + override fun onPageSelected(position: Int) { + currentPosition = position + if (viewPager.adapter != null) { + (viewPager.adapter as AlbumCoverPagerAdapter).receiveColor(colorReceiver, position) + } + if (position != MusicPlayerRemote.position) { + MusicPlayerRemote.playSongAt(position) + } + } + + override fun onPageScrollStateChanged(state: Int) { + + } + + + private fun notifyColorChange(color: Int) { + if (callbacks != null) { + callbacks!!.onColorChanged(color) + } + } + + fun setCallbacks(listener: Callbacks) { + callbacks = listener + } + + fun removeEffect() { + viewPager.setPageTransformer(false, null) + } + + + interface Callbacks { + + fun onColorChanged(color: Int) + + fun onFavoriteToggled() + + } + + companion object { + val TAG: String = PlayerAlbumCoverFragment::class.java.simpleName + const val VISIBILITY_ANIM_DURATION: Long = 300 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptiveFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptiveFragment.java deleted file mode 100644 index 28c4cbda..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptiveFragment.java +++ /dev/null @@ -1,160 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.adaptive; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment.Callbacks; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; - -public class AdaptiveFragment extends AbsPlayerFragment implements Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - private int lastColor; - private AdaptivePlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - - public static PlayerFragment newInstance() { - Bundle args = new Bundle(); - PlayerFragment fragment = new PlayerFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_adaptive_player, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = - (AdaptivePlaybackControlsFragment) getChildFragmentManager() - .findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = - (PlayerAlbumCoverFragment) getChildFragmentManager() - .findFragmentById(R.id.player_album_cover_fragment); - playerAlbumCoverFragment.setCallbacks(this); - playerAlbumCoverFragment.removeSlideEffect(); - } - - private void setUpPlayerToolbar() { - int primaryColor = ATHUtil.resolveColor(getContext(), R.attr.iconColor); - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, primaryColor, getActivity()); - toolbar.setTitleTextColor(primaryColor); - toolbar.setSubtitleTextColor(ThemeStore.textColorSecondary(getContext())); - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - updateSong(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - toolbar.setTitle(song.title); - toolbar.setSubtitle(song.artistName); - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - updateSong(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptiveFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptiveFragment.kt new file mode 100644 index 00000000..eaa45107 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptiveFragment.kt @@ -0,0 +1,106 @@ +package code.name.monkey.retromusic.ui.fragments.player.adaptive + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment +import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment + +class AdaptiveFragment : AbsPlayerFragment(), PlayerAlbumCoverFragment.Callbacks { + private var lastColor: Int = 0 + lateinit var playbackControlsFragment: AdaptivePlaybackControlsFragment + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_adaptive_player, container, false); + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + toolbar = view.findViewById(R.id.toolbar) + setUpSubFragments() + setUpPlayerToolbar() + } + + private fun setUpSubFragments() { + playbackControlsFragment = childFragmentManager.findFragmentById(R.id.playback_controls_fragment) as AdaptivePlaybackControlsFragment + val playerAlbumCoverFragment = childFragmentManager.findFragmentById(R.id.player_album_cover_fragment) as PlayerAlbumCoverFragment + playerAlbumCoverFragment.setCallbacks(this) + playerAlbumCoverFragment.removeSlideEffect() + } + + private fun setUpPlayerToolbar() { + val primaryColor = ATHUtil.resolveColor(context, R.attr.iconColor) + /*toolbar!!.apply { + inflateMenu(R.menu.menu_player) + setNavigationOnClickListener { activity!!.onBackPressed() } + ToolbarContentTintHelper.colorizeToolbar(this, primaryColor, activity) + setTitleTextColor(primaryColor) + setSubtitleTextColor(ThemeStore.textColorSecondary(context!!)) + }.setOnMenuItemClickListener(this)*/ + } + + override fun onServiceConnected() { + super.onServiceConnected() + updateIsFavorite() + updateSong() + } + + override fun onPlayingMetaChanged() { + updateIsFavorite() + updateSong() + } + + private fun updateSong() { + val song = MusicPlayerRemote.currentSong + /*toolbar!!.apply { + title = song.title + subtitle = song.artistName + }*/ + } + + override fun toggleFavorite(song: Song) { + super.toggleFavorite(song) + if (song.id == MusicPlayerRemote.currentSong.id) { + updateIsFavorite() + } + } + + override fun onFavoriteToggled() { + toggleFavorite(MusicPlayerRemote.currentSong) + } + + override fun onColorChanged(color: Int) { + playbackControlsFragment.setDark(color) + lastColor = color + callbacks!!.onPaletteColorChanged() + //ToolbarContentTintHelper.colorizeToolbar(toolbar, ATHUtil.resolveColor(context, R.attr.iconColor), activity) + } + + override fun onShow() { + playbackControlsFragment.show() + } + + override fun onHide() { + playbackControlsFragment.hide() + onBackPressed() + } + + override fun onBackPressed(): Boolean { + return false + } + + override fun toolbarIconColor(): Int { + return ATHUtil.resolveColor(context, R.attr.iconColor) + } + + override val paletteColor: Int + get() = lastColor + +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptivePlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptivePlaybackControlsFragment.java deleted file mode 100644 index e1be14a7..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptivePlaybackControlsFragment.java +++ /dev/null @@ -1,285 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.adaptive; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.PlayPauseDrawable; - -public class AdaptivePlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - - private Unbinder unbinder; - private PlayPauseDrawable playPauseDrawable; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater - .inflate(R.layout.fragment_adaptive_player_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - hideVolumeIfAvailable(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - - if (ColorUtil.isColorLight(ATHUtil.resolveColor(getContext(), android.R.attr.windowBackground))) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - updatePlayPauseColor(); - - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), ColorUtil.isColorLight(dark)), false); - TintHelper.setTintAuto(playPauseFab, dark, true); - TintHelper.setTintAuto(progressSlider, dark, false); - } - - private void updatePlayPauseColor() { - //playPauseButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - - @Override - protected void show() { - //Ignore - } - - @Override - protected void hide() { - //Ignore - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(playPauseFab); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } - - private void hideVolumeIfAvailable() { - volumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptivePlaybackControlsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptivePlaybackControlsFragment.kt new file mode 100644 index 00000000..4ef44759 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/adaptive/AdaptivePlaybackControlsFragment.kt @@ -0,0 +1,209 @@ +package code.name.monkey.retromusic.ui.fragments.player.adaptive + +import android.animation.ObjectAnimator +import android.graphics.PorterDuff +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.animation.LinearInterpolator +import android.widget.SeekBar +import code.name.monkey.appthemehelper.util.ATHUtil +import code.name.monkey.appthemehelper.util.ColorUtil +import code.name.monkey.appthemehelper.util.MaterialValueHelper +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper +import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler +import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener +import code.name.monkey.retromusic.service.MusicService +import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.views.PlayPauseDrawable + +class AdaptivePlaybackControlsFragment : AbsPlayerControlsFragment() { + + private val playPauseDrawable: PlayPauseDrawable? = null + private var lastPlaybackControlsColor: Int = 0 + private var lastDisabledPlaybackControlsColor: Int = 0 + private var progressViewUpdateHelper: MusicProgressViewUpdateHelper? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + progressViewUpdateHelper = MusicProgressViewUpdateHelper(this) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_adaptive_player_playback_controls, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setUpMusicControllers() + hideVolumeIfAvailable() + + playPauseFab!!.setOnClickListener { + if (MusicPlayerRemote.isPlaying) { + MusicPlayerRemote.pauseSong() + } else { + MusicPlayerRemote.resumePlaying() + } + showBouceAnimation(playPauseFab!!) + } + } + + override fun onResume() { + super.onResume() + progressViewUpdateHelper!!.start() + } + + override fun onPause() { + super.onPause() + progressViewUpdateHelper!!.stop() + } + + override fun onServiceConnected() { + updatePlayPauseDrawableState() + updateRepeatState() + updateShuffleState() + } + + override fun onPlayStateChanged() { + updatePlayPauseDrawableState() + } + + override fun onRepeatModeChanged() { + updateRepeatState() + } + + override fun onShuffleModeChanged() { + updateShuffleState() + } + + override fun setDark(color: Int) { + if (ColorUtil.isColorLight(ATHUtil.resolveColor(context, android.R.attr.windowBackground))) { + lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(activity, true) + lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(activity, true) + } else { + lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(activity, false) + lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(activity, false) + } + + updateRepeatState() + updateShuffleState() + updatePrevNextColor() + updatePlayPauseColor() + + TintHelper.setTintAuto(playPauseFab!!, MaterialValueHelper.getPrimaryTextColor(context, ColorUtil.isColorLight(color)), false) + TintHelper.setTintAuto(playPauseFab!!, color, true) + TintHelper.setTintAuto(progressSlider!!, color, false) + } + + private fun updatePlayPauseColor() { + //playPauseButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); + } + + private fun setUpPlayPauseFab() { + playPauseFab!!.setOnClickListener(PlayPauseButtonOnClickHandler()) + } + + protected fun updatePlayPauseDrawableState() { + if (MusicPlayerRemote.isPlaying) { + playPauseFab!!.setImageResource(R.drawable.ic_pause_white_24dp) + } else { + playPauseFab!!.setImageResource(R.drawable.ic_play_arrow_white_24dp) + } + } + + + private fun setUpMusicControllers() { + setUpPlayPauseFab() + setUpPrevNext() + setUpRepeatButton() + setUpShuffleButton() + setUpProgressSlider() + } + + private fun setUpPrevNext() { + updatePrevNextColor() + nextButton!!.setOnClickListener { MusicPlayerRemote.playNextSong() } + prevButton!!.setOnClickListener { MusicPlayerRemote.back() } + } + + private fun updatePrevNextColor() { + nextButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + prevButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + + private fun setUpShuffleButton() { + shuffleButton!!.setOnClickListener { MusicPlayerRemote.toggleShuffleMode() } + } + + override fun updateShuffleState() { + when (MusicPlayerRemote.shuffleMode) { + MusicService.SHUFFLE_MODE_SHUFFLE -> shuffleButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + else -> shuffleButton!!.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + } + + private fun setUpRepeatButton() { + repeatButton!!.setOnClickListener { MusicPlayerRemote.cycleRepeatMode() } + } + + override fun updateRepeatState() { + when (MusicPlayerRemote.repeatMode) { + MusicService.REPEAT_MODE_NONE -> { + repeatButton!!.setImageResource(R.drawable.ic_repeat_white_24dp) + repeatButton!!.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + MusicService.REPEAT_MODE_ALL -> { + repeatButton!!.setImageResource(R.drawable.ic_repeat_white_24dp) + repeatButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + MusicService.REPEAT_MODE_THIS -> { + repeatButton!!.setImageResource(R.drawable.ic_repeat_one_white_24dp) + repeatButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + } + } + + + public override fun show() { + //Ignore + } + + public override fun hide() { + //Ignore + } + + override fun setUpProgressSlider() { + progressSlider!!.setOnSeekBarChangeListener(object : SimpleOnSeekbarChangeListener() { + override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { + if (fromUser) { + MusicPlayerRemote.seekTo(progress) + onUpdateProgressViews(MusicPlayerRemote.songProgressMillis, + MusicPlayerRemote.songDurationMillis) + } + } + }) + } + + override fun onUpdateProgressViews(progress: Int, total: Int) { + progressSlider!!.max = total + + val animator = ObjectAnimator.ofInt(progressSlider, "progress", progress) + animator.duration = 1500 + animator.interpolator = LinearInterpolator() + animator.start() + + songTotalTime!!.text = MusicUtil.getReadableDurationString(total.toLong()) + songCurrentProgress!!.text = MusicUtil.getReadableDurationString(progress.toLong()) + } + + private fun hideVolumeIfAvailable() { + volumeContainer!!.visibility = if (PreferenceUtil.getInstance().volumeToggle) View.VISIBLE else View.GONE + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlaybackControlsFragment.java deleted file mode 100644 index eec9433c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlaybackControlsFragment.java +++ /dev/null @@ -1,299 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.blur; - -import android.animation.ObjectAnimator; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import androidx.core.content.ContextCompat; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.VolumeFragment; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - - -public class BlurPlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView songTitle; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.volume_fragment_container) - View mVolumeContainer; - - private Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, - @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_blur_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - mVolumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - - VolumeFragment mVolumeFragment = (VolumeFragment) getChildFragmentManager().findFragmentById(R.id.volume_fragment); - if (mVolumeFragment != null) { - mVolumeFragment.tintWhiteColor(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - songTitle.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - lastPlaybackControlsColor = Color.WHITE; - lastDisabledPlaybackControlsColor = ContextCompat.getColor(getContext(), R.color.md_grey_500); - - songTitle.setTextColor(lastPlaybackControlsColor); - text.setTextColor(lastDisabledPlaybackControlsColor); - - setProgressBarColor(); - - songCurrentProgress.setTextColor(lastPlaybackControlsColor); - songTotalTime.setTextColor(lastPlaybackControlsColor); - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - } - - private void setProgressBarColor() { - TintHelper.setTintAuto(progressSlider, Color.WHITE, false); - } - - private void setUpPlayPauseFab() { - TintHelper.setTintAuto(playPauseFab, Color.WHITE, true); - TintHelper.setTintAuto(playPauseFab, Color.BLACK, false); - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlaybackControlsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlaybackControlsFragment.kt new file mode 100644 index 00000000..f643ad47 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlaybackControlsFragment.kt @@ -0,0 +1,231 @@ +package code.name.monkey.retromusic.ui.fragments.player.blur + +import android.animation.ObjectAnimator +import android.graphics.Color +import android.graphics.PorterDuff +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.animation.DecelerateInterpolator +import android.view.animation.LinearInterpolator +import android.widget.SeekBar +import android.widget.TextView +import androidx.appcompat.widget.AppCompatTextView +import androidx.core.content.ContextCompat +import butterknife.BindView +import butterknife.ButterKnife +import butterknife.Unbinder +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper +import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler +import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener +import code.name.monkey.retromusic.service.MusicService +import code.name.monkey.retromusic.ui.fragments.VolumeFragment +import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.PreferenceUtil + + +class BlurPlaybackControlsFragment : AbsPlayerControlsFragment() { + + lateinit var songTitle: AppCompatTextView + lateinit var text: TextView + + private var lastPlaybackControlsColor: Int = 0 + private var lastDisabledPlaybackControlsColor: Int = 0 + private var progressViewUpdateHelper: MusicProgressViewUpdateHelper? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + progressViewUpdateHelper = MusicProgressViewUpdateHelper(this) + } + + override fun onCreateView(inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle?): View? { + val view = inflater.inflate(R.layout.fragment_blur_playback_controls, container, false) + songTitle = view.findViewById(R.id.title) + text = view.findViewById(R.id.text) + return view + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setUpMusicControllers() + + volumeContainer!!.visibility = if (PreferenceUtil.getInstance().volumeToggle) View.VISIBLE else View.GONE + val mVolumeFragment = childFragmentManager.findFragmentById(R.id.volume_fragment) as VolumeFragment + mVolumeFragment.tintWhiteColor() + } + + private fun updateSong() { + val song = MusicPlayerRemote.currentSong + songTitle.text = song.title + text.text = song.artistName + } + + override fun onResume() { + super.onResume() + progressViewUpdateHelper!!.start() + } + + override fun onPause() { + super.onPause() + progressViewUpdateHelper!!.stop() + } + + override fun onServiceConnected() { + updatePlayPauseDrawableState() + updateRepeatState() + updateShuffleState() + updateSong() + } + + override fun onPlayingMetaChanged() { + super.onPlayingMetaChanged() + updateSong() + } + + override fun onPlayStateChanged() { + updatePlayPauseDrawableState() + } + + override fun onRepeatModeChanged() { + updateRepeatState() + } + + override fun onShuffleModeChanged() { + updateShuffleState() + } + + override fun setDark(color: Int) { + lastPlaybackControlsColor = Color.WHITE + lastDisabledPlaybackControlsColor = ContextCompat.getColor(context!!, R.color.md_grey_500) + + songTitle.setTextColor(lastPlaybackControlsColor) + text.setTextColor(lastDisabledPlaybackControlsColor) + + setProgressBarColor() + + songCurrentProgress!!.setTextColor(lastPlaybackControlsColor) + songTotalTime!!.setTextColor(lastPlaybackControlsColor) + + updateRepeatState() + updateShuffleState() + updatePrevNextColor() + } + + private fun setProgressBarColor() { + TintHelper.setTintAuto(progressSlider!!, Color.WHITE, false) + } + + private fun setUpPlayPauseFab() { + TintHelper.setTintAuto(playPauseFab!!, Color.WHITE, true) + TintHelper.setTintAuto(playPauseFab!!, Color.BLACK, false) + playPauseFab!!.setOnClickListener(PlayPauseButtonOnClickHandler()) + } + + protected fun updatePlayPauseDrawableState() { + if (MusicPlayerRemote.isPlaying) { + playPauseFab!!.setImageResource(R.drawable.ic_pause_white_24dp) + } else { + playPauseFab!!.setImageResource(R.drawable.ic_play_arrow_white_24dp) + } + } + + + private fun setUpMusicControllers() { + setUpPlayPauseFab() + setUpPrevNext() + setUpRepeatButton() + setUpShuffleButton() + setUpProgressSlider() + } + + private fun setUpPrevNext() { + updatePrevNextColor() + nextButton!!.setOnClickListener { MusicPlayerRemote.playNextSong() } + prevButton!!.setOnClickListener { MusicPlayerRemote.back() } + } + + private fun updatePrevNextColor() { + nextButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + prevButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + + private fun setUpShuffleButton() { + shuffleButton!!.setOnClickListener { MusicPlayerRemote.toggleShuffleMode() } + } + + override fun updateShuffleState() { + when (MusicPlayerRemote.shuffleMode) { + MusicService.SHUFFLE_MODE_SHUFFLE -> shuffleButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + else -> shuffleButton!!.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + } + + private fun setUpRepeatButton() { + repeatButton!!.setOnClickListener { MusicPlayerRemote.cycleRepeatMode() } + } + + override fun updateRepeatState() { + when (MusicPlayerRemote.repeatMode) { + MusicService.REPEAT_MODE_NONE -> { + repeatButton!!.setImageResource(R.drawable.ic_repeat_white_24dp) + repeatButton!!.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + MusicService.REPEAT_MODE_ALL -> { + repeatButton!!.setImageResource(R.drawable.ic_repeat_white_24dp) + repeatButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + MusicService.REPEAT_MODE_THIS -> { + repeatButton!!.setImageResource(R.drawable.ic_repeat_one_white_24dp) + repeatButton!!.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN) + } + } + } + + + override fun show() { + playPauseFab!!.animate() + .scaleX(1f) + .scaleY(1f) + .rotation(360f) + .setInterpolator(DecelerateInterpolator()) + .start() + } + + override fun hide() { + if (playPauseFab != null) { + playPauseFab!!.scaleX = 0f + playPauseFab!!.scaleY = 0f + playPauseFab!!.rotation = 0f + } + } + + override fun setUpProgressSlider() { + progressSlider!!.setOnSeekBarChangeListener(object : SimpleOnSeekbarChangeListener() { + override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { + if (fromUser) { + MusicPlayerRemote.seekTo(progress) + onUpdateProgressViews(MusicPlayerRemote.songProgressMillis, MusicPlayerRemote.songDurationMillis) + } + } + }) + } + + override fun onUpdateProgressViews(progress: Int, total: Int) { + progressSlider!!.max = total + + val animator = ObjectAnimator.ofInt(progressSlider, "progress", progress) + animator.duration = 1500 + animator.interpolator = LinearInterpolator() + animator.start() + + songTotalTime!!.text = MusicUtil.getReadableDurationString(total.toLong()) + songCurrentProgress!!.text = MusicUtil.getReadableDurationString(progress.toLong()) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlayerFragment.java deleted file mode 100644 index 01f6f108..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlayerFragment.java +++ /dev/null @@ -1,271 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.blur; - -import android.app.Activity; -import android.graphics.Color; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import com.bumptech.glide.Glide; -import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator; -import com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.BlurTransformation; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.song.PlayingQueueAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; - -/** - * @author Hemanth S (h4h13). - */ - -public class BlurPlayerFragment extends AbsPlayerFragment implements PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @BindView(R.id.toolbar_container) - View toolbarContainer; - - @BindView(R.id.gradient_background) - ImageView colorBackground; - - @Nullable - @BindView(R.id.recycler_view) - RecyclerView recyclerView; - - private int lastColor; - private BlurPlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - - private PlayingQueueAdapter playingQueueAdapter; - private LinearLayoutManager layoutManager; - - public static PlayerFragment newInstance() { - Bundle args = new Bundle(); - PlayerFragment fragment = new PlayerFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return Color.WHITE; - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - public void onDestroyView() { - if (recyclerView != null) { - recyclerView.setItemAnimator(null); - recyclerView.setAdapter(null); - recyclerView = null; - } - playingQueueAdapter = null; - layoutManager = null; - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_blur, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = (BlurPlaybackControlsFragment) getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = - (PlayerAlbumCoverFragment) getChildFragmentManager() - .findFragmentById(R.id.player_album_cover_fragment); - if (playerAlbumCoverFragment != null) { - playerAlbumCoverFragment.setCallbacks(this); - } - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - //noinspection ConstantConditions - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - } - - private void updateBlur() { - Activity activity = getActivity(); - if (activity == null) { - return; - } - - int blurAmount = PreferenceManager.getDefaultSharedPreferences(getContext()) - .getInt("new_blur_amount", 25); - - colorBackground.clearColorFilter(); - - SongGlideRequest.Builder.from(Glide.with(activity), MusicPlayerRemote.getCurrentSong()) - .checkIgnoreMediaStore(activity) - .generatePalette(activity) - .build() - .override(320, 480) - .transform(new BlurTransformation.Builder(getActivity()).blurRadius(blurAmount).build()) - .into(new RetroMusicColoredTarget(colorBackground) { - @Override - public void onColorReady(int color) { - if (color == getDefaultFooterColor()) { - colorBackground.setColorFilter(color); - } - } - }); - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - updateBlur(); - setUpRecyclerView(); - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - updateBlur(); - updateQueuePosition(); - } - - private void setUpRecyclerView() { - if (recyclerView != null) { - final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator(); - - playingQueueAdapter = new PlayingQueueAdapter( - (AppCompatActivity) getActivity(), - MusicPlayerRemote.getPlayingQueue(), - MusicPlayerRemote.getPosition(), - R.layout.item_song, Color.WHITE); - layoutManager = new LinearLayoutManager(getContext()); - - recyclerView.setLayoutManager(layoutManager); - recyclerView.setAdapter(playingQueueAdapter); - recyclerView.setItemAnimator(animator); - layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); - } - } - - @Override - public void onQueueChanged() { - updateQueue(); - updateCurrentSong(); - } - - @Override - public void onMediaStoreChanged() { - updateQueue(); - updateCurrentSong(); - } - - @SuppressWarnings("ConstantConditions") - private void updateCurrentSong() { - } - - private void updateQueuePosition() { - if (playingQueueAdapter != null) { - playingQueueAdapter.setCurrent(MusicPlayerRemote.getPosition()); - // if (slidingUpPanelLayout.getPanelState() == SlidingUpPanelLayout.PanelState.COLLAPSED) { - resetToCurrentPosition(); - //} - } - } - - private void updateQueue() { - if (playingQueueAdapter != null) { - playingQueueAdapter - .swapDataSet(MusicPlayerRemote.getPlayingQueue(), MusicPlayerRemote.getPosition()); - resetToCurrentPosition(); - } - } - - private void resetToCurrentPosition() { - if (recyclerView != null) { - recyclerView.stopScroll(); - layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlayerFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlayerFragment.kt new file mode 100644 index 00000000..a29a82c3 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/blur/BlurPlayerFragment.kt @@ -0,0 +1,198 @@ +package code.name.monkey.retromusic.ui.fragments.player.blur + +import android.graphics.Color +import android.os.Bundle +import android.preference.PreferenceManager +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import androidx.appcompat.app.AppCompatActivity +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.BlurTransformation +import code.name.monkey.retromusic.glide.RetroMusicColoredTarget +import code.name.monkey.retromusic.glide.SongGlideRequest +import code.name.monkey.retromusic.helper.MusicPlayerRemote +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.song.PlayingQueueAdapter +import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment +import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment +import com.bumptech.glide.Glide +import com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator + +class BlurPlayerFragment : AbsPlayerFragment() { + lateinit var playbackControlsFragment: BlurPlaybackControlsFragment + + private var colorBackground: ImageView? = null + private var lastColor: Int = 0 + private var playingQueueAdapter: PlayingQueueAdapter? = null + private var layoutManager: LinearLayoutManager? = null + private var recyclerView: RecyclerView? = null + + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_blur, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + setUpSubFragments() + setUpPlayerToolbar() + } + + private fun setUpSubFragments() { + playbackControlsFragment = childFragmentManager.findFragmentById(R.id.playback_controls_fragment) as BlurPlaybackControlsFragment + val playerAlbumCoverFragment = childFragmentManager.findFragmentById(R.id.player_album_cover_fragment) as PlayerAlbumCoverFragment + playerAlbumCoverFragment.setCallbacks(this) + } + + private fun setUpPlayerToolbar() { + toolbar!!.apply { + inflateMenu(R.menu.menu_player) + setNavigationOnClickListener { activity!!.onBackPressed() } + ToolbarContentTintHelper.colorizeToolbar(this, Color.WHITE, activity) + }.setOnMenuItemClickListener(this) + } + + override fun onFavoriteToggled() { + toggleFavorite(MusicPlayerRemote.currentSong) + } + + override fun onColorChanged(color: Int) { + playbackControlsFragment.setDark(color) + lastColor = color + callbacks!!.onPaletteColorChanged() + ToolbarContentTintHelper.colorizeToolbar(toolbar!!, Color.WHITE, activity) + } + + override fun toggleFavorite(song: Song) { + super.toggleFavorite(song) + if (song.id == MusicPlayerRemote.currentSong.id) { + updateIsFavorite() + } + } + + override fun onShow() { + + } + + override fun onHide() { + + } + + override fun onBackPressed(): Boolean { + return false + } + + override fun toolbarIconColor(): Int { + return Color.WHITE + } + + override val paletteColor: Int + get() = lastColor + + override fun onDestroyView() { + recyclerView!!.apply { + itemAnimator = null + adapter = null + } + playingQueueAdapter = null + layoutManager = null + super.onDestroyView() + } + + private fun updateBlur() { + val activity = activity ?: return + + val blurAmount = PreferenceManager.getDefaultSharedPreferences(context).getInt("new_blur_amount", 25) + + colorBackground!!.clearColorFilter() + + SongGlideRequest.Builder.from(Glide.with(activity), MusicPlayerRemote.currentSong) + .checkIgnoreMediaStore(activity) + .generatePalette(activity) + .build() + .override(320, 480) + .transform(BlurTransformation.Builder(getActivity()!!).blurRadius(blurAmount.toFloat()).build()) + .into(object : RetroMusicColoredTarget(colorBackground!!) { + override fun onColorReady(color: Int) { + if (color == defaultFooterColor) { + colorBackground!!.setColorFilter(color) + } + } + }) + } + + override fun onServiceConnected() { + updateIsFavorite() + updateBlur() + setUpRecyclerView() + } + + override fun onPlayingMetaChanged() { + updateIsFavorite() + updateBlur() + updateQueuePosition() + } + + private fun setUpRecyclerView() { + if (recyclerView != null) { + val animator = RefactoredDefaultItemAnimator() + + playingQueueAdapter = PlayingQueueAdapter((activity as AppCompatActivity), + MusicPlayerRemote.playingQueue, + MusicPlayerRemote.position, + R.layout.item_song, + Color.WHITE) + layoutManager = LinearLayoutManager(context) + + recyclerView!!.apply { + layoutManager = layoutManager + adapter = playingQueueAdapter + itemAnimator = animator + } + layoutManager!!.scrollToPositionWithOffset(MusicPlayerRemote.position + 1, 0) + } + } + + override fun onQueueChanged() { + updateQueue() + updateCurrentSong() + } + + override fun onMediaStoreChanged() { + updateQueue() + updateCurrentSong() + } + + private fun updateCurrentSong() {} + + private fun updateQueuePosition() { + + playingQueueAdapter!!.apply { + setCurrent(MusicPlayerRemote.position) + resetToCurrentPosition() + } + + } + + private fun updateQueue() { + playingQueueAdapter!!.apply { + swapDataSet(MusicPlayerRemote.playingQueue, MusicPlayerRemote.position) + resetToCurrentPosition() + } + + } + + private fun resetToCurrentPosition() { + recyclerView!!.apply { + stopScroll() + } + layoutManager!!.scrollToPositionWithOffset(MusicPlayerRemote.position + 1, 0) + } +} + diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/card/CardFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/card/CardFragment.java deleted file mode 100644 index 0a1e9e25..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/card/CardFragment.java +++ /dev/null @@ -1,281 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.card; - -import android.graphics.Color; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator; -import com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator; -import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager; -import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.song.PlayingQueueAdapter; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; - -public class CardFragment extends AbsPlayerFragment implements PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @Nullable - @BindView(R.id.recycler_view) - - RecyclerView recyclerView; - @Nullable - - @BindView(R.id.title) - TextView title; - - private RecyclerView.Adapter wrappedAdapter; - private RecyclerViewDragDropManager recyclerViewDragDropManager; - private PlayingQueueAdapter playingQueueAdapter; - private LinearLayoutManager layoutManager; - private int lastColor; - private CardPlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - - public static PlayerFragment newInstance() { - Bundle args = new Bundle(); - PlayerFragment fragment = new PlayerFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public void onResume() { - super.onResume(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return Color.WHITE; - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - - if (title != null && playingQueueAdapter != null) { - if (ColorUtil.isColorLight(color)) { - title.setTextColor(Color.BLACK); - playingQueueAdapter.usePalette(false); - } else { - title.setTextColor(Color.WHITE); - playingQueueAdapter.usePalette(true); - } - } - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - if (recyclerViewDragDropManager != null) { - recyclerViewDragDropManager.release(); - recyclerViewDragDropManager = null; - } - - if (recyclerView != null) { - recyclerView.setItemAnimator(null); - recyclerView.setAdapter(null); - recyclerView = null; - } - - if (wrappedAdapter != null) { - WrapperAdapterUtils.releaseAll(wrappedAdapter); - wrappedAdapter = null; - } - playingQueueAdapter = null; - layoutManager = null; - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_card_player, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - setUpRecyclerView(); - } - - private void setUpSubFragments() { - playbackControlsFragment = - (CardPlaybackControlsFragment) getChildFragmentManager() - .findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) getChildFragmentManager() - .findFragmentById(R.id.player_album_cover_fragment); - playerAlbumCoverFragment.setCallbacks(this); - playerAlbumCoverFragment.removeSlideEffect(); - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - //updateLyrics(); - setUpRecyclerView(); - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - //updateLyrics(); - updateQueuePosition(); - } - - private void setUpRecyclerView() { - if (recyclerView != null) { - recyclerViewDragDropManager = new RecyclerViewDragDropManager(); - final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator(); - - playingQueueAdapter = new PlayingQueueAdapter( - (AppCompatActivity) getActivity(), - MusicPlayerRemote.getPlayingQueue(), - MusicPlayerRemote.getPosition(), - R.layout.item_song); - wrappedAdapter = recyclerViewDragDropManager.createWrappedAdapter(playingQueueAdapter); - - layoutManager = new LinearLayoutManager(getContext()); - - recyclerView.setLayoutManager(layoutManager); - recyclerView.setAdapter(wrappedAdapter); - recyclerView.setItemAnimator(animator); - recyclerViewDragDropManager.attachRecyclerView(recyclerView); - layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); - } - } - - @Override - public void onQueueChanged() { - updateQueue(); - updateCurrentSong(); - } - - @Override - public void onMediaStoreChanged() { - updateQueue(); - updateCurrentSong(); - } - - @SuppressWarnings("ConstantConditions") - private void updateCurrentSong() { - } - - private void updateQueuePosition() { - if (playingQueueAdapter != null) { - playingQueueAdapter.setCurrent(MusicPlayerRemote.getPosition()); - } - // if (slidingUpPanelLayout.getPanelState() == SlidingUpPanelLayout.PanelState.COLLAPSED) { - resetToCurrentPosition(); - //} - } - - private void updateQueue() { - if (playingQueueAdapter != null) { - playingQueueAdapter.swapDataSet(MusicPlayerRemote.getPlayingQueue(), - MusicPlayerRemote.getPosition()); - resetToCurrentPosition(); - } - } - - private void resetToCurrentPosition() { - if (recyclerView != null) { - recyclerView.stopScroll(); - layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.getPosition() + 1, 0); - } - - } - - @Override - public void onPause() { - if (recyclerViewDragDropManager != null) { - recyclerViewDragDropManager.cancelDrag(); - } - - super.onPause(); - } - - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/card/CardPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/card/CardPlaybackControlsFragment.java deleted file mode 100644 index 0abcaff0..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/card/CardPlaybackControlsFragment.java +++ /dev/null @@ -1,334 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.card; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import androidx.cardview.widget.CardView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.PlayPauseDrawable; - -public class CardPlaybackControlsFragment extends AbsPlayerControlsFragment { - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - @BindView(R.id.menu) - View menuView; - - @BindView(R.id.image_text_container) - CardView colorContainer; - - @BindView(R.id.image) - ImageView playImageView; - - @BindView(R.id.playback_controls) - View playbackControls; - - private Unbinder unbinder; - private PlayPauseDrawable playPauseDrawable; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_card_player_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - hideVolumeIfAvailable(); - - setupControls(); - } - - private void setupControls() { - playImageView.setImageResource(R.drawable.ic_play_circle_filled_white_24dp); - //noinspection ConstantConditions - int iconPadding = getActivity().getResources().getDimensionPixelSize(R.dimen.list_item_image_icon_padding); - playImageView.setPadding(iconPadding, iconPadding, iconPadding, iconPadding); - - menuView.setVisibility(View.GONE); - - int primaryColor = ThemeStore.primaryColor(getContext()); - playbackControls.setBackgroundColor(primaryColor); - colorContainer.setCardBackgroundColor(primaryColor); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - playImageView.setColorFilter(dark, PorterDuff.Mode.SRC_IN); - if (ColorUtil.isColorLight(ATHUtil.resolveColor(getContext(), android.R.attr.windowBackground))) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - updatePlayPauseColor(); - updateProgressTextColor(); - - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), ColorUtil.isColorLight(dark)), false); - TintHelper.setTintAuto(playPauseFab, dark, true); - } - - private void updatePlayPauseColor() { - //playPauseButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void updateProgressTextColor() { - int color = MaterialValueHelper.getPrimaryTextColor(getContext(), false); - songTotalTime.setTextColor(color); - songCurrentProgress.setTextColor(color); - } - - @Override - protected void show() { - //Ignore - } - - @Override - protected void hide() { - //Ignore - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(playPauseFab); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } - - private void hideVolumeIfAvailable() { - volumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/cardblur/CardBlurFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/cardblur/CardBlurFragment.java deleted file mode 100644 index 97e7931f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/cardblur/CardBlurFragment.java +++ /dev/null @@ -1,201 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.cardblur; - -import android.app.Activity; -import android.graphics.Color; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import com.bumptech.glide.Glide; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.BlurTransformation; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; - -public class CardBlurFragment extends AbsPlayerFragment implements - PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @BindView(R.id.gradient_background) - ImageView colorBackground; - - private int lastColor; - private CardBlurPlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - - public static PlayerFragment newInstance() { - Bundle args = new Bundle(); - PlayerFragment fragment = new PlayerFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public void onResume() { - super.onResume(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return Color.WHITE; - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - - toolbar.setTitleTextColor(Color.WHITE); - toolbar.setSubtitleTextColor(Color.WHITE); - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_card_blur_player, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = (CardBlurPlaybackControlsFragment) getChildFragmentManager() - .findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = - (PlayerAlbumCoverFragment) getChildFragmentManager().findFragmentById(R.id.player_album_cover_fragment); - if (playerAlbumCoverFragment != null) { - playerAlbumCoverFragment.setCallbacks(this); - playerAlbumCoverFragment.removeEffect(); - } - - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - toolbar.setTitleTextColor(Color.WHITE); - toolbar.setSubtitleTextColor(Color.WHITE); - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - updateBlur(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - updateBlur(); - updateSong(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - toolbar.setTitle(song.title); - toolbar.setSubtitle(song.artistName); - } - - private void updateBlur() { - Activity activity = getActivity(); - if (activity == null) { - return; - } - int blurAmount = PreferenceManager.getDefaultSharedPreferences(getContext()) - .getInt("new_blur_amount", 25); - - colorBackground.clearColorFilter(); - SongGlideRequest.Builder.from(Glide.with(activity), MusicPlayerRemote.getCurrentSong()) - .checkIgnoreMediaStore(activity) - .generatePalette(activity) - .build() - .transform(new BlurTransformation.Builder(getActivity()).blurRadius(blurAmount).build()) - .into(new RetroMusicColoredTarget(colorBackground) { - @Override - public void onColorReady(int color) { - if (color == getDefaultFooterColor()) { - colorBackground.setColorFilter(color); - } - } - }); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/cardblur/CardBlurPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/cardblur/CardBlurPlaybackControlsFragment.java deleted file mode 100644 index 0b6acbc2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/cardblur/CardBlurPlaybackControlsFragment.java +++ /dev/null @@ -1,309 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.cardblur; - -import android.animation.ObjectAnimator; -import android.content.res.ColorStateList; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.VolumeFragment; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class CardBlurPlaybackControlsFragment extends AbsPlayerControlsFragment { - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - - private Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_card_blur_player_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - hideVolumeIfAvailable(); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - } - - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - lastPlaybackControlsColor = Color.WHITE; - lastDisabledPlaybackControlsColor = ColorUtil.withAlpha(Color.WHITE, 0.3f); - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - updateProgressTextColor(); - } - - - private void setUpPlayPauseFab() { - TintHelper.setTintAuto(playPauseFab, Color.WHITE, true); - TintHelper.setTintAuto(playPauseFab, Color.BLACK, false); - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - setupVolumeControls(); - } - - private void setupVolumeControls() { - VolumeFragment volumeFragment = (VolumeFragment) getChildFragmentManager() - .findFragmentById(R.id.volume_fragment); - if (volumeFragment != null) { - volumeFragment.tintWhiteColor(); - } - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void updateProgressTextColor() { - int color = MaterialValueHelper.getPrimaryTextColor(getContext(), false); - songTotalTime.setTextColor(color); - songCurrentProgress.setTextColor(color); - } - - @Override - protected void show() { - //Ignore - } - - @Override - protected void hide() { - //Ignore - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - progressSlider.setBackgroundTintList(ColorStateList.valueOf(Color.WHITE)); - } - - public void showBouceAnimation() { - playPauseFab.clearAnimation(); - - playPauseFab.setScaleX(0.9f); - playPauseFab.setScaleY(0.9f); - playPauseFab.setVisibility(View.VISIBLE); - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - - playPauseFab.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> playPauseFab.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } - - public void hideVolumeIfAvailable() { - volumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.java deleted file mode 100644 index 76d46883..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.java +++ /dev/null @@ -1,309 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.color; - -import android.animation.ArgbEvaluator; -import android.animation.ValueAnimator; -import android.annotation.SuppressLint; -import android.app.Activity; -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.os.AsyncTask; -import android.os.Bundle; -import android.text.TextUtils; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import androidx.palette.graphics.Palette; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.RetroMusicColoredTarget; -import code.name.monkey.retromusic.glide.SongGlideRequest; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.model.lyrics.Lyrics; -import code.name.monkey.retromusic.ui.activities.LyricsActivity; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.RetroColorUtil; -import code.name.monkey.retromusic.util.ViewUtil; - -public class ColorFragment extends AbsPlayerFragment { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @BindView(R.id.gradient_background) - View colorBackground; - - @BindView(R.id.image) - ImageView imageView; - - @BindView(R.id.lyrics) - TextView lyricsView; - - @BindView(R.id.lyrics_container) - View lyricsViewContainer; - - @BindView(R.id.album_cover_container) - View imageViewContainer; - - private int lastColor; - private int backgroundColor; - private ColorPlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - private ValueAnimator valueAnimator; - private AsyncTask updateLyricsAsyncTask; - private Lyrics lyrics; - - public static ColorFragment newInstance() { - Bundle args = new Bundle(); - ColorFragment fragment = new ColorFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - @ColorInt - public int getPaletteColor() { - return backgroundColor; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return lastColor; - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - if (valueAnimator != null) { - valueAnimator.cancel(); - valueAnimator = null; - } - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_color_player, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = (ColorPlaybackControlsFragment) - getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - updateLyricsLocal(); - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - updateSong(); - updateLyricsLocal(); - } - - private void updateSong() { - Activity activity = getActivity(); - - SongGlideRequest.Builder.from(Glide.with(activity), MusicPlayerRemote.getCurrentSong()) - .checkIgnoreMediaStore(activity) - .generatePalette(activity).build().dontAnimate() - .into(new RetroMusicColoredTarget(imageView) { - @Override - public void onColorReady(int color) { - //setColors(color); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - - int backgroundColor = getDefaultFooterColor(); - int textColor = ColorUtil.isColorLight(getDefaultFooterColor()) ? - MaterialValueHelper.getPrimaryTextColor(getContext(), true) : - MaterialValueHelper.getPrimaryTextColor(getContext(), false); - - setColors(backgroundColor, textColor); - } - - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - super.onResourceReady(resource, glideAnimation); - /* MediaNotificationProcessor processor = new MediaNotificationProcessor(getContext(), - getContext()); - Palette.Builder builder = MediaNotificationProcessor - .generatePalette(resource.getBitmap()); - - int backgroundColor = processor.getBackgroundColor(builder); - int textColor = processor.getTextColor(builder);*/ - - Palette palette = resource.getPalette(); - Palette.Swatch swatch = RetroColorUtil.getSwatch(palette); - - int textColor = RetroColorUtil.getTextColor(palette); - int backgroundColor = swatch.getRgb(); - - setColors(backgroundColor, textColor); - } - }); - } - - private void setColors(int backgroundColor, int textColor) { - playbackControlsFragment.setDark(textColor, backgroundColor); - - colorBackground.setBackgroundColor(backgroundColor); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, textColor, getActivity()); - - lastColor = textColor; - - this.backgroundColor = backgroundColor; - - if (getPlayerActivity() != null) { - getPlayerActivity().setLightNavigationBar(ColorUtil.isColorLight(backgroundColor)); - } - getCallbacks().onPaletteColorChanged(); - - } - - private void colorize(int i) { - if (valueAnimator != null) { - valueAnimator.cancel(); - } - - valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), backgroundColor, i); - valueAnimator.addUpdateListener(animation -> { - if (colorBackground != null) { - colorBackground.setBackgroundColor((Integer) animation.getAnimatedValue()); - } - }); - valueAnimator.setDuration(ViewUtil.RETRO_MUSIC_ANIM_TIME).start(); - } - - @SuppressLint("StaticFieldLeak") - private void updateLyricsLocal() { - if (updateLyricsAsyncTask != null) { - updateLyricsAsyncTask.cancel(false); - } - final Song song = MusicPlayerRemote.getCurrentSong(); - updateLyricsAsyncTask = new AsyncTask() { - @Override - protected void onPreExecute() { - super.onPreExecute(); - lyrics = null; - toolbar.getMenu().removeItem(R.id.action_show_lyrics); - } - - @Override - protected Lyrics doInBackground(Void... params) { - String data = MusicUtil.getLyrics(song); - if (TextUtils.isEmpty(data)) { - return null; - } - return Lyrics.parse(song, data); - } - - @Override - protected void onPostExecute(Lyrics l) { - lyrics = l; - if (lyrics == null) { - lyricsView.setText(R.string.no_lyrics_found); - } else { - lyricsView.setText(lyrics.getText()); - } - } - - @Override - protected void onCancelled(Lyrics s) { - onPostExecute(null); - } - }.execute(); - } - - @OnClick(R.id.expand) - void expand() { - startActivity(new Intent(getContext(), LyricsActivity.class)); - } - - @OnClick({R.id.lyrics, R.id.image}) - void toggleLyrics(View view) { - if (lyricsViewContainer.getVisibility() == View.GONE) { - lyricsViewContainer.setVisibility(View.VISIBLE); - } else { - lyricsViewContainer.setVisibility(View.GONE); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorPlaybackControlsFragment.java deleted file mode 100644 index b98dc4f5..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorPlaybackControlsFragment.java +++ /dev/null @@ -1,311 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.color; - -import android.animation.ObjectAnimator; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.VolumeFragment; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class ColorPlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - private Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - private VolumeFragment volumeFragment; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, - @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_color_player_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - if (PreferenceUtil.getInstance().getVolumeToggle()) { - volumeContainer.setVisibility(View.VISIBLE); - } else { - volumeContainer.setVisibility(View.GONE); - } - - volumeFragment = (VolumeFragment) getChildFragmentManager().findFragmentById(R.id.volume_fragment); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - - public void setDark(int textColor, int background) { - setDark(textColor); - TintHelper.setTintAuto(playPauseFab, background, false); - TintHelper.setTintAuto(playPauseFab, textColor, true); - } - - @Override - public void setDark(int color) { - lastPlaybackControlsColor = color; - lastDisabledPlaybackControlsColor = ColorUtil.withAlpha(color, 0.5f); - - title.setTextColor(lastPlaybackControlsColor); - text.setTextColor(lastDisabledPlaybackControlsColor); - - TintHelper.setTintAuto(progressSlider, lastPlaybackControlsColor, false); - - volumeFragment.setTintable(lastPlaybackControlsColor); - - songCurrentProgress.setTextColor(lastDisabledPlaybackControlsColor); - songTotalTime.setTextColor(lastDisabledPlaybackControlsColor); - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - } - - - private void setUpPlayPauseFab() { - TintHelper.setTintAuto(playPauseFab, Color.WHITE, true); - TintHelper.setTintAuto(playPauseFab, Color.BLACK, false); - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } - - public void hideVolumeIfAvailable() { - volumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/fit/FitFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/fit/FitFragment.java deleted file mode 100644 index 12ec30b8..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/fit/FitFragment.java +++ /dev/null @@ -1,154 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.fit; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; - - -public class FitFragment extends AbsPlayerFragment implements PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - private int lastColor; - private FitPlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - - public FitFragment() { - } - - public static FitFragment newInstance() { - Bundle args = new Bundle(); - FitFragment fragment = new FitFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_fit, container, false); - unbinder = ButterKnife.bind(this, view); - if (getPlayerActivity() != null) { - getPlayerActivity().setDrawUnderStatusBar(); - getPlayerActivity().setNavigationbarColorAuto(); - } - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = (FitPlaybackControlsFragment) getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) getChildFragmentManager().findFragmentById(R.id.player_album_cover_fragment); - if (playerAlbumCoverFragment != null) { - playerAlbumCoverFragment.setCallbacks(this); - playerAlbumCoverFragment.removeEffect(); - } - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/fit/FitPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/fit/FitPlaybackControlsFragment.java deleted file mode 100644 index 271ebe61..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/fit/FitPlaybackControlsFragment.java +++ /dev/null @@ -1,344 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.fit; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.graphics.drawable.ClipDrawable; -import android.graphics.drawable.LayerDrawable; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class FitPlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.volume_fragment_container) - View mVolumeContainer; - - private Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_fit_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - if (PreferenceUtil.getInstance().getVolumeToggle()) { - mVolumeContainer.setVisibility(View.VISIBLE); - } else { - mVolumeContainer.setVisibility(View.GONE); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - int color = ATHUtil.resolveColor(getActivity(), android.R.attr.colorBackground); - if (ColorUtil.isColorLight(color)) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - setFabColor(dark); - } else { - setFabColor(ThemeStore.accentColor(getContext())); - } - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - } - - private void setFabColor(int i) { - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), ColorUtil.isColorLight(i)), false); - TintHelper.setTintAuto(playPauseFab, i, true); - //setProgressBarColor(i); - } - - private void setProgressBarColor(int newColor) { - LayerDrawable ld = (LayerDrawable) progressSlider.getProgressDrawable(); - ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(android.R.id.progress); - clipDrawable.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - public void showBouceAnimation() { - playPauseFab.clearAnimation(); - - playPauseFab.setScaleX(0.9f); - playPauseFab.setScaleY(0.9f); - playPauseFab.setVisibility(View.VISIBLE); - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - - playPauseFab.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> playPauseFab.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/flat/FlatPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/flat/FlatPlaybackControlsFragment.java deleted file mode 100644 index 2f766f3f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/flat/FlatPlaybackControlsFragment.java +++ /dev/null @@ -1,297 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.flat; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.ImageView; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper.Callback; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsMusicServiceFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.PlayPauseDrawable; - -public class FlatPlaybackControlsFragment extends AbsMusicServiceFragment implements Callback { - - @BindView(R.id.text) - TextView mText; - - @BindView(R.id.title) - TextView mTitle; - - @BindView(R.id.playback_controls) - ViewGroup viewGroup; - - @BindView(R.id.player_song_total_time) - TextView mSongTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView mPlayerSongCurrentProgress; - - @BindView(R.id.player_repeat_button) - ImageButton mPlayerRepeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton mPlayerShuffleButton; - - @BindView(R.id.player_play_pause_button) - ImageView playPauseFab; - - @BindView(R.id.player_progress_slider) - SeekBar progressSlider; - - @BindView(R.id.volume_fragment_container) - View mVolumeContainer; - - Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - private PlayPauseDrawable playerFabPlayPauseDrawable; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_flat_player_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpMusicControllers(); - - mVolumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - mPlayerSongCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - mSongTotalTime.setText(MusicUtil.getReadableDurationString(total)); - } - - - public void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - - public void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - public void setDark(int dark) { - int color = ATHUtil.resolveColor(getActivity(), android.R.attr.colorBackground); - boolean isDark = ColorUtil.isColorLight(color); - if (isDark) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - int accentColor = ThemeStore.accentColor(getContext()); - boolean b = PreferenceUtil.getInstance().getAdaptiveColor(); - updateTextColors(b ? dark : accentColor); - setProgressBarColor(b ? dark : accentColor); - - - updateRepeatState(); - updateShuffleState(); - } - - private void setProgressBarColor(int dark) { - TintHelper.setTintAuto(progressSlider, dark, false); - //LayerDrawable ld = (LayerDrawable) progressSlider.getProgressDrawable(); - //ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(android.R.id.progress); - //clipDrawable.setColorFilter(dark, PorterDuff.Mode.SRC_IN); - } - - private void updateTextColors(int color) { - boolean isDark = ColorUtil.isColorLight(color); - int darkColor = ColorUtil.darkenColor(color); - int colorPrimary = MaterialValueHelper.getPrimaryTextColor(getContext(), isDark); - int colorSecondary = MaterialValueHelper.getSecondaryTextColor(getContext(), ColorUtil.isColorLight(darkColor)); - - TintHelper.setTintAuto(playPauseFab, colorPrimary, false); - TintHelper.setTintAuto(playPauseFab, color, true); - - mTitle.setBackgroundColor(color); - mTitle.setTextColor(colorPrimary); - mText.setBackgroundColor(darkColor); - mText.setTextColor(colorSecondary); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void updateSong() { - //TransitionManager.beginDelayedTransition(viewGroup, new ChangeText().setChangeBehavior(ChangeText.CHANGE_BEHAVIOR_OUT_IN)); - Song song = MusicPlayerRemote.getCurrentSong(); - mTitle.setText(song.title); - mText.setText(song.artistName); - - } - - private void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - private void setUpRepeatButton() { - mPlayerRepeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - private void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - mPlayerRepeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - mPlayerRepeatButton - .setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - mPlayerRepeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - mPlayerRepeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - mPlayerRepeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - mPlayerRepeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpShuffleButton() { - mPlayerShuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - private void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - mPlayerShuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - mPlayerShuffleButton - .setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/flat/FlatPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/flat/FlatPlayerFragment.java deleted file mode 100644 index 5d302840..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/flat/FlatPlayerFragment.java +++ /dev/null @@ -1,177 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.flat; - -import android.animation.ArgbEvaluator; -import android.animation.ValueAnimator; -import android.graphics.drawable.GradientDrawable; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.ViewUtil; -import code.name.monkey.retromusic.views.DrawableGradient; - -public class FlatPlayerFragment extends AbsPlayerFragment implements - PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @BindView(R.id.gradient_background) - View colorBackground; - - @BindView(R.id.toolbar_container) - FrameLayout toolbarContainer; - - - private Unbinder unbinder; - private ValueAnimator valueAnimator; - private FlatPlaybackControlsFragment flatPlaybackControlsFragment; - private int lastColor; - - private void setUpSubFragments() { - flatPlaybackControlsFragment = (FlatPlaybackControlsFragment) - getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) - getChildFragmentManager().findFragmentById(R.id.player_album_cover_fragment); - if (playerAlbumCoverFragment != null) { - playerAlbumCoverFragment.setCallbacks(this); - } - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, ATHUtil.resolveColor(getContext(), - R.attr.iconColor), getActivity()); - } - - private void colorize(int i) { - if (valueAnimator != null) { - valueAnimator.cancel(); - } - - valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), android.R.color.transparent, i); - valueAnimator.addUpdateListener(animation -> { - GradientDrawable drawable = new DrawableGradient(GradientDrawable.Orientation.TOP_BOTTOM, - new int[]{(int) animation.getAnimatedValue(), android.R.color.transparent}, 0); - if (colorBackground != null) { - colorBackground.setBackground(drawable); - } - }); - valueAnimator.setDuration(ViewUtil.RETRO_MUSIC_ANIM_TIME).start(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_flat_player, container, false); - unbinder = ButterKnife.bind(this, view); - - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpPlayerToolbar(); - setUpSubFragments(); - - } - - @Override - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - flatPlaybackControlsFragment.show(); - } - - @Override - public void onHide() { - flatPlaybackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - boolean isLight = ColorUtil.isColorLight(lastColor); - return PreferenceUtil.getInstance().getAdaptiveColor() ? - MaterialValueHelper.getPrimaryTextColor(getContext(), isLight) : - ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - lastColor = color; - flatPlaybackControlsFragment.setDark(color); - getCallbacks().onPaletteColorChanged(); - - boolean isLight = ColorUtil.isColorLight(color); - - //TransitionManager.beginDelayedTransition(mToolbar); - int iconColor = PreferenceUtil.getInstance().getAdaptiveColor() ? - MaterialValueHelper.getPrimaryTextColor(getContext(), isLight) : - ATHUtil.resolveColor(getContext(), R.attr.iconColor); - ToolbarContentTintHelper.colorizeToolbar(toolbar, iconColor, getActivity()); - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - colorize(color); - } - } - - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/full/FullPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/full/FullPlaybackControlsFragment.java deleted file mode 100644 index b7a527f2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/full/FullPlaybackControlsFragment.java +++ /dev/null @@ -1,313 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.full; - -import android.animation.ObjectAnimator; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.graphics.drawable.ClipDrawable; -import android.graphics.drawable.LayerDrawable; -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.VolumeFragment; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * Created by hemanths on 20/09/17. - */ - -public class FullPlaybackControlsFragment extends AbsPlayerControlsFragment { - @BindView(R.id.player_song_current_progress) - TextView mPlayerSongCurrentProgress; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_progress_slider) - SeekBar progressSlider; - @BindView(R.id.player_prev_button) - - ImageButton playerPrevButton; - @BindView(R.id.player_next_button) - - ImageButton playerNextButton; - @BindView(R.id.player_repeat_button) - - ImageButton playerRepeatButton; - @BindView(R.id.player_shuffle_button) - - ImageButton playerShuffleButton; - @BindView(R.id.player_play_pause_button) - - ImageButton playerPlayPauseFab; - - - @BindView(R.id.title) - TextView mTitle; - - @BindView(R.id.text) - TextView mText; - - @BindView(R.id.volume_fragment_container) - View mVolumeContainer; - - Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, - @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_full_player_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - setUpMusicControllers(); - - mVolumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - VolumeFragment volumeFragment = (VolumeFragment) getChildFragmentManager().findFragmentById(R.id.volume_fragment); - volumeFragment.tintWhiteColor(); - - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - mPlayerSongCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - } - - - public void show() { - playerPlayPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - - public void hide() { - if (playerPlayPauseFab != null) { - playerPlayPauseFab.setScaleX(0f); - playerPlayPauseFab.setScaleY(0f); - playerPlayPauseFab.setRotation(0f); - } - } - - public void setDark(int dark) { - lastPlaybackControlsColor = Color.WHITE; - lastDisabledPlaybackControlsColor = ContextCompat.getColor(getContext(), R.color.md_grey_500); - - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - setProgressBarColor(dark); - } else { - int accentColor = ThemeStore.accentColor(getContext()); - setProgressBarColor(accentColor); - } - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - updateProgressTextColor(); - } - - private void setProgressBarColor(int dark) { - LayerDrawable ld = (LayerDrawable) progressSlider.getProgressDrawable(); - ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(android.R.id.progress); - clipDrawable.setColorFilter(dark, PorterDuff.Mode.SRC_IN); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(false); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - mTitle.setText(song.title); - mText.setText(song.artistName); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(true); - } - - protected void updatePlayPauseDrawableState(boolean animate) { - - if (MusicPlayerRemote.isPlaying()) { - playerPlayPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playerPlayPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - private void setUpPlayPauseFab() { - - playerPlayPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - playerPlayPauseFab.post(() -> { - if (playerPlayPauseFab != null) { - playerPlayPauseFab.setPivotX(playerPlayPauseFab.getWidth() / 2); - playerPlayPauseFab.setPivotY(playerPlayPauseFab.getHeight() / 2); - } - }); - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - playerNextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - playerPrevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updateProgressTextColor() { - int color = MaterialValueHelper.getSecondaryTextColor(getContext(), false); - //songTotalTime.setTextColor(color); - //songCurrentProgress.setTextColor(color); - } - - private void updatePrevNextColor() { - playerNextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - playerPrevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - private void setUpRepeatButton() { - playerRepeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - playerRepeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - playerRepeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - playerRepeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - playerRepeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - playerRepeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - playerRepeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpShuffleButton() { - playerShuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - public void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - playerShuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - playerShuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/full/FullPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/full/FullPlayerFragment.java deleted file mode 100644 index 5c3daa35..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/full/FullPlayerFragment.java +++ /dev/null @@ -1,124 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.full; - -import android.graphics.Color; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; - -public class FullPlayerFragment extends AbsPlayerFragment implements PlayerAlbumCoverFragment.Callbacks { - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - private Unbinder unbinder; - - private int lastColor; - private FullPlaybackControlsFragment fullPlaybackControlsFragment; - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_full, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - fullPlaybackControlsFragment = (FullPlaybackControlsFragment) - getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) - getChildFragmentManager().findFragmentById(R.id.player_album_cover_fragment); - if (playerAlbumCoverFragment != null) { - playerAlbumCoverFragment.setCallbacks(this); - playerAlbumCoverFragment.removeSlideEffect(); - } - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - - } - - @Override - public void onHide() { - - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return Color.WHITE; - } - - @Override - public void onColorChanged(int color) { - lastColor = color; - fullPlaybackControlsFragment.setDark(color); - getCallbacks().onPaletteColorChanged(); - ToolbarContentTintHelper.colorizeToolbar(toolbar, Color.WHITE, getActivity()); - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/hmm/HmmPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/hmm/HmmPlaybackControlsFragment.java deleted file mode 100644 index 17884afc..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/hmm/HmmPlaybackControlsFragment.java +++ /dev/null @@ -1,142 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.hmm; - -import android.graphics.PorterDuff; -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageButton; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; - -/** - * @author Hemanth S (h4h13). - */ - -public class HmmPlaybackControlsFragment extends AbsPlayerControlsFragment { - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - private Unbinder unbinder; - private int mLastPlaybackControlsColor; - private int mLastDisabledPlaybackControlsColor; - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_hmm_controls_fragment, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpMusicControllers(); - } - - private void setUpMusicControllers() { - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - @Override - protected void show() { - - } - - @Override - protected void hide() { - - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(mLastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(mLastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(mLastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(mLastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(mLastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - @Override - protected void setUpProgressSlider() { - - } - - @Override - public void setDark(int dark) { - if (ColorUtil.isColorLight(dark)) { - mLastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - mLastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - mLastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - mLastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - updateRepeatState(); - updateShuffleState(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/hmm/HmmPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/hmm/HmmPlayerFragment.java deleted file mode 100644 index 7197914e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/hmm/HmmPlayerFragment.java +++ /dev/null @@ -1,222 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.hmm; - -import android.animation.AnimatorSet; -import android.animation.ObjectAnimator; -import android.graphics.Color; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.LinearInterpolator; -import android.widget.ProgressBar; -import android.widget.TextView; - -import com.afollestad.materialdialogs.internal.MDTintHelper; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.MiniPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ - -public class HmmPlayerFragment extends AbsPlayerFragment implements - MusicProgressViewUpdateHelper.Callback, PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.player_song_total_time) - TextView totalTime; - - @BindView(R.id.progress_bar) - ProgressBar progressBar; - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - private Unbinder unBinder; - private int lastColor; - private HmmPlaybackControlsFragment hmmPlaybackControlsFragment; - - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(String.format("%s \nby -%s", song.albumName, song.artistName)); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unBinder.unbind(); - - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_hmm_player, container, false); - unBinder = ButterKnife.bind(this, view); - - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - progressBar.setOnClickListener(new PlayPauseButtonOnClickHandler()); - progressBar.setOnTouchListener(new MiniPlayerFragment.FlingPlayBackController(getActivity())); - - setUpPlayerToolbar(); - setUpSubFragments(); - } - - private void setUpSubFragments() { - hmmPlaybackControlsFragment = (HmmPlaybackControlsFragment) getChildFragmentManager() - .findFragmentById(R.id.playback_controls_fragment); - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) getChildFragmentManager() - .findFragmentById(R.id.player_album_cover_fragment); - playerAlbumCoverFragment.setCallbacks(this); - - } - - @Override - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - hmmPlaybackControlsFragment.show(); - } - - @Override - public void onHide() { - hmmPlaybackControlsFragment.hide(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return MaterialValueHelper - .getSecondaryTextColor(getContext(), ColorUtil.isColorLight(lastColor)); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressBar.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressBar, "progress", progress); - - AnimatorSet animatorSet = new AnimatorSet(); - animatorSet.playSequentially(animator); - - animatorSet.setDuration(1500); - animatorSet.setInterpolator(new LinearInterpolator()); - animatorSet.start(); - - totalTime.setText(String.format("%s/%s", MusicUtil.getReadableDurationString(total), - MusicUtil.getReadableDurationString(progress))); - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - } - - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onColorChanged(int color) { - lastColor = PreferenceUtil.getInstance().getAdaptiveColor() ? color : - ThemeStore.accentColor(getContext()); - getCallbacks().onPaletteColorChanged(); - hmmPlaybackControlsFragment.setDark(lastColor); - setProgressBarColor(lastColor); - - int iconColor = MaterialValueHelper - .getSecondaryTextColor(getContext(), ColorUtil.isColorLight(lastColor)); - ToolbarContentTintHelper.colorizeToolbar(toolbar, iconColor, getActivity()); - } - - private void setProgressBarColor(int color) { - MDTintHelper.setTint(progressBar, color); - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/lockscreen/LockScreenPlayerControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/lockscreen/LockScreenPlayerControlsFragment.java deleted file mode 100644 index b66d2e24..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/lockscreen/LockScreenPlayerControlsFragment.java +++ /dev/null @@ -1,306 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.lockscreen; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatImageButton; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ -public class LockScreenPlayerControlsFragment extends AbsPlayerControlsFragment { - @BindView(R.id.player_play_pause_button) - AppCompatImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView title; - - @BindView(R.id.text) - AppCompatTextView text; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - private Unbinder unbinder; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - private int lastPlaybackControlsColor; - - public LockScreenPlayerControlsFragment() { - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_lock_screen_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpMusicControllers(); - - //noinspection ConstantConditions - volumeContainer.setVisibility(PreferenceUtil.getInstance().getVolumeToggle() - ? View.VISIBLE : View.GONE); - - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - - title.setText(song.title); - text.setText(String.format("%s - %s", song.artistName, song.albumName)); - - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(false); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(true); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - setProgressBarColor(progressSlider, dark); - - if (ColorUtil.isColorLight(ATHUtil.resolveColor(getContext(), android.R.attr.windowBackground))) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - - } - - updatePrevNextColor(); - - boolean isDark = ColorUtil.isColorLight(dark); - text.setTextColor(dark); - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), isDark), false); - TintHelper.setTintAuto(playPauseFab, dark, true); - } - - public void setProgressBarColor(SeekBar progressBar, int newColor) { - TintHelper.setTintAuto(progressBar, newColor, false); - //LayerDrawable ld = (LayerDrawable) progressBar.getProgressDrawable(); - //ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(android.R.id.progress); - //clipDrawable.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpPlayPauseFab() { - playPauseFab.post(() -> { - if (playPauseFab != null) { - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - } - }); - } - - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - @Override - protected void updateShuffleState() { - //TODO(Nothing to Implement) - } - - @Override - protected void updateRepeatState() { - //TODO(Nothing to Implement) - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - public void showBouceAnimation() { - playPauseFab.clearAnimation(); - - playPauseFab.setScaleX(0.9f); - playPauseFab.setScaleY(0.9f); - playPauseFab.setVisibility(View.VISIBLE); - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - - playPauseFab.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> playPauseFab.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - - protected void updatePlayPauseDrawableState(boolean animate) { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/material/MaterialControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/material/MaterialControlsFragment.java deleted file mode 100644 index 5649185b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/material/MaterialControlsFragment.java +++ /dev/null @@ -1,290 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.material; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ -public class MaterialControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.volume_fragment_container) - View mVolumeContainer; - - private Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_material_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - if (PreferenceUtil.getInstance().getVolumeToggle()) { - mVolumeContainer.setVisibility(View.VISIBLE); - } else { - mVolumeContainer.setVisibility(View.GONE); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - int color = ATHUtil.resolveColor(getActivity(), android.R.attr.colorBackground); - if (ColorUtil.isColorLight(color)) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - updateRepeatState(); - updateShuffleState(); - - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - lastPlaybackControlsColor = dark; - text.setTextColor(dark); - } - - updatePlayPauseColor(); - updatePrevNextColor(); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_big); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_big); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void updatePlayPauseColor() { - playPauseFab.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - @Override - protected void show() { - - } - - @Override - protected void hide() { - - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/material/MaterialFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/material/MaterialFragment.java deleted file mode 100644 index 502e40a2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/material/MaterialFragment.java +++ /dev/null @@ -1,149 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.material; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.ui.fragments.player.normal.PlayerFragment; - -/** - * @author Hemanth S (h4h13). - */ -public class MaterialFragment extends AbsPlayerFragment implements PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - private int lastColor; - private MaterialControlsFragment playbackControlsFragment; - private Unbinder unbinder; - - public static PlayerFragment newInstance() { - Bundle args = new Bundle(); - PlayerFragment fragment = new PlayerFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_material, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = (MaterialControlsFragment) getChildFragmentManager() - .findFragmentById(R.id.playback_controls_fragment); - - PlayerAlbumCoverFragment playerAlbumCoverFragment = - (PlayerAlbumCoverFragment) getChildFragmentManager() - .findFragmentById(R.id.player_album_cover_fragment); - playerAlbumCoverFragment.setCallbacks(this); - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/normal/PlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/normal/PlayerFragment.java deleted file mode 100644 index 2ad2bfc9..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/normal/PlayerFragment.java +++ /dev/null @@ -1,175 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.normal; - -import android.animation.ArgbEvaluator; -import android.animation.ValueAnimator; -import android.graphics.drawable.GradientDrawable; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.ColorInt; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.ViewUtil; -import code.name.monkey.retromusic.views.DrawableGradient; - - -public class PlayerFragment extends AbsPlayerFragment implements PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @BindView(R.id.gradient_background) - View colorBackground; - - private int lastColor; - private PlayerPlaybackControlsFragment playbackControlsFragment; - private Unbinder unbinder; - private ValueAnimator valueAnimator; - - public static PlayerFragment newInstance() { - Bundle args = new Bundle(); - PlayerFragment fragment = new PlayerFragment(); - fragment.setArguments(args); - return fragment; - } - - - private void colorize(int i) { - if (valueAnimator != null) { - valueAnimator.cancel(); - } - - valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), android.R.color.transparent, i); - valueAnimator.addUpdateListener(animation -> { - GradientDrawable drawable = new DrawableGradient(GradientDrawable.Orientation.TOP_BOTTOM, - new int[]{(int) animation.getAnimatedValue(), android.R.color.transparent}, 0); - if (colorBackground != null) { - colorBackground.setBackground(drawable); - } - }); - valueAnimator.setDuration(ViewUtil.RETRO_MUSIC_ANIM_TIME).start(); - } - - @Override - @ColorInt - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - playbackControlsFragment.show(); - } - - @Override - public void onHide() { - playbackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - playbackControlsFragment.setDark(color); - lastColor = color; - getCallbacks().onPaletteColorChanged(); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - colorize(color); - } - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_player, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - playbackControlsFragment = (PlayerPlaybackControlsFragment) getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) getChildFragmentManager().findFragmentById(R.id.player_album_cover_fragment); - if (playerAlbumCoverFragment != null) { - playerAlbumCoverFragment.setCallbacks(this); - } - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - } - - @Override - public void onServiceConnected() { - updateIsFavorite(); - - } - - @Override - public void onPlayingMetaChanged() { - updateIsFavorite(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/normal/PlayerPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/normal/PlayerPlaybackControlsFragment.java deleted file mode 100644 index 28eb7789..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/normal/PlayerPlaybackControlsFragment.java +++ /dev/null @@ -1,344 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.normal; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.graphics.drawable.ClipDrawable; -import android.graphics.drawable.LayerDrawable; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.AppCompatSeekBar; -import androidx.appcompat.widget.AppCompatTextView; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class PlayerPlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - AppCompatSeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.title) - AppCompatTextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.volume_fragment_container) - View mVolumeContainer; - - private Unbinder unbinder; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_player_playback_controls, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - unbinder = ButterKnife.bind(this, view); - setUpMusicControllers(); - - if (PreferenceUtil.getInstance().getVolumeToggle()) { - mVolumeContainer.setVisibility(View.VISIBLE); - } else { - mVolumeContainer.setVisibility(View.GONE); - } - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void setDark(int dark) { - int color = ATHUtil.resolveColor(getActivity(), android.R.attr.colorBackground); - if (ColorUtil.isColorLight(color)) { - lastPlaybackControlsColor = MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - setFabColor(dark); - } else { - setFabColor(ThemeStore.accentColor(getContext())); - } - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - } - - private void setFabColor(int i) { - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), ColorUtil.isColorLight(i)), false); - TintHelper.setTintAuto(playPauseFab, i, true); - setProgressBarColor(i); - } - - private void setProgressBarColor(int newColor) { - LayerDrawable ld = (LayerDrawable) progressSlider.getProgressDrawable(); - ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(android.R.id.progress); - clipDrawable.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - public void showBouceAnimation() { - playPauseFab.clearAnimation(); - - playPauseFab.setScaleX(0.9f); - playPauseFab.setScaleY(0.9f); - playPauseFab.setVisibility(View.VISIBLE); - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - - playPauseFab.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> playPauseFab.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/plain/PlainPlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/plain/PlainPlaybackControlsFragment.java deleted file mode 100644 index e1afe5e4..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/plain/PlainPlaybackControlsFragment.java +++ /dev/null @@ -1,324 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.plain; - -import android.animation.ObjectAnimator; -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.LinearInterpolator; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.misc.SimpleOnSeekbarChangeListener; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.PlayPauseDrawable; - -/** - * @author Hemanth S (h4h13). - */ - -public class PlainPlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_progress_slider) - SeekBar progressSlider; - - @BindView(R.id.player_song_total_time) - TextView songTotalTime; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - private Unbinder unbinder; - private PlayPauseDrawable playerFabPlayPauseDrawable; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, - @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_plain_controls_fragment, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpMusicControllers(); - if (PreferenceUtil.getInstance().getVolumeToggle()) { - volumeContainer.setVisibility(View.VISIBLE); - } else { - volumeContainer.setVisibility(View.GONE); - } - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - @Override - protected void setUpProgressSlider() { - progressSlider.setOnSeekBarChangeListener(new SimpleOnSeekbarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - MusicPlayerRemote.seekTo(progress); - onUpdateProgressViews(MusicPlayerRemote.getSongProgressMillis(), - MusicPlayerRemote.getSongDurationMillis()); - } - } - }); - } - - public void showBouceAnimation() { - playPauseFab.clearAnimation(); - - playPauseFab.setScaleX(0.9f); - playPauseFab.setScaleY(0.9f); - playPauseFab.setVisibility(View.VISIBLE); - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - - playPauseFab.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> playPauseFab.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - progressSlider.setMax(total); - - ObjectAnimator animator = ObjectAnimator.ofInt(progressSlider, "progress", progress); - animator.setDuration(1500); - animator.setInterpolator(new LinearInterpolator()); - animator.start(); - - songTotalTime.setText(MusicUtil.getReadableDurationString(total)); - songCurrentProgress.setText(MusicUtil.getReadableDurationString(progress)); - } - - @Override - public void setDark(int dark) { - int color = ATHUtil.resolveColor(getActivity(), android.R.attr.colorBackground); - if (ColorUtil.isColorLight(color)) { - lastPlaybackControlsColor = - MaterialValueHelper.getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = - MaterialValueHelper.getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = - MaterialValueHelper.getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = - MaterialValueHelper.getPrimaryDisabledTextColor(getActivity(), false); - } - - int finalColor = PreferenceUtil.getInstance().getAdaptiveColor() ? dark : ThemeStore.accentColor(getContext()); - - - setProgressBarColor(finalColor); - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), ColorUtil.isColorLight(finalColor)), false); - TintHelper.setTintAuto(playPauseFab, finalColor, true); - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - } - - private void setProgressBarColor(int newColor) { - TintHelper.setTintAuto(progressSlider, newColor, false); - } - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/plain/PlainPlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/plain/PlainPlayerFragment.java deleted file mode 100644 index 7a1a72ca..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/plain/PlainPlayerFragment.java +++ /dev/null @@ -1,161 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.plain; - -import android.graphics.Color; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.FrameLayout; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; - -/** - * @author Hemanth S (h4h13). - */ - -public class PlainPlayerFragment extends AbsPlayerFragment implements - PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.text) - TextView text; - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - @BindView(R.id.toolbar_container) - FrameLayout toolbarContainer; - - private Unbinder unbinder; - private PlainPlaybackControlsFragment plainPlaybackControlsFragment; - private int mLastColor; - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - updateSong(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_plain_player, container, false); - unbinder = ButterKnife.bind(this, view); - - return view; - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), - getActivity()); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - setUpSubFragments(); - setUpPlayerToolbar(); - title.setSelected(true); - } - - private void setUpSubFragments() { - plainPlaybackControlsFragment = (PlainPlaybackControlsFragment) getChildFragmentManager() - .findFragmentById(R.id.playback_controls_fragment); - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) getChildFragmentManager() - .findFragmentById(R.id.player_album_cover_fragment); - playerAlbumCoverFragment.setCallbacks(this); - } - - @Override - public int getPaletteColor() { - return mLastColor; - } - - @Override - public void onShow() { - plainPlaybackControlsFragment.show(); - } - - @Override - public void onHide() { - plainPlaybackControlsFragment.hide(); - onBackPressed(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - plainPlaybackControlsFragment.setDark(color); - mLastColor = color; - getCallbacks().onPaletteColorChanged(); - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/simple/SimplePlaybackControlsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/simple/SimplePlaybackControlsFragment.java deleted file mode 100644 index 657b0155..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/simple/SimplePlaybackControlsFragment.java +++ /dev/null @@ -1,312 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.simple; - -import android.graphics.PorterDuff; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.AccelerateInterpolator; -import android.view.animation.DecelerateInterpolator; -import android.widget.ImageButton; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ColorUtil; -import code.name.monkey.appthemehelper.util.MaterialValueHelper; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.helper.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.helper.PlayPauseButtonOnClickHandler; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerControlsFragment; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.PlayPauseDrawable; - -/** - * @author Hemanth S (h4h13). - */ - -public class SimplePlaybackControlsFragment extends AbsPlayerControlsFragment { - - @BindView(R.id.player_play_pause_button) - ImageButton playPauseFab; - - @BindView(R.id.player_prev_button) - ImageButton prevButton; - - @BindView(R.id.player_next_button) - ImageButton nextButton; - - @BindView(R.id.player_repeat_button) - ImageButton repeatButton; - - @BindView(R.id.player_shuffle_button) - ImageButton shuffleButton; - - @BindView(R.id.player_song_current_progress) - TextView songCurrentProgress; - - @BindView(R.id.volume_fragment_container) - View volumeContainer; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.text) - TextView text; - private Unbinder unbinder; - private PlayPauseDrawable playerFabPlayPauseDrawable; - private int lastPlaybackControlsColor; - private int lastDisabledPlaybackControlsColor; - private MusicProgressViewUpdateHelper progressViewUpdateHelper; - - - @Override - public void onPlayStateChanged() { - updatePlayPauseDrawableState(); - } - - @Override - public void onRepeatModeChanged() { - updateRepeatState(); - } - - @Override - public void onShuffleModeChanged() { - updateShuffleState(); - } - - @Override - public void onServiceConnected() { - updatePlayPauseDrawableState(); - updateRepeatState(); - updateShuffleState(); - updateSong(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - progressViewUpdateHelper = new MusicProgressViewUpdateHelper(this); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_simple_controls_fragment, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onResume() { - super.onResume(); - progressViewUpdateHelper.start(); - } - - @Override - public void onPause() { - super.onPause(); - progressViewUpdateHelper.stop(); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpMusicControllers(); - volumeContainer.setVisibility( - PreferenceUtil.getInstance().getVolumeToggle() ? View.VISIBLE : View.GONE); - } - - private void setUpMusicControllers() { - setUpPlayPauseFab(); - setUpPrevNext(); - setUpRepeatButton(); - setUpShuffleButton(); - setUpProgressSlider(); - } - - private void setUpPrevNext() { - updatePrevNextColor(); - nextButton.setOnClickListener(v -> MusicPlayerRemote.playNextSong()); - prevButton.setOnClickListener(v -> MusicPlayerRemote.back()); - } - - private void updatePrevNextColor() { - nextButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - prevButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - } - - private void setUpShuffleButton() { - shuffleButton.setOnClickListener(v -> MusicPlayerRemote.toggleShuffleMode()); - } - - @Override - protected void updateShuffleState() { - switch (MusicPlayerRemote.getShuffleMode()) { - case MusicService.SHUFFLE_MODE_SHUFFLE: - shuffleButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - default: - shuffleButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void setUpRepeatButton() { - repeatButton.setOnClickListener(v -> MusicPlayerRemote.cycleRepeatMode()); - } - - @Override - protected void updateRepeatState() { - switch (MusicPlayerRemote.getRepeatMode()) { - case MusicService.REPEAT_MODE_NONE: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastDisabledPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_ALL: - repeatButton.setImageResource(R.drawable.ic_repeat_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - case MusicService.REPEAT_MODE_THIS: - repeatButton.setImageResource(R.drawable.ic_repeat_one_white_24dp); - repeatButton.setColorFilter(lastPlaybackControlsColor, PorterDuff.Mode.SRC_IN); - break; - } - } - - private void updateSong() { - Song song = MusicPlayerRemote.getCurrentSong(); - title.setText(song.title); - text.setText(song.artistName); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - updateSong(); - - } - - @Override - protected void setUpProgressSlider() { - - } - - @Override - protected void show() { - playPauseFab.animate() - .scaleX(1f) - .scaleY(1f) - .rotation(360f) - .setInterpolator(new DecelerateInterpolator()) - .start(); - } - - @Override - protected void hide() { - if (playPauseFab != null) { - playPauseFab.setScaleX(0f); - playPauseFab.setScaleY(0f); - playPauseFab.setRotation(0f); - } - } - - - public void showBouceAnimation() { - playPauseFab.clearAnimation(); - - playPauseFab.setScaleX(0.9f); - playPauseFab.setScaleY(0.9f); - playPauseFab.setVisibility(View.VISIBLE); - playPauseFab.setPivotX(playPauseFab.getWidth() / 2); - playPauseFab.setPivotY(playPauseFab.getHeight() / 2); - - playPauseFab.animate() - .setDuration(200) - .setInterpolator(new DecelerateInterpolator()) - .scaleX(1.1f) - .scaleY(1.1f) - .withEndAction(() -> playPauseFab.animate() - .setDuration(200) - .setInterpolator(new AccelerateInterpolator()) - .scaleX(1f) - .scaleY(1f) - .alpha(1f) - .start()) - .start(); - } - - @OnClick(R.id.player_play_pause_button) - void showAnimation() { - if (MusicPlayerRemote.isPlaying()) { - MusicPlayerRemote.pauseSong(); - } else { - MusicPlayerRemote.resumePlaying(); - } - showBouceAnimation(); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - songCurrentProgress - .setText(String.format("%s / %s", MusicUtil.getReadableDurationString(progress), - MusicUtil.getReadableDurationString(total))); - } - - @Override - public void setDark(int dark) { - int color = ATHUtil.resolveColor(getActivity(), android.R.attr.colorBackground); - if (ColorUtil.isColorLight(color)) { - lastPlaybackControlsColor = MaterialValueHelper - .getSecondaryTextColor(getActivity(), true); - lastDisabledPlaybackControlsColor = MaterialValueHelper - .getSecondaryDisabledTextColor(getActivity(), true); - } else { - lastPlaybackControlsColor = MaterialValueHelper - .getPrimaryTextColor(getActivity(), false); - lastDisabledPlaybackControlsColor = MaterialValueHelper - .getPrimaryDisabledTextColor(getActivity(), false); - } - - int finalColor = PreferenceUtil.getInstance().getAdaptiveColor() ? dark : ThemeStore.accentColor(getContext()); - text.setTextColor(finalColor); - TintHelper.setTintAuto(playPauseFab, MaterialValueHelper.getPrimaryTextColor(getContext(), ColorUtil.isColorLight(finalColor)), false); - TintHelper.setTintAuto(playPauseFab, finalColor, true); - - - updateRepeatState(); - updateShuffleState(); - updatePrevNextColor(); - } - - - private void setUpPlayPauseFab() { - playPauseFab.setOnClickListener(new PlayPauseButtonOnClickHandler()); - } - - protected void updatePlayPauseDrawableState() { - if (MusicPlayerRemote.isPlaying()) { - playPauseFab.setImageResource(R.drawable.ic_pause_white_24dp); - } else { - playPauseFab.setImageResource(R.drawable.ic_play_arrow_white_24dp); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/simple/SimplePlayerFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/simple/SimplePlayerFragment.java deleted file mode 100644 index 302ae16a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/simple/SimplePlayerFragment.java +++ /dev/null @@ -1,130 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.player.simple; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; -import code.name.monkey.appthemehelper.util.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.fragments.base.AbsPlayerFragment; -import code.name.monkey.retromusic.ui.fragments.player.PlayerAlbumCoverFragment; - -/** - * @author Hemanth S (h4h13). - */ - -public class SimplePlayerFragment extends AbsPlayerFragment implements - PlayerAlbumCoverFragment.Callbacks { - - @BindView(R.id.player_toolbar) - Toolbar toolbar; - - private Unbinder unbinder; - private SimplePlaybackControlsFragment simplePlaybackControlsFragment; - private int lastColor; - - - @Override - public void onDestroyView() { - super.onDestroyView(); - unbinder.unbind(); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_simple_player, container, false); - unbinder = ButterKnife.bind(this, view); - return view; - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - setUpSubFragments(); - setUpPlayerToolbar(); - } - - private void setUpSubFragments() { - PlayerAlbumCoverFragment playerAlbumCoverFragment = (PlayerAlbumCoverFragment) - getChildFragmentManager().findFragmentById(R.id.player_album_cover_fragment); - playerAlbumCoverFragment.setCallbacks(this); - simplePlaybackControlsFragment = (SimplePlaybackControlsFragment) - getChildFragmentManager().findFragmentById(R.id.playback_controls_fragment); - - } - - @Override - public int getPaletteColor() { - return lastColor; - } - - @Override - public void onShow() { - simplePlaybackControlsFragment.show(); - } - - @Override - public void onHide() { - simplePlaybackControlsFragment.hide(); - } - - @Override - public boolean onBackPressed() { - return false; - } - - @Override - public Toolbar getToolbar() { - return toolbar; - } - - @Override - public int toolbarIconColor() { - return ATHUtil.resolveColor(getContext(), R.attr.iconColor); - } - - @Override - public void onColorChanged(int color) { - lastColor = color; - getCallbacks().onPaletteColorChanged(); - simplePlaybackControlsFragment.setDark(color); - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), getActivity()); - - } - - @Override - public void onFavoriteToggled() { - toggleFavorite(MusicPlayerRemote.getCurrentSong()); - } - - @Override - protected void toggleFavorite(Song song) { - super.toggleFavorite(song); - if (song.id == MusicPlayerRemote.getCurrentSong().id) { - updateIsFavorite(); - } - } - - private void setUpPlayerToolbar() { - toolbar.inflateMenu(R.menu.menu_player); - toolbar.setNavigationOnClickListener(v -> getActivity().onBackPressed()); - toolbar.setOnMenuItemClickListener(this); - - ToolbarContentTintHelper.colorizeToolbar(toolbar, - ATHUtil.resolveColor(getContext(), R.attr.iconColor), - getActivity()); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/MainSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/MainSettingsFragment.java index 0843b248..20b352a4 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/MainSettingsFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/MainSettingsFragment.java @@ -151,7 +151,7 @@ public class MainSettingsFragment extends Fragment { .setQuality(75) .setCompressFormat(Bitmap.CompressFormat.WEBP) .compressToBitmapAsFlowable( - new File(PreferenceUtil.getInstance().getProfileImage(), USER_PROFILE)) + new File(PreferenceUtil.getInstance().getProfileImage(),USER_PROFILE)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(userImageBottom::setImageBitmap, diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.java index 1739f4b5..6eec07ab 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.java @@ -25,7 +25,7 @@ public class NotificationSettingsFragment extends AbsSettingsFragment { // Save preference PreferenceUtil.getInstance().setClassicNotification((Boolean) newValue); - final MusicService service = MusicPlayerRemote.musicService; + final MusicService service = MusicPlayerRemote.INSTANCE.getMusicService(); if (service != null) { service.initNotification(); service.updateNotification(); diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.java index cf3b8805..ee67454f 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.java @@ -25,7 +25,7 @@ public class NowPlayingSettingsFragment extends AbsSettingsFragment implements final TwoStatePreference carouselEffect = (TwoStatePreference) findPreference("carousel_effect"); carouselEffect.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue && !RetroApplication.isProVersion()) { + if ((Boolean) newValue && !RetroApplication.Companion.isProVersion()) { showProToastAndNavigate(getActivity().getString(R.string.pref_title_toggle_carousel_effect)); return false; } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.java index 0bb677f3..39dc558d 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.java @@ -16,7 +16,7 @@ public class PersonaizeSettingsFragment extends AbsSettingsFragment implements S public void invalidateSettings() { final TwoStatePreference cornerWindow = (TwoStatePreference) findPreference("corner_window"); cornerWindow.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue && !RetroApplication.isProVersion()) { + if ((Boolean) newValue && !RetroApplication.Companion.isProVersion()) { showProToastAndNavigate(getActivity().getString(R.string.pref_title_round_corners)); return false; } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.java index 5f6cc4d2..2a4e0095 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.java @@ -3,19 +3,18 @@ package code.name.monkey.retromusic.ui.fragments.settings; import android.graphics.Color; import android.os.Build; import android.os.Bundle; -import androidx.core.content.ContextCompat; -import androidx.preference.Preference; -import androidx.preference.TwoStatePreference; import com.afollestad.materialdialogs.color.ColorChooserDialog; +import androidx.core.content.ContextCompat; +import androidx.preference.Preference; +import androidx.preference.TwoStatePreference; import code.name.monkey.appthemehelper.ThemeStore; import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEColorPreference; import code.name.monkey.appthemehelper.util.ColorUtil; import code.name.monkey.appthemehelper.util.VersionUtils; import code.name.monkey.retromusic.R; import code.name.monkey.retromusic.RetroApplication; -import code.name.monkey.retromusic.appshortcuts.DynamicShortcutManager; import code.name.monkey.retromusic.ui.activities.SettingsActivity; import code.name.monkey.retromusic.util.PreferenceUtil; @@ -49,7 +48,7 @@ public class ThemeSettingsFragment extends AbsSettingsFragment { generalTheme.setOnPreferenceChangeListener((preference, newValue) -> { String theme = (String) newValue; - if (theme.equals("color") && !RetroApplication.isProVersion()) { + if (theme.equals("color") && !RetroApplication.Companion.isProVersion()) { primaryColorPref.setVisible(false); showProToastAndNavigate("Color theme"); return false; @@ -81,7 +80,6 @@ public class ThemeSettingsFragment extends AbsSettingsFragment { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { getActivity().setTheme(PreferenceUtil.getThemeResFromPrefValue(theme)); - new DynamicShortcutManager(getActivity()).updateDynamicShortcuts(); } getActivity().recreate(); //invalidateSettings(); @@ -111,9 +109,6 @@ public class ThemeSettingsFragment extends AbsSettingsFragment { colorAppShortcuts.setOnPreferenceChangeListener((preference, newValue) -> { // Save preference PreferenceUtil.getInstance().setColoredAppShortcuts((Boolean) newValue); - // Update app shortcuts - new DynamicShortcutManager(getActivity()).updateDynamicShortcuts(); - return true; }); } diff --git a/app/src/main/java/code/name/monkey/retromusic/util/CustomArtistImageUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/CustomArtistImageUtil.java index 752b4871..34406ea7 100644 --- a/app/src/main/java/code/name/monkey/retromusic/util/CustomArtistImageUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/CustomArtistImageUtil.java @@ -7,7 +7,6 @@ import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; -import androidx.annotation.NonNull; import android.widget.Toast; import com.bumptech.glide.Glide; @@ -22,6 +21,7 @@ import java.io.IOException; import java.io.OutputStream; import java.util.Locale; +import androidx.annotation.NonNull; import code.name.monkey.retromusic.RetroApplication; import code.name.monkey.retromusic.model.Artist; @@ -55,12 +55,12 @@ public class CustomArtistImageUtil { } public static File getFile(Artist artist) { - File dir = new File(RetroApplication.getInstance().getFilesDir(), FOLDER_NAME); + File dir = new File(RetroApplication.Companion.getInstance().getFilesDir(), FOLDER_NAME); return new File(dir, getFileName(artist)); } public void setCustomArtistImage(final Artist artist, Uri uri) { - Glide.with(RetroApplication.getInstance()) + Glide.with(RetroApplication.Companion.getInstance()) .load(uri) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.NONE) @@ -70,7 +70,7 @@ public class CustomArtistImageUtil { public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); e.printStackTrace(); - Toast.makeText(RetroApplication.getInstance(), e.toString(), Toast.LENGTH_LONG).show(); + Toast.makeText(RetroApplication.Companion.getInstance(), e.toString(), Toast.LENGTH_LONG).show(); } @SuppressLint("StaticFieldLeak") @@ -80,7 +80,7 @@ public class CustomArtistImageUtil { @SuppressLint("ApplySharedPref") @Override protected Void doInBackground(Void... params) { - File dir = new File(RetroApplication.getInstance().getFilesDir(), FOLDER_NAME); + File dir = new File(RetroApplication.Companion.getInstance().getFilesDir(), FOLDER_NAME); if (!dir.exists()) { if (!dir.mkdirs()) { // create the folder return null; @@ -94,13 +94,13 @@ public class CustomArtistImageUtil { succesful = ImageUtil.resizeBitmap(resource, 2048).compress(Bitmap.CompressFormat.JPEG, 100, os); os.close(); } catch (IOException e) { - Toast.makeText(RetroApplication.getInstance(), e.toString(), Toast.LENGTH_LONG).show(); + Toast.makeText(RetroApplication.Companion.getInstance(), e.toString(), Toast.LENGTH_LONG).show(); } if (succesful) { mPreferences.edit().putBoolean(getFileName(artist), true).commit(); - ArtistSignatureUtil.getInstance(RetroApplication.getInstance()).updateArtistSignature(artist.getName()); - RetroApplication.getInstance().getContentResolver().notifyChange(Uri.parse("content://media"), null); // trigger media store changed to force artist image reload + ArtistSignatureUtil.getInstance(RetroApplication.Companion.getInstance()).updateArtistSignature(artist.getName()); + RetroApplication.Companion.getInstance().getContentResolver().notifyChange(Uri.parse("content://media"), null); // trigger media store changed to force artist image reload } return null; } @@ -116,8 +116,8 @@ public class CustomArtistImageUtil { @Override protected Void doInBackground(Void... params) { mPreferences.edit().putBoolean(getFileName(artist), false).commit(); - ArtistSignatureUtil.getInstance(RetroApplication.getInstance()).updateArtistSignature(artist.getName()); - RetroApplication.getInstance().getContentResolver().notifyChange(Uri.parse("content://media"), null); // trigger media store changed to force artist image reload + ArtistSignatureUtil.getInstance(RetroApplication.Companion.getInstance()).updateArtistSignature(artist.getName()); + RetroApplication.Companion.getInstance().getContentResolver().notifyChange(Uri.parse("content://media"), null); // trigger media store changed to force artist image reload File file = getFile(artist); if (!file.exists()) { diff --git a/app/src/main/java/code/name/monkey/retromusic/util/FileUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/FileUtil.java index 103df288..fae4f13f 100644 --- a/app/src/main/java/code/name/monkey/retromusic/util/FileUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/FileUtil.java @@ -47,7 +47,7 @@ public final class FileUtil { @NonNull public static Observable> matchFilesWithMediaStore(@NonNull Context context, @Nullable List files) { - return SongLoader.Companion.getSongs(makeSongCursor(context, files)); + return SongLoader.INSTANCE.getSongs(makeSongCursor(context, files)); } public static String safeGetCanonicalPath(File file) { @@ -75,7 +75,7 @@ public final class FileUtil { } } - Cursor songCursor = SongLoader.Companion.makeSongCursor(context, selection, selection == null ? null : paths); + Cursor songCursor = SongLoader.INSTANCE.makeSongCursor(context, selection, selection == null ? null : paths); return songCursor == null ? null : new SortedCursor(songCursor, paths, MediaStore.Audio.AudioColumns.DATA); diff --git a/app/src/main/java/code/name/monkey/retromusic/util/MusicUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/MusicUtil.java index 1c082beb..bbbf7e77 100644 --- a/app/src/main/java/code/name/monkey/retromusic/util/MusicUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/MusicUtil.java @@ -65,7 +65,7 @@ public class MusicUtil { .putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName(), - new File(song.data))) + new File(song.getData()))) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) .setType("audio/*"); } catch (IllegalArgumentException e) { @@ -142,7 +142,7 @@ public class MusicUtil { long duration = 0; for (int i = 0; i < songs.size(); i++) { - duration += songs.get(i).duration; + duration += songs.get(i).getDuration(); } return songCount + " " + songString + " • " + MusicUtil.getReadableDurationString(duration); @@ -207,7 +207,7 @@ public class MusicUtil { final StringBuilder selection = new StringBuilder(); selection.append(BaseColumns._ID + " IN ("); for (int i = 0; i < songs.size(); i++) { - selection.append(songs.get(i).id); + selection.append(songs.get(i).getId()); if (i < songs.size() - 1) { selection.append(","); } @@ -224,8 +224,8 @@ public class MusicUtil { cursor.moveToFirst(); while (!cursor.isAfterLast()) { final int id = cursor.getInt(0); - Song song = SongLoader.Companion.getSong(activity, id).blockingFirst(); - MusicPlayerRemote.removeFromQueue(song); + Song song = SongLoader.INSTANCE.getSong(activity, id).blockingFirst(); + MusicPlayerRemote.INSTANCE.removeFromQueue(song); cursor.moveToNext(); } @@ -271,7 +271,7 @@ public class MusicUtil { public static String getLyrics(Song song) { String lyrics = null; - File file = new File(song.data); + File file = new File(song.getData()); try { lyrics = AudioFileIO.read(file).getTagOrCreateDefault().getFirst(FieldKey.LYRICS); @@ -286,7 +286,7 @@ public class MusicUtil { if (dir != null && dir.exists() && dir.isDirectory()) { String format = ".*%s.*\\.(lrc|txt)"; String filename = Pattern.quote(FileUtil.stripExtension(file.getName())); - String songtitle = Pattern.quote(song.title); + String songtitle = Pattern.quote(song.getTitle()); final ArrayList patterns = new ArrayList<>(); patterns.add(Pattern.compile(String.format(format, filename), @@ -341,11 +341,11 @@ public class MusicUtil { } private static Observable getFavoritesPlaylist(@NonNull final Context context) { - return PlaylistLoader.getPlaylist(context, context.getString(R.string.favorites)); + return PlaylistLoader.INSTANCE.getPlaylist(context, context.getString(R.string.favorites)); } private static Observable getOrCreateFavoritesPlaylist(@NonNull final Context context) { - return PlaylistLoader.getPlaylist(context, + return PlaylistLoader.INSTANCE.getPlaylist(context, PlaylistsUtil.createPlaylist(context, context.getString(R.string.favorites))); } @@ -359,7 +359,7 @@ public class MusicUtil { //getFavoritesPlaylist(context).blockingFirst().id.subscribe(MusicUtil::setPlaylist); //return PlaylistsUtil.doPlaylistContains(context, getFavoritesPlaylist(context).blockingFirst().id, song.id); return PlaylistsUtil - .doPlaylistContains(context, getFavoritesPlaylist(context).blockingFirst().id, song.id); + .doPlaylistContains(context, getFavoritesPlaylist(context).blockingFirst().id, song.getId()); } public static boolean isArtistNameUnknown(@Nullable String artistName) { @@ -401,7 +401,7 @@ public class MusicUtil { public static long getTotalDuration(@NonNull final Context context, @NonNull List songs) { long duration = 0; for (int i = 0; i < songs.size(); i++) { - duration += songs.get(i).duration; + duration += songs.get(i).getDuration(); } return duration; } diff --git a/app/src/main/java/code/name/monkey/retromusic/util/NavigationUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/NavigationUtil.java index 5308b169..44ad3fcb 100755 --- a/app/src/main/java/code/name/monkey/retromusic/util/NavigationUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/NavigationUtil.java @@ -18,12 +18,12 @@ import code.name.monkey.retromusic.helper.MusicPlayerRemote; import code.name.monkey.retromusic.model.Genre; import code.name.monkey.retromusic.model.Playlist; import code.name.monkey.retromusic.ui.activities.AboutActivity; +import code.name.monkey.retromusic.ui.activities.AlbumDetailsActivity; import code.name.monkey.retromusic.ui.activities.ArtistDetailActivity; import code.name.monkey.retromusic.ui.activities.EqualizerActivity; import code.name.monkey.retromusic.ui.activities.GenreDetailsActivity; import code.name.monkey.retromusic.ui.activities.LicenseActivity; import code.name.monkey.retromusic.ui.activities.LyricsActivity; -import code.name.monkey.retromusic.ui.activities.NowPayingActivity; import code.name.monkey.retromusic.ui.activities.PlayingQueueActivity; import code.name.monkey.retromusic.ui.activities.PlaylistDetailActivity; import code.name.monkey.retromusic.ui.activities.ProVersionActivity; @@ -32,8 +32,6 @@ import code.name.monkey.retromusic.ui.activities.SettingsActivity; import code.name.monkey.retromusic.ui.activities.SupportDevelopmentActivity; import code.name.monkey.retromusic.ui.activities.UserInfoActivity; import code.name.monkey.retromusic.ui.activities.WhatsNewActivity; -import code.name.monkey.retromusic.ui.activities.AlbumDetailsActivity; -import code.name.monkey.retromusic.ui.activities.base.AbsSlidingMusicPanelActivity; import static code.name.monkey.retromusic.Constants.RATE_ON_GOOGLE_PLAY; import static code.name.monkey.retromusic.ui.activities.GenreDetailsActivity.EXTRA_GENRE_ID; @@ -75,7 +73,7 @@ public class NavigationUtil { } private static void stockEqalizer(@NonNull Activity activity) { - final int sessionId = MusicPlayerRemote.getAudioSessionId(); + final int sessionId = MusicPlayerRemote.INSTANCE.getAudioSessionId(); if (sessionId == AudioEffect.ERROR_BAD_VALUE) { Toast.makeText(activity, activity.getResources().getString(R.string.no_audio_ID), Toast.LENGTH_LONG).show(); @@ -149,12 +147,11 @@ public class NavigationUtil { } public static void gotoNowPlayingActivity(Context context, @Nullable Pair... sharedElements) { - ActivityCompat.startActivity(context, new Intent(context, NowPayingActivity.class), - ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context, sharedElements).toBundle()); + //ActivityCompat.startActivity(context, new Intent(context, NowPayingActivity.class), ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context, sharedElements).toBundle()); } public static void gotoNowPlaying(Activity activity) { - ActivityCompat.startActivity(activity, new Intent(activity, NowPayingActivity.class),null); + //ActivityCompat.startActivity(activity, new Intent(activity, NowPayingActivity.class),null); } } diff --git a/app/src/main/java/code/name/monkey/retromusic/util/PlaylistsUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/PlaylistsUtil.java index 920224f4..c016d6de 100644 --- a/app/src/main/java/code/name/monkey/retromusic/util/PlaylistsUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/PlaylistsUtil.java @@ -149,7 +149,7 @@ public class PlaylistsUtil { for (int i = 0; i < len; i++) { contentValues[i] = new ContentValues(); contentValues[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, base + offset + i); - contentValues[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songs.get(offset + i).id); + contentValues[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songs.get(offset + i).getId()); } return contentValues; } @@ -158,7 +158,7 @@ public class PlaylistsUtil { Uri uri = MediaStore.Audio.Playlists.Members.getContentUri( "external", playlistId); String selection = MediaStore.Audio.Playlists.Members.AUDIO_ID + " =?"; - String[] selectionArgs = new String[]{String.valueOf(song.id)}; + String[] selectionArgs = new String[]{String.valueOf(song.getId())}; try { context.getContentResolver().delete(uri, selection, selectionArgs); @@ -244,7 +244,7 @@ public class PlaylistsUtil { } public static Observable savePlaylist(Context context, Playlist playlist) { - return M3UWriter.write(context, new File(Environment.getExternalStorageDirectory(), "Playlists"), playlist); + return M3UWriter.Companion.write(context, new File(Environment.getExternalStorageDirectory(), "Playlists"), playlist); } } \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/util/PreferenceUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/PreferenceUtil.java index 2697890e..9b93568b 100644 --- a/app/src/main/java/code/name/monkey/retromusic/util/PreferenceUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/PreferenceUtil.java @@ -122,7 +122,7 @@ public final class PreferenceUtil { public static PreferenceUtil getInstance() { if (sInstance == null) { - sInstance = new PreferenceUtil(RetroApplication.getContext()); + sInstance = new PreferenceUtil(RetroApplication.Companion.getContext()); } return sInstance; } @@ -145,7 +145,7 @@ public final class PreferenceUtil { } public final String getArtistSortOrder() { - return mPreferences.getString(ARTIST_SORT_ORDER, SortOrder.ArtistSortOrder.ARTIST_A_Z); + return mPreferences.getString(ARTIST_SORT_ORDER, SortOrder.ArtistSortOrder.Companion.getARTIST_A_Z()); } public void setArtistSortOrder(final String sortOrder) { @@ -155,7 +155,7 @@ public final class PreferenceUtil { } public final String getArtistSongSortOrder() { - return mPreferences.getString(ARTIST_SONG_SORT_ORDER, SortOrder.ArtistSongSortOrder.SONG_A_Z); + return mPreferences.getString(ARTIST_SONG_SORT_ORDER, SortOrder.ArtistSongSortOrder.Companion.getSONG_A_Z()); } public final boolean isHomeBanner() { @@ -164,11 +164,11 @@ public final class PreferenceUtil { public final String getArtistAlbumSortOrder() { return mPreferences - .getString(ARTIST_ALBUM_SORT_ORDER, SortOrder.ArtistAlbumSortOrder.ALBUM_YEAR); + .getString(ARTIST_ALBUM_SORT_ORDER, SortOrder.ArtistAlbumSortOrder.Companion.getALBUM_YEAR()); } public final String getAlbumSortOrder() { - return mPreferences.getString(ALBUM_SORT_ORDER, SortOrder.AlbumSortOrder.ALBUM_A_Z); + return mPreferences.getString(ALBUM_SORT_ORDER, SortOrder.AlbumSortOrder.Companion.getALBUM_A_Z()); } public void setAlbumSortOrder(final String sortOrder) { @@ -179,11 +179,11 @@ public final class PreferenceUtil { public final String getAlbumSongSortOrder() { return mPreferences - .getString(ALBUM_SONG_SORT_ORDER, SortOrder.AlbumSongSortOrder.SONG_TRACK_LIST); + .getString(ALBUM_SONG_SORT_ORDER, SortOrder.AlbumSongSortOrder.Companion.getSONG_TRACK_LIST()); } public final String getSongSortOrder() { - return mPreferences.getString(SONG_SORT_ORDER, SortOrder.SongSortOrder.SONG_A_Z); + return mPreferences.getString(SONG_SORT_ORDER, SortOrder.SongSortOrder.Companion.getSONG_A_Z()); } public void setSongSortOrder(final String sortOrder) { @@ -193,7 +193,7 @@ public final class PreferenceUtil { } public final String getGenreSortOrder() { - return mPreferences.getString(GENRE_SORT_ORDER, SortOrder.GenreSortOrder.GENRE_A_Z); + return mPreferences.getString(GENRE_SORT_ORDER, SortOrder.GenreSortOrder.Companion.getGENRE_A_Z()); } public boolean isScreenOnEnabled() { @@ -327,7 +327,7 @@ public final class PreferenceUtil { return nowPlayingScreen; } } - return NowPlayingScreen.NORMAL; + return NowPlayingScreen.ADAPTIVE; } @SuppressLint("CommitPrefEdits") @@ -632,7 +632,7 @@ public final class PreferenceUtil { public String getAlbumDetailSongSortOrder() { return mPreferences - .getString(ALBUM_DETAIL_SONG_SORT_ORDER, SortOrder.AlbumSongSortOrder.SONG_TRACK_LIST); + .getString(ALBUM_DETAIL_SONG_SORT_ORDER, SortOrder.AlbumSongSortOrder.Companion.getSONG_TRACK_LIST()); } public void setAlbumDetailSongSortOrder(String sortOrder) { @@ -643,7 +643,7 @@ public final class PreferenceUtil { public String getArtistDetailSongSortOrder() { return mPreferences - .getString(ARTIST_DETAIL_SONG_SORT_ORDER, SortOrder.ArtistSongSortOrder.SONG_A_Z); + .getString(ARTIST_DETAIL_SONG_SORT_ORDER, SortOrder.ArtistSongSortOrder.Companion.getSONG_A_Z()); } public void setArtistDetailSongSortOrder(String sortOrder) { diff --git a/app/src/main/java/code/name/monkey/retromusic/util/RetroUtil.java b/app/src/main/java/code/name/monkey/retromusic/util/RetroUtil.java index 30cb0e0a..01bfe30b 100755 --- a/app/src/main/java/code/name/monkey/retromusic/util/RetroUtil.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/RetroUtil.java @@ -84,11 +84,11 @@ public class RetroUtil { } public static boolean isTablet() { - return RetroApplication.getContext().getResources().getConfiguration().smallestScreenWidthDp >= 600; + return RetroApplication.Companion.getContext().getResources().getConfiguration().smallestScreenWidthDp >= 600; } public static boolean isLandscape() { - return RetroApplication.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; + return RetroApplication.Companion.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @@ -199,8 +199,8 @@ public class RetroUtil { public static Drawable getTintedDrawable(@DrawableRes int id) { return TintHelper - .createTintedDrawable(ContextCompat.getDrawable(RetroApplication.getInstance(), id), - ThemeStore.accentColor(RetroApplication.getInstance())); + .createTintedDrawable(ContextCompat.getDrawable(RetroApplication.Companion.getInstance(), id), + ThemeStore.accentColor(RetroApplication.Companion.getInstance())); } public static Bitmap createBitmap(Drawable drawable, float sizeMultiplier) { @@ -297,9 +297,9 @@ public class RetroUtil { public static int getStatusBarHeight() { int result = 0; - int resourceId = RetroApplication.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android"); + int resourceId = RetroApplication.Companion.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { - result = RetroApplication.getContext().getResources().getDimensionPixelSize(resourceId); + result = RetroApplication.Companion.getContext().getResources().getDimensionPixelSize(resourceId); } return result; } @@ -415,7 +415,7 @@ public class RetroUtil { } public static boolean checkNavigationBarHeight() { - Resources resources = RetroApplication.getContext().getResources(); + Resources resources = RetroApplication.Companion.getContext().getResources(); int orientation = resources.getConfiguration().orientation; if (!hasNavBar(resources)) { return false; diff --git a/app/src/main/java/code/name/monkey/retromusic/util/SystemUtils.java b/app/src/main/java/code/name/monkey/retromusic/util/SystemUtils.java index 62eaf510..2d4b7199 100644 --- a/app/src/main/java/code/name/monkey/retromusic/util/SystemUtils.java +++ b/app/src/main/java/code/name/monkey/retromusic/util/SystemUtils.java @@ -38,9 +38,9 @@ public class SystemUtils { public static int getNavigationBarHeight() { int result = 0; - int resourceId = RetroApplication.getContext().getResources().getIdentifier("navigation_bar_height", "dimen", "android"); + int resourceId = RetroApplication.Companion.getContext().getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { - result = RetroApplication.getContext().getResources().getDimensionPixelSize(resourceId); + result = RetroApplication.Companion.getContext().getResources().getDimensionPixelSize(resourceId); } return result; } diff --git a/app/src/main/java/code/name/monkey/retromusic/views/MetalRecyclerViewPager.java b/app/src/main/java/code/name/monkey/retromusic/views/MetalRecyclerViewPager.java deleted file mode 100644 index ae117ce0..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/views/MetalRecyclerViewPager.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2017. Alexander Bilchuk - * - * 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 code.name.monkey.retromusic.views; - -import android.content.Context; -import android.content.res.TypedArray; -import android.util.AttributeSet; -import android.util.DisplayMetrics; -import android.view.View; -import android.view.ViewGroup; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.PagerSnapHelper; -import androidx.recyclerview.widget.RecyclerView; -import androidx.recyclerview.widget.SnapHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; -import code.name.monkey.retromusic.util.RetroUtil; - -public class MetalRecyclerViewPager extends RecyclerView { - - private int itemMargin; - - public MetalRecyclerViewPager(Context context) { - super(context); - init(context, null); - } - - public MetalRecyclerViewPager(Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - init(context, attrs); - } - - public MetalRecyclerViewPager(Context context, @Nullable AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - init(context, attrs); - } - - private void init(Context context, @Nullable AttributeSet attrs) { - if (attrs != null) { - TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MetalRecyclerViewPager, 0, 0); - itemMargin = (int) typedArray.getDimension(R.styleable.MetalRecyclerViewPager_itemMargin, 0f); - typedArray.recycle(); - } - - setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)); - SnapHelper snapHelper = new PagerSnapHelper(); - snapHelper.attachToRecyclerView(this); - } - - public void setAdapter(Adapter adapter) { - if (MetalAdapter.class.isInstance(adapter)) { - MetalAdapter metalAdapter = (MetalAdapter) adapter; - metalAdapter.setItemMargin(itemMargin); - metalAdapter.updateDisplayMetrics(); - } else { - throw new IllegalArgumentException("Only MetalAdapter is allowed here"); - } - super.setAdapter(adapter); - } - - public static abstract class MetalAdapter extends RecyclerView.Adapter { - - private DisplayMetrics metrics; - private int itemMargin; - private int itemWidth; - - public MetalAdapter(@NonNull DisplayMetrics metrics) { - this.metrics = metrics; - } - - void setItemMargin(int itemMargin) { - this.itemMargin = itemMargin; - } - - void updateDisplayMetrics() { - if (RetroUtil.isTablet()) { - itemWidth = (metrics.widthPixels / 2) - itemMargin * 3; - } else { - itemWidth = metrics.widthPixels - itemMargin ; - } - } - - @Override - public void onBindViewHolder(@NonNull VH holder, int position) { - int currentItemWidth = itemWidth; - - if (position == 0) { - currentItemWidth += itemMargin; - holder.rootLayout.setPadding(0, 0, 0, 0); - } else if (position == getItemCount() - 1) { - currentItemWidth += itemMargin; - holder.rootLayout.setPadding(0, 0, 0, 0); - } - - int height = holder.rootLayout.getLayoutParams().height; - holder.rootLayout.setLayoutParams(new ViewGroup.LayoutParams(currentItemWidth, height)); - } - - - } - - public static abstract class MetalViewHolder extends MediaEntryViewHolder { - - ViewGroup rootLayout; - - public MetalViewHolder(View itemView) { - super(itemView); - rootLayout = (ViewGroup) itemView.findViewById(R.id.root_layout); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/views/MetalRecyclerViewPager.kt b/app/src/main/java/code/name/monkey/retromusic/views/MetalRecyclerViewPager.kt new file mode 100644 index 00000000..958637a1 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/views/MetalRecyclerViewPager.kt @@ -0,0 +1,86 @@ +package code.name.monkey.retromusic.views + +import android.content.Context +import android.util.AttributeSet +import android.util.DisplayMetrics +import android.view.View +import android.view.ViewGroup +import androidx.annotation.NonNull +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.PagerSnapHelper +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import code.name.monkey.retromusic.util.RetroUtil + +class MetalRecyclerViewPager : RecyclerView { + constructor(context: Context) : super(context) { + init(context, null) + } + + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { + init(context, attrs) + } + + constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { + init(context, attrs) + } + + private var itemMargin: Int = 0 + + fun init(context: Context, attrs: AttributeSet?) { + val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MetalRecyclerViewPager, 0, 0) + itemMargin = typedArray.getDimension(R.styleable.MetalRecyclerViewPager_itemMargin, 0f).toInt() + typedArray.recycle() + + layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) + val snapHelper = PagerSnapHelper() + snapHelper.attachToRecyclerView(this) + } + + override fun setAdapter(adapter: Adapter<*>?) { + if (adapter is MetalAdapter) { + adapter.setItemMargin(itemMargin) + adapter.updateDisplayMetrics() + } else { + throw IllegalArgumentException("Only MetalAdapter is allowed here") + } + super.setAdapter(adapter) + } + + abstract class MetalAdapter(@NonNull val displayMetrics: DisplayMetrics) : RecyclerView.Adapter() { + private var itemMargin: Int = 0 + private var itemWidth: Int = 0 + + fun setItemMargin(itemMargin: Int) { + this.itemMargin = itemMargin + } + + fun updateDisplayMetrics() { + itemWidth = if (RetroUtil.isTablet()) { + displayMetrics.widthPixels / 2 - itemMargin * 3 + } else { + displayMetrics.widthPixels - itemMargin + } + } + + override fun onBindViewHolder(holder: VH, position: Int) { + var currentItemWidth = itemWidth + + if (position == 0) { + currentItemWidth += itemMargin + holder.rootLayout.setPadding(0, 0, 0, 0) + } else if (position == itemCount - 1) { + currentItemWidth += itemMargin + holder.rootLayout.setPadding(0, 0, 0, 0) + } + + val height = holder.rootLayout.layoutParams.height + holder.rootLayout.layoutParams = ViewGroup.LayoutParams(currentItemWidth, height) + } + } + + abstract class MetalViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + var rootLayout: ViewGroup = itemView.findViewById(R.id.root_layout) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/views/TintIconColorToolbar.java b/app/src/main/java/code/name/monkey/retromusic/views/TintIconColorToolbar.java deleted file mode 100644 index eb3d190f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/views/TintIconColorToolbar.java +++ /dev/null @@ -1,33 +0,0 @@ -package code.name.monkey.retromusic.views; - -import android.content.Context; -import android.graphics.PorterDuff; -import android.graphics.drawable.Drawable; -import android.util.AttributeSet; - -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import code.name.monkey.appthemehelper.ThemeStore; - -public class TintIconColorToolbar extends Toolbar { - public TintIconColorToolbar(Context context) { - super(context); - } - - public TintIconColorToolbar(Context context, @Nullable AttributeSet attrs) { - super(context, attrs); - } - - public TintIconColorToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - - @Override - public void setNavigationIcon(@Nullable Drawable icon) { - super.setNavigationIcon(icon); - if (icon != null) { - icon.setColorFilter(ThemeStore.accentColor(getContext()), PorterDuff.Mode.SRC_IN); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/views/TintIconColorToolbar.kt b/app/src/main/java/code/name/monkey/retromusic/views/TintIconColorToolbar.kt new file mode 100644 index 00000000..ee5ae245 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/views/TintIconColorToolbar.kt @@ -0,0 +1,22 @@ +package code.name.monkey.retromusic.views + +import android.content.Context +import android.graphics.PorterDuff +import android.graphics.drawable.Drawable +import android.util.AttributeSet +import androidx.appcompat.widget.Toolbar +import code.name.monkey.appthemehelper.ThemeStore + +class TintIconColorToolbar : Toolbar { + constructor(context: Context) : super(context) + + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) + + constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) + + + override fun setNavigationIcon(icon: Drawable?) { + super.setNavigationIcon(icon) + icon?.setColorFilter(ThemeStore.accentColor(context), PorterDuff.Mode.SRC_IN) + } +} diff --git a/app/src/main/res/layout-land/activity_album.xml b/app/src/main/res/layout-land/activity_album.xml index f3cefaa8..a1078fab 100644 --- a/app/src/main/res/layout-land/activity_album.xml +++ b/app/src/main/res/layout-land/activity_album.xml @@ -30,7 +30,7 @@ @@ -16,12 +16,14 @@ @@ -40,7 +42,7 @@ diff --git a/app/src/main/res/layout/activity_whats_new.xml b/app/src/main/res/layout/activity_whats_new.xml index 719c143a..b4086b12 100644 --- a/app/src/main/res/layout/activity_whats_new.xml +++ b/app/src/main/res/layout/activity_whats_new.xml @@ -7,7 +7,7 @@ tools:context="code.name.monkey.retromusic.ui.activities.WhatsNewActivity"> @@ -34,7 +34,7 @@ diff --git a/app/src/main/res/layout/fragment_volume.xml b/app/src/main/res/layout/fragment_volume.xml index 8f160c01..ebe69c00 100755 --- a/app/src/main/res/layout/fragment_volume.xml +++ b/app/src/main/res/layout/fragment_volume.xml @@ -1,14 +1,14 @@