From 63e32760987ee6b0ca9a3af5523e05e4443d1307 Mon Sep 17 00:00:00 2001 From: h4h13 Date: Thu, 6 Dec 2018 14:22:57 +0530 Subject: [PATCH] Removed butter knife --- .../retromusic/dialogs/AddToPlaylistDialog.kt | 6 +- .../dialogs/CreatePlaylistDialog.kt | 6 +- .../dialogs/DeletePlaylistDialog.kt | 5 +- .../retromusic/dialogs/DeleteSongsDialog.java | 100 ----- .../retromusic/dialogs/DeleteSongsDialog.kt | 69 ++++ .../dialogs/RemoveFromPlaylistDialog.kt | 6 +- .../dialogs/RenamePlaylistDialog.kt | 6 +- .../retromusic/dialogs/SleepTimerDialog.java | 193 --------- .../retromusic/dialogs/SleepTimerDialog.kt | 138 +++++++ .../retromusic/dialogs/SongDetailDialog.java | 124 ------ .../retromusic/dialogs/SongDetailDialog.kt | 113 ++++++ .../retromusic/dialogs/SongShareDialog.java | 77 ---- .../retromusic/dialogs/SongShareDialog.kt | 56 +++ .../retromusic/glide/ArtistGlideRequest.java | 141 ------- .../retromusic/glide/ArtistGlideRequest.kt | 112 ++++++ .../retromusic/glide/BlurTransformation.java | 147 ------- .../retromusic/glide/BlurTransformation.kt | 142 +++++++ .../glide/RetroMusicGlideModule.java | 27 -- .../retromusic/glide/RetroMusicGlideModule.kt | 25 ++ .../retromusic/glide/SongGlideRequest.java | 124 ------ .../retromusic/glide/SongGlideRequest.kt | 102 +++++ .../glide/artistimage/ArtistImage.java | 12 - .../glide/artistimage/ArtistImage.kt | 4 + .../glide/artistimage/ArtistImageFetcher.java | 83 ---- .../glide/artistimage/ArtistImageFetcher.kt | 69 ++++ .../glide/artistimage/ArtistImageLoader.java | 68 ---- .../glide/artistimage/ArtistImageLoader.kt | 52 +++ .../glide/audiocover/AudioFileCover.java | 10 - .../glide/audiocover/AudioFileCover.kt | 4 + .../audiocover/AudioFileCoverFetcher.java | 95 ----- .../glide/audiocover/AudioFileCoverFetcher.kt | 87 ++++ .../audiocover/AudioFileCoverLoader.java | 32 -- .../glide/audiocover/AudioFileCoverLoader.kt | 28 ++ .../glide/palette/BitmapPaletteResource.java | 34 -- .../glide/palette/BitmapPaletteResource.kt | 23 ++ .../palette/BitmapPaletteTranscoder.java | 34 -- .../glide/palette/BitmapPaletteTranscoder.kt | 25 ++ .../glide/palette/BitmapPaletteWrapper.java | 22 - .../glide/palette/BitmapPaletteWrapper.kt | 6 + .../monkey/retromusic/mvp/BasePresenter.java | 12 - .../monkey/retromusic/mvp/BasePresenter.kt | 12 + .../name/monkey/retromusic/mvp/BaseView.java | 15 - .../name/monkey/retromusic/mvp/BaseView.kt | 15 + .../name/monkey/retromusic/mvp/Presenter.java | 27 -- .../name/monkey/retromusic/mvp/Presenter.kt | 16 + .../mvp/contract/AlbumContract.java | 19 - .../retromusic/mvp/contract/AlbumContract.kt | 17 + .../mvp/contract/AlbumDetailsContract.java | 18 - .../mvp/contract/AlbumDetailsContract.kt | 16 + .../mvp/contract/ArtistContract.java | 23 -- .../retromusic/mvp/contract/ArtistContract.kt | 21 + .../mvp/contract/ArtistDetailContract.java | 21 - .../mvp/contract/ArtistDetailContract.kt | 19 + .../mvp/contract/GenreContract.java | 21 - .../retromusic/mvp/contract/GenreContract.kt | 19 + .../mvp/contract/GenreDetailsContract.java | 20 - .../mvp/contract/GenreDetailsContract.kt | 19 + .../retromusic/mvp/contract/HomeContract.java | 47 --- .../retromusic/mvp/contract/HomeContract.kt | 47 +++ .../mvp/contract/PlaylistContract.java | 21 - .../mvp/contract/PlaylistContract.kt | 19 + .../mvp/contract/PlaylistSongsContract.java | 23 -- .../mvp/contract/PlaylistSongsContract.kt | 21 + .../mvp/contract/SearchContract.java | 21 - .../retromusic/mvp/contract/SearchContract.kt | 19 + .../retromusic/mvp/contract/SongContract.java | 24 -- .../retromusic/mvp/contract/SongContract.kt | 22 + .../mvp/presenter/AlbumDetailsPresenter.java | 54 --- .../mvp/presenter/AlbumDetailsPresenter.kt | 39 ++ .../mvp/presenter/AlbumPresenter.java | 49 --- .../mvp/presenter/AlbumPresenter.kt | 36 ++ .../mvp/presenter/ArtistDetailsPresenter.java | 56 --- .../mvp/presenter/ArtistDetailsPresenter.kt | 42 ++ .../mvp/presenter/ArtistPresenter.java | 47 --- .../mvp/presenter/ArtistPresenter.kt | 35 ++ .../mvp/presenter/GenreDetailsPresenter.java | 56 --- .../mvp/presenter/GenreDetailsPresenter.kt | 41 ++ .../mvp/presenter/GenrePresenter.java | 53 --- .../mvp/presenter/GenrePresenter.kt | 40 ++ .../mvp/presenter/HomePresenter.java | 126 ------ .../retromusic/mvp/presenter/HomePresenter.kt | 105 +++++ .../mvp/presenter/PlaylistPresenter.java | 54 --- .../mvp/presenter/PlaylistPresenter.kt | 40 ++ .../mvp/presenter/PlaylistSongsPresenter.java | 48 --- .../mvp/presenter/PlaylistSongsPresenter.kt | 32 ++ .../mvp/presenter/SearchPresenter.java | 52 --- .../mvp/presenter/SearchPresenter.kt | 40 ++ .../mvp/presenter/SongPresenter.java | 53 --- .../retromusic/mvp/presenter/SongPresenter.kt | 39 ++ .../AlbumCoverStylePreference.java | 25 -- .../preferences/AlbumCoverStylePreference.kt | 17 + .../AlbumCoverStylePreferenceDialog.java | 137 ------- .../AlbumCoverStylePreferenceDialog.kt | 116 ++++++ .../preferences/BlacklistPreference.java | 25 -- .../preferences/BlacklistPreference.kt | 17 + .../NowPlayingScreenPreference.java | 25 -- .../preferences/NowPlayingScreenPreference.kt | 17 + .../NowPlayingScreenPreferenceDialog.java | 166 -------- .../NowPlayingScreenPreferenceDialog.kt | 144 +++++++ .../providers/interfaces/Repository.java | 60 --- .../providers/interfaces/Repository.kt | 60 +++ .../retromusic/service/MusicService.java | 2 +- .../service/daydream/RetroMusicAlbums.kt | 161 -------- .../notification/PlayingNotification.java | 82 ---- .../notification/PlayingNotification.kt | 83 ++++ .../notification/PlayingNotificationImpl.java | 225 ----------- .../notification/PlayingNotificationImpl.kt | 219 ++++++++++ .../PlayingNotificationImpl24.java | 143 ------- .../notification/PlayingNotificationImpl24.kt | 138 +++++++ .../notification/PlayingNotificationOreo.kt | 4 +- .../transform/CarousalPagerTransformer.java | 45 --- .../transform/CarousalPagerTransformer.kt | 43 ++ .../transform/CascadingPageTransformer.java | 57 --- .../transform/CascadingPageTransformer.kt | 55 +++ .../transform/DepthTransformation.java | 30 -- .../transform/DepthTransformation.kt | 27 ++ .../transform/HingeTransformation.java | 35 -- .../transform/HingeTransformation.kt | 32 ++ .../HorizontalFlipTransformation.java | 39 -- .../transform/HorizontalFlipTransformation.kt | 36 ++ .../transform/NormalPageTransformer.java | 49 --- .../transform/NormalPageTransformer.kt | 49 +++ .../transform/ParallaxPagerTransformer.java | 57 --- .../transform/ParallaxPagerTransformer.kt | 45 +++ .../transform/StackPagerTransformer.java | 28 -- .../transform/StackPagerTransformer.kt | 28 ++ .../transform/VerticalFlipTransformation.java | 42 -- .../transform/VerticalFlipTransformation.kt | 39 ++ .../ui/activities/AboutActivity.java | 227 ----------- .../retromusic/ui/activities/AboutActivity.kt | 181 +++++++++ .../ui/activities/AlbumDetailsActivity.kt | 16 +- .../ui/activities/ArtistDetailActivity.kt | 5 +- .../ui/activities/EqualizerActivity.java | 232 ----------- .../ui/activities/EqualizerActivity.kt | 189 +++++++++ .../ui/activities/ErrorHandlerActivity.java | 2 +- .../ui/activities/GenreDetailsActivity.kt | 7 +- .../ui/activities/LicenseActivity.java | 62 --- .../ui/activities/LicenseActivity.kt | 44 ++ .../ui/activities/LyricsActivity.java | 367 ----------------- .../ui/activities/LyricsActivity.kt | 307 ++++++++++++++ .../retromusic/ui/activities/MainActivity.kt | 24 +- .../ui/activities/PlayingQueueActivity.java | 203 ---------- .../ui/activities/PlayingQueueActivity.kt | 152 +++++++ .../ui/activities/PlaylistDetailActivity.kt | 6 +- .../ui/activities/ProVersionActivity.java | 214 ---------- .../ui/activities/ProVersionActivity.kt | 167 ++++++++ .../ui/activities/SearchActivity.java | 252 ------------ .../ui/activities/SearchActivity.kt | 201 ++++++++++ .../ui/activities/SettingsActivity.kt | 2 - .../SupportDevelopmentActivity.java | 379 ------------------ .../activities/SupportDevelopmentActivity.kt | 252 ++++++++++++ .../ui/activities/UserInfoActivity.java | 296 -------------- .../ui/activities/UserInfoActivity.kt | 233 +++++++++++ .../ui/activities/WhatsNewActivity.kt | 3 +- .../base/AbsSlidingMusicPanelActivity.kt | 2 - .../tageditor/AbsTagEditorActivity.java | 375 ----------------- .../tageditor/AbsTagEditorActivity.kt | 332 +++++++++++++++ .../tageditor/AlbumTagEditorActivity.java | 307 -------------- .../tageditor/AlbumTagEditorActivity.kt | 232 +++++++++++ .../tageditor/SongTagEditorActivity.java | 179 --------- .../tageditor/SongTagEditorActivity.kt | 117 ++++++ .../tageditor/WriteTagsAsyncTask.java | 10 +- .../ui/adapter/CollageSongAdapter.java | 102 ----- .../ui/adapter/CollageSongAdapter.kt | 68 ++++ .../adapter/album/AlbumCoverPagerAdapter.kt | 6 +- .../ui/adapter/playlist/PlaylistAdapter.kt | 2 - .../ui/fragments/AlbumCoverStyle.java | 28 -- .../ui/fragments/AlbumCoverStyle.kt | 19 + ...PlayingScreen.java => NowPlayingScreen.kt} | 27 +- .../fragments/mainactivity/AlbumsFragment.kt | 4 +- .../fragments/mainactivity/ArtistsFragment.kt | 4 +- .../fragments/mainactivity/GenreFragment.kt | 4 +- .../fragments/mainactivity/LibraryFragment.kt | 86 ++-- .../mainactivity/PlaylistsFragment.kt | 5 +- .../fragments/mainactivity/SongsFragment.kt | 4 +- .../mainactivity/folders/FoldersFragment.java | 8 +- .../mainactivity/home/BannerHomeFragment.kt | 4 +- .../fragments/player/color/ColorFragment.kt | 2 +- .../settings/AbsSettingsFragment.java | 4 +- .../ui/fragments/settings/AudioSettings.java | 49 --- .../ui/fragments/settings/AudioSettings.kt | 46 +++ .../settings/ImageSettingFragment.java | 28 -- .../settings/ImageSettingFragment.kt | 26 ++ .../NotificationSettingsFragment.java | 43 -- .../settings/NotificationSettingsFragment.kt | 41 ++ .../settings/NowPlayingSettingsFragment.java | 80 ---- .../settings/NowPlayingSettingsFragment.kt | 64 +++ .../settings/OtherSettingsFragment.java | 23 -- .../settings/OtherSettingsFragment.kt | 21 + .../settings/PersonaizeSettingsFragment.java | 65 --- .../settings/PersonaizeSettingsFragment.kt | 55 +++ .../settings/ThemeSettingsFragment.java | 122 ------ .../settings/ThemeSettingsFragment.kt | 108 +++++ .../retromusic/util/PreferenceUtil.java | 10 +- 194 files changed, 5984 insertions(+), 7491 deletions(-) delete mode 100644 app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.kt delete mode 100755 app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.java create mode 100755 app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.kt delete mode 100755 app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.java create mode 100755 app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.kt delete mode 100755 app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.java create mode 100755 app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.kt delete mode 100755 app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.java create mode 100755 app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.kt rename app/src/main/java/code/name/monkey/retromusic/ui/fragments/{NowPlayingScreen.java => NowPlayingScreen.kt} (53%) delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.kt delete mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.java create mode 100644 app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.kt diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.kt index b8b68391..5c7b8481 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.kt +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/AddToPlaylistDialog.kt @@ -6,7 +6,6 @@ import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.retromusic.R import code.name.monkey.retromusic.loaders.PlaylistLoader @@ -24,9 +23,8 @@ class AddToPlaylistDialog : RoundedBottomSheetDialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - val layout = inflater.inflate(R.layout.dialog_add_to_playlist, container, false) - ButterKnife.bind(this, layout) - return layout + + return inflater.inflate(R.layout.dialog_add_to_playlist, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/CreatePlaylistDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/CreatePlaylistDialog.kt index f2245eba..73982455 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/CreatePlaylistDialog.kt +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/CreatePlaylistDialog.kt @@ -6,7 +6,6 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.MaterialUtil import code.name.monkey.retromusic.R @@ -23,9 +22,8 @@ class CreatePlaylistDialog : RoundedBottomSheetDialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - val layout = inflater.inflate(R.layout.dialog_playlist, container, false) - ButterKnife.bind(this, layout) - return layout + + return inflater.inflate(R.layout.dialog_playlist, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/DeletePlaylistDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/DeletePlaylistDialog.kt index 78a2969b..f2b91e05 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/DeletePlaylistDialog.kt +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/DeletePlaylistDialog.kt @@ -5,7 +5,6 @@ import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.retromusic.R import code.name.monkey.retromusic.model.Playlist @@ -19,9 +18,7 @@ class DeletePlaylistDialog : RoundedBottomSheetDialogFragment() { 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 + return inflater.inflate(R.layout.dialog_remove_from_playlist, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 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 deleted file mode 100644 index 0f725635..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.java +++ /dev/null @@ -1,100 +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 com.google.android.material.button.MaterialButton; - -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.appthemehelper.util.MaterialUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment; - -public class DeleteSongsDialog extends RoundedBottomSheetDialogFragment { - @BindView(R.id.action_delete) - MaterialButton actionDelete; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.action_cancel) - MaterialButton actionCancel; - - @NonNull - public static DeleteSongsDialog create(Song song) { - ArrayList list = new ArrayList<>(); - list.add(song); - return create(list); - } - - @NonNull - public static DeleteSongsDialog create(ArrayList songs) { - DeleteSongsDialog dialog = new DeleteSongsDialog(); - Bundle args = new Bundle(); - args.putParcelableArrayList("songs", songs); - dialog.setArguments(args); - return dialog; - } - - @OnClick({R.id.action_cancel, R.id.action_delete}) - void actions(View view) { - //noinspection ConstantConditions - final ArrayList songs = getArguments().getParcelableArrayList("songs"); - switch (view.getId()) { - case R.id.action_delete: - if (getActivity() == null) { - return; - } - if (songs != null) { - MusicUtil.deleteTracks(getActivity(), songs); - } - break; - default: - } - dismiss(); - } - - @SuppressWarnings("ConstantConditions") - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - title.setTextColor(ThemeStore.textColorPrimary(getContext())); - MaterialUtil.setTint(actionDelete, true); - MaterialUtil.setTint(actionCancel, false); - - //noinspection unchecked,ConstantConditions - final ArrayList songs = getArguments().getParcelableArrayList("songs"); - CharSequence content; - if (songs != null) { - 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).getTitle())); - } - this.title.setText(content); - } - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - View layout = inflater.inflate(R.layout.dialog_delete, container, false); - ButterKnife.bind(this, layout); - return layout; - } -} - diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.kt new file mode 100644 index 00000000..47c1cc06 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/DeleteSongsDialog.kt @@ -0,0 +1,69 @@ +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 code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.MaterialUtil +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment +import kotlinx.android.synthetic.main.dialog_delete.* +import java.util.* + +class DeleteSongsDialog : RoundedBottomSheetDialogFragment() { + + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + title.setTextColor(ThemeStore.textColorPrimary(context!!)) + MaterialUtil.setTint(actionDelete, true) + MaterialUtil.setTint(actionCancel, false) + + //noinspection unchecked,ConstantConditions + val songs = arguments!!.getParcelableArrayList("songs") + val content: CharSequence + if (songs != null) { + content = if (songs.size > 1) { + Html.fromHtml(getString(R.string.delete_x_songs, songs.size)) + } else { + Html.fromHtml(getString(R.string.delete_song_x, songs[0].title)) + } + this.title.text = content + } + actionDelete.setOnClickListener { + if (songs != null) { + MusicUtil.deleteTracks(activity!!, songs) + } + dismiss() + } + actionCancel.setOnClickListener { dismiss() } + } + + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.dialog_delete, container, false) + } + + companion object { + + fun create(song: Song): DeleteSongsDialog { + val list = ArrayList() + list.add(song) + return create(list) + } + + fun create(songs: ArrayList): DeleteSongsDialog { + val dialog = DeleteSongsDialog() + val args = Bundle() + args.putParcelableArrayList("songs", songs) + dialog.arguments = args + return dialog + } + } +} + 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 index 94988c5a..b24dbb6d 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.kt +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/RemoveFromPlaylistDialog.kt @@ -6,7 +6,6 @@ import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.retromusic.R import code.name.monkey.retromusic.model.PlaylistSong @@ -19,9 +18,8 @@ import java.util.* class RemoveFromPlaylistDialog : RoundedBottomSheetDialogFragment() { 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 + + return inflater.inflate(R.layout.dialog_remove_from_playlist, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/RenamePlaylistDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/RenamePlaylistDialog.kt index 53bc6cb5..4f9c7183 100644 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/RenamePlaylistDialog.kt +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/RenamePlaylistDialog.kt @@ -5,7 +5,6 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.MaterialUtil import code.name.monkey.retromusic.R @@ -17,9 +16,8 @@ class RenamePlaylistDialog : RoundedBottomSheetDialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - val layout = inflater.inflate(R.layout.dialog_playlist, container, false) - ButterKnife.bind(this, layout) - return layout + + return inflater.inflate(R.layout.dialog_playlist, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 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 deleted file mode 100755 index 3e661319..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.java +++ /dev/null @@ -1,193 +0,0 @@ -package code.name.monkey.retromusic.dialogs; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.graphics.PorterDuff; -import android.graphics.drawable.ClipDrawable; -import android.graphics.drawable.LayerDrawable; -import android.os.Bundle; -import android.os.CountDownTimer; -import android.os.SystemClock; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.SeekBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.google.android.material.button.MaterialButton; - -import java.util.Locale; - -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.appthemehelper.util.MaterialUtil; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.service.MusicService; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment; - -import static code.name.monkey.retromusic.Constants.ACTION_QUIT; - -public class SleepTimerDialog extends RoundedBottomSheetDialogFragment { - @BindView(R.id.seek_arc) - SeekBar seekArc; - - @BindView(R.id.timer_display) - TextView timerDisplay; - - @BindView(R.id.action_set) - MaterialButton setButton; - - @BindView(R.id.action_cancel) - MaterialButton cancelButton; - - @BindView(R.id.title) - TextView title; - private int seekArcProgress; - private TimerUpdater timerUpdater; - - @Override - public void onDismiss(DialogInterface dialog) { - super.onDismiss(dialog); - timerUpdater.cancel(); - } - - @Override - public void onResume() { - super.onResume(); - if (makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE) != null) { - timerUpdater.start(); - } - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View layout = inflater.inflate(R.layout.dialog_sleep_timer, container, false); - ButterKnife.bind(this, layout); - return layout; - } - - private void setProgressBarColor(int dark) { - LayerDrawable ld = (LayerDrawable) seekArc.getProgressDrawable(); - ClipDrawable clipDrawable = (ClipDrawable) ld.findDrawableByLayerId(android.R.id.progress); - clipDrawable.setColorFilter(dark, PorterDuff.Mode.SRC_IN); - } - - @SuppressWarnings("ConstantConditions") - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - MaterialUtil.setTint(setButton, true); - MaterialUtil.setTint(cancelButton, false); - - title.setTextColor(ThemeStore.textColorPrimary(getContext())); - timerDisplay.setTextColor(ThemeStore.textColorSecondary(getContext())); - - timerUpdater = new TimerUpdater(); - - seekArcProgress = PreferenceUtil.getInstance().getLastSleepTimerValue(); - updateTimeDisplayTime(); - seekArc.setProgress(seekArcProgress); - setProgressBarColor(ThemeStore.accentColor(getContext())); - - seekArc.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int i, boolean b) { - if (i < 1) { - seekArc.setProgress(1); - return; - } - seekArcProgress = i; - updateTimeDisplayTime(); - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - PreferenceUtil.getInstance().setLastSleepTimerValue(seekArcProgress); - } - }); - } - - @OnClick({R.id.action_cancel, R.id.action_set}) - void set(View view) { - switch (view.getId()) { - case R.id.action_cancel: - if (getActivity() == null) { - return; - } - final PendingIntent previous = makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE); - if (previous != null) { - AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE); - if (am != null) { - am.cancel(previous); - } - previous.cancel(); - Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.sleep_timer_canceled), Toast.LENGTH_SHORT).show(); - } - break; - case R.id.action_set: - if (getActivity() == null) { - return; - } - final int minutes = seekArcProgress; - PendingIntent pi = makeTimerPendingIntent(PendingIntent.FLAG_CANCEL_CURRENT); - final long nextSleepTimerElapsedTime = SystemClock.elapsedRealtime() + minutes * 60 * 1000; - PreferenceUtil.getInstance().setNextSleepTimerElapsedRealtime(nextSleepTimerElapsedTime); - AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE); - if (am != null) { - am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextSleepTimerElapsedTime, pi); - } - Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.sleep_timer_set, minutes), Toast.LENGTH_SHORT).show(); - break; - } - dismiss(); - } - - private void updateTimeDisplayTime() { - timerDisplay.setText(String.format(Locale.getDefault(), "%d min", seekArcProgress)); - } - - private PendingIntent makeTimerPendingIntent(int flag) { - return PendingIntent.getService(getActivity(), 0, makeTimerIntent(), flag); - } - - private Intent makeTimerIntent() { - return new Intent(getActivity(), MusicService.class) - .setAction( ACTION_QUIT); - } - - private class TimerUpdater extends CountDownTimer { - TimerUpdater() { - //noinspection ConstantConditions - super(PreferenceUtil.getInstance().getNextSleepTimerElapsedRealTime() - SystemClock.elapsedRealtime(), 1000); - } - - @Override - public void onTick(long millisUntilFinished) { - cancelButton.setText(String.format("%s (%s)", getString(R.string.cancel_current_timer), MusicUtil.getReadableDurationString(millisUntilFinished))); - //materialDialog.setActionButton(DialogAction.NEUTRAL, materialDialog.getContext().getString(R.string.cancel_current_timer) + " (" + MusicUtil.getReadableDurationString(millisUntilFinished) + ")"); - } - - @Override - public void onFinish() { - cancelButton.setText(null); - cancelButton.setVisibility(View.GONE); - //materialDialog.setActionButton(DialogAction.NEUTRAL, null); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.kt new file mode 100755 index 00000000..41bf91ff --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/SleepTimerDialog.kt @@ -0,0 +1,138 @@ +package code.name.monkey.retromusic.dialogs + +import android.app.AlarmManager +import android.app.PendingIntent +import android.content.Context +import android.content.DialogInterface +import android.content.Intent +import android.graphics.PorterDuff +import android.graphics.drawable.ClipDrawable +import android.graphics.drawable.LayerDrawable +import android.os.Bundle +import android.os.CountDownTimer +import android.os.SystemClock +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.SeekBar +import android.widget.Toast +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.MaterialUtil +import code.name.monkey.retromusic.Constants.ACTION_QUIT +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.service.MusicService +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment +import kotlinx.android.synthetic.main.dialog_sleep_timer.* +import java.util.* + +class SleepTimerDialog : RoundedBottomSheetDialogFragment() { + + private var seekArcProgress: Int = 0 + private lateinit var timerUpdater: TimerUpdater + + override fun onDismiss(dialog: DialogInterface?) { + super.onDismiss(dialog) + timerUpdater.cancel() + } + + override fun onResume() { + super.onResume() + if (makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE) != null) { + timerUpdater.start() + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + + return inflater.inflate(R.layout.dialog_sleep_timer, container, false) + } + + private fun setProgressBarColor(dark: Int) { + val ld = seekBar.progressDrawable as LayerDrawable + val clipDrawable = ld.findDrawableByLayerId(android.R.id.progress) as ClipDrawable + clipDrawable.setColorFilter(dark, PorterDuff.Mode.SRC_IN) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + MaterialUtil.setTint(actionSet, true) + MaterialUtil.setTint(actionCancel, false) + + title.setTextColor(ThemeStore.textColorPrimary(context!!)) + timerDisplay!!.setTextColor(ThemeStore.textColorSecondary(context!!)) + + timerUpdater = TimerUpdater() + + seekArcProgress = PreferenceUtil.getInstance().lastSleepTimerValue + updateTimeDisplayTime() + seekBar.progress = seekArcProgress + setProgressBarColor(ThemeStore.accentColor(context!!)) + seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { + if (i < 1) { + seekBar.progress = 1 + return + } + seekArcProgress = i + updateTimeDisplayTime() + } + + override fun onStartTrackingTouch(seekBar: SeekBar) { + + } + + override fun onStopTrackingTouch(seekBar: SeekBar) { + PreferenceUtil.getInstance().lastSleepTimerValue = seekArcProgress + } + }) + + actionCancel.setOnClickListener { + + val previous = makeTimerPendingIntent(PendingIntent.FLAG_NO_CREATE) + if (previous != null) { + val am = activity!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager + am.cancel(previous) + previous.cancel() + Toast.makeText(activity, activity!!.resources.getString(R.string.sleep_timer_canceled), Toast.LENGTH_SHORT).show() + } + dismiss() + } + actionSet.setOnClickListener { + val minutes = seekArcProgress + val pi = makeTimerPendingIntent(PendingIntent.FLAG_CANCEL_CURRENT) + val nextSleepTimerElapsedTime = SystemClock.elapsedRealtime() + minutes * 60 * 1000 + PreferenceUtil.getInstance().setNextSleepTimerElapsedRealtime(nextSleepTimerElapsedTime) + val am = activity!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager + am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextSleepTimerElapsedTime, pi) + Toast.makeText(activity, activity!!.resources.getString(R.string.sleep_timer_set, minutes), Toast.LENGTH_SHORT).show() + dismiss() + } + } + + private fun updateTimeDisplayTime() { + timerDisplay!!.text = String.format(Locale.getDefault(), "%d min", seekArcProgress) + } + + private fun makeTimerPendingIntent(flag: Int): PendingIntent? { + return PendingIntent.getService(activity, 0, makeTimerIntent(), flag) + } + + private fun makeTimerIntent(): Intent { + return Intent(activity, MusicService::class.java) + .setAction(ACTION_QUIT) + } + + private inner class TimerUpdater internal constructor() : CountDownTimer(PreferenceUtil.getInstance().nextSleepTimerElapsedRealTime - SystemClock.elapsedRealtime(), 1000) { + + override fun onTick(millisUntilFinished: Long) { + actionCancel.text = String.format("%s (%s)", getString(R.string.cancel_current_timer), MusicUtil.getReadableDurationString(millisUntilFinished)) + } + + override fun onFinish() { + actionCancel.text = null + actionCancel.visibility = View.GONE + } + } +} \ No newline at end of file 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 deleted file mode 100644 index e67a4a68..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.java +++ /dev/null @@ -1,124 +0,0 @@ -package code.name.monkey.retromusic.dialogs; - -import android.content.Context; -import android.os.Bundle; -import android.text.Html; -import android.text.Spanned; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.jaudiotagger.audio.AudioFile; -import org.jaudiotagger.audio.AudioFileIO; -import org.jaudiotagger.audio.AudioHeader; -import org.jaudiotagger.audio.exceptions.CannotReadException; -import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException; -import org.jaudiotagger.audio.exceptions.ReadOnlyFileException; -import org.jaudiotagger.tag.TagException; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindViews; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment; - -/** - * @author Karim Abou Zeid (kabouzeid), Aidan Follestad (afollestad) - */ -public class SongDetailDialog extends RoundedBottomSheetDialogFragment { - - public static final String TAG = SongDetailDialog.class.getSimpleName(); - @BindViews({R.id.title, - R.id.file_name, - R.id.file_path, - R.id.file_size, - R.id.file_format, - R.id.track_length, - R.id.bitrate, - R.id.sampling_rate}) - List textViews; - - @NonNull - public static SongDetailDialog create(Song song) { - SongDetailDialog dialog = new SongDetailDialog(); - Bundle args = new Bundle(); - args.putParcelable("song", song); - dialog.setArguments(args); - return dialog; - } - - private static Spanned makeTextWithTitle(@NonNull Context context, int titleResId, String text) { - return Html.fromHtml("" + context.getResources().getString(titleResId) + ": " + "" + text); - } - - private static String getFileSizeString(long sizeInBytes) { - long fileSizeInKB = sizeInBytes / 1024; - long fileSizeInMB = fileSizeInKB / 1024; - return fileSizeInMB + " MB"; - } - - private void setTextColor(List textColor) { - for (TextView textView : textColor) { - //noinspection ConstantConditions - textView.setTextColor(ThemeStore.textColorPrimary(getContext())); - } - } - - @SuppressWarnings("ConstantConditions") - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View dialogView = inflater.inflate(R.layout.dialog_file_details, container, false); - ButterKnife.bind(this, dialogView); - Context context = getContext(); - - setTextColor(textViews); - - textViews.get(1).setText(makeTextWithTitle(context, R.string.label_file_name, "-")); - textViews.get(2).setText(makeTextWithTitle(context, R.string.label_file_path, "-")); - textViews.get(3).setText(makeTextWithTitle(context, R.string.label_file_size, "-")); - textViews.get(4).setText(makeTextWithTitle(context, R.string.label_file_format, "-")); - textViews.get(5).setText(makeTextWithTitle(context, R.string.label_track_length, "-")); - textViews.get(6).setText(makeTextWithTitle(context, R.string.label_bit_rate, "-")); - textViews.get(7).setText(makeTextWithTitle(context, R.string.label_sampling_rate, "-")); - - final Song song = getArguments().getParcelable("song"); - if (song != null) { - 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())); - textViews.get(3).setText(makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length()))); - try { - AudioFile audioFile = AudioFileIO.read(songFile); - AudioHeader audioHeader = audioFile.getAudioHeader(); - - textViews.get(4).setText(makeTextWithTitle(context, R.string.label_file_format, audioHeader.getFormat())); - textViews.get(5).setText(makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(audioHeader.getTrackLength() * 1000))); - textViews.get(6).setText(makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.getBitRate() + " kb/s")); - textViews.get(7).setText(makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.getSampleRate() + " Hz")); - } 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.getDuration()))); - } - } else { - // fallback - 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()))); - } - } - - return dialogView; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.kt new file mode 100644 index 00000000..412fef9e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongDetailDialog.kt @@ -0,0 +1,113 @@ +package code.name.monkey.retromusic.dialogs + +import android.content.Context +import android.os.Bundle +import android.text.Html +import android.text.Spanned +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment +import kotlinx.android.synthetic.main.dialog_file_details.* +import org.jaudiotagger.audio.AudioFileIO +import org.jaudiotagger.audio.exceptions.CannotReadException +import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException +import org.jaudiotagger.audio.exceptions.ReadOnlyFileException +import org.jaudiotagger.tag.TagException +import java.io.File +import java.io.IOException + +class SongDetailDialog : RoundedBottomSheetDialogFragment() { + + private fun setTextColor(textColor: List) { + for (textView in textColor) { + + textView.setTextColor(ThemeStore.textColorPrimary(context!!)) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val dialogView = inflater.inflate(R.layout.dialog_file_details, container, false) + val context = context + + fileName.text = makeTextWithTitle(context!!, R.string.label_file_name, "-") + filePath.text = makeTextWithTitle(context, R.string.label_file_path, "-") + fileSize.text = makeTextWithTitle(context, R.string.label_file_size, "-") + fileFormat.text = makeTextWithTitle(context, R.string.label_file_format, "-") + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, "-") + bitrate.text = makeTextWithTitle(context, R.string.label_bit_rate, "-") + samplingRate.text = makeTextWithTitle(context, R.string.label_sampling_rate, "-") + + val song = arguments!!.getParcelable("song") + if (song != null) { + val songFile = File(song.data) + if (songFile.exists()) { + fileName.text = makeTextWithTitle(context, R.string.label_file_name, songFile.name) + filePath.text = makeTextWithTitle(context, R.string.label_file_path, songFile.absolutePath) + fileSize.text = makeTextWithTitle(context, R.string.label_file_size, getFileSizeString(songFile.length())) + try { + val audioFile = AudioFileIO.read(songFile) + val audioHeader = audioFile.audioHeader + + fileFormat.text = makeTextWithTitle(context, R.string.label_file_format, audioHeader.format) + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString((audioHeader.trackLength * 1000).toLong())) + bitrate.text = makeTextWithTitle(context, R.string.label_bit_rate, audioHeader.bitRate + " kb/s") + samplingRate.text = makeTextWithTitle(context, R.string.label_sampling_rate, audioHeader.sampleRate + " Hz") + } catch (e: CannotReadException) { + Log.e(TAG, "error while reading the song file", e) + // fallback + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)) + } catch (e: IOException) { + Log.e(TAG, "error while reading the song file", e) + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)) + } catch (e: TagException) { + Log.e(TAG, "error while reading the song file", e) + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)) + } catch (e: ReadOnlyFileException) { + Log.e(TAG, "error while reading the song file", e) + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)) + } catch (e: InvalidAudioFrameException) { + Log.e(TAG, "error while reading the song file", e) + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)) + } + + } else { + // fallback + fileName.text = makeTextWithTitle(context, R.string.label_file_name, song.title) + trackLength.text = makeTextWithTitle(context, R.string.label_track_length, MusicUtil.getReadableDurationString(song.duration)) + } + } + + return dialogView + } + + companion object { + + val TAG = SongDetailDialog::class.java.simpleName + + + fun create(song: Song): SongDetailDialog { + val dialog = SongDetailDialog() + val args = Bundle() + args.putParcelable("song", song) + dialog.arguments = args + return dialog + } + + private fun makeTextWithTitle(context: Context, titleResId: Int, text: String?): Spanned { + return Html.fromHtml("" + context.resources.getString(titleResId) + ": " + "" + text) + } + + private fun getFileSizeString(sizeInBytes: Long): String { + val fileSizeInKB = sizeInBytes / 1024 + val fileSizeInMB = fileSizeInKB / 1024 + return fileSizeInMB.toString() + " MB" + } + } +} 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 deleted file mode 100644 index 7b804a7e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.java +++ /dev/null @@ -1,77 +0,0 @@ -package code.name.monkey.retromusic.dialogs; - -import android.annotation.SuppressLint; -import android.content.Intent; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -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.Song; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment; - - -public class SongShareDialog extends RoundedBottomSheetDialogFragment { - @BindView(R.id.option_1) - TextView audioFile; - @BindView(R.id.option_2) - TextView audioText; - @BindView(R.id.title) - TextView title; - - @NonNull - public static SongShareDialog create(final Song song) { - final SongShareDialog dialog = new SongShareDialog(); - final Bundle args = new Bundle(); - args.putParcelable("song", song); - dialog.setArguments(args); - return dialog; - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View layout = inflater.inflate(R.layout.dialog_file_share, container, false); - ButterKnife.bind(this, layout); - return layout; - } - - @SuppressLint("StringFormatInvalid") - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - final Song song = getArguments().getParcelable("song"); - - 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())); - } - - @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.getTitle(), song.getArtistName()); - switch (view.getId()) { - case R.id.option_1: - startActivity(Intent.createChooser( - MusicUtil.createShareSongFileIntent(song, getContext()), null)); - break; - case R.id.option_2: - getActivity().startActivity(Intent.createChooser(new Intent().setAction(Intent.ACTION_SEND) - .putExtra(Intent.EXTRA_TEXT, currentlyListening) - .setType("text/plain"), null)); - break; - } - dismiss(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.kt b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.kt new file mode 100644 index 00000000..6d386ccd --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/dialogs/SongShareDialog.kt @@ -0,0 +1,56 @@ +package code.name.monkey.retromusic.dialogs + +import android.annotation.SuppressLint +import android.content.Intent +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.retromusic.R +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.views.RoundedBottomSheetDialogFragment +import kotlinx.android.synthetic.main.dialog_file_share.* + + +class SongShareDialog : RoundedBottomSheetDialogFragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.dialog_file_share, container, false) + } + + @SuppressLint("StringFormatInvalid") + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + val song = arguments!!.getParcelable("song")!! + + audioFile.text = getString(R.string.currently_listening_to_x_by_x, song.title, song.artistName) + audioFile.setTextColor(ThemeStore.textColorSecondary(context!!)) + audioText.setTextColor(ThemeStore.textColorSecondary(context!!)) + title.setTextColor(ThemeStore.textColorPrimary(context!!)) + + audioFile.setOnClickListener { + MusicUtil.createShareSongFileIntent(song, context) + dismiss() + } + audioText.setOnClickListener { + val currentlyListening = getString(R.string.currently_listening_to_x_by_x, song.title, song.artistName) + activity!!.startActivity(Intent.createChooser(Intent().setAction(Intent.ACTION_SEND) + .putExtra(Intent.EXTRA_TEXT, currentlyListening) + .setType("text/plain"), null)) + dismiss() + } + + } + + companion object { + + fun create(song: Song): SongShareDialog { + val dialog = SongShareDialog() + val args = Bundle() + args.putParcelable("song", song) + dialog.arguments = args + return dialog + } + } +} 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 deleted file mode 100644 index 2a779a2a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.java +++ /dev/null @@ -1,141 +0,0 @@ -package code.name.monkey.retromusic.glide; - -import android.content.Context; -import android.graphics.Bitmap; -import androidx.annotation.NonNull; - -import com.bumptech.glide.BitmapRequestBuilder; -import com.bumptech.glide.DrawableRequestBuilder; -import com.bumptech.glide.DrawableTypeRequest; -import com.bumptech.glide.Priority; -import com.bumptech.glide.RequestManager; -import com.bumptech.glide.load.Key; -import com.bumptech.glide.load.engine.DiskCacheStrategy; -import com.bumptech.glide.load.resource.drawable.GlideDrawable; -import com.bumptech.glide.request.target.Target; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.App; -import code.name.monkey.retromusic.glide.artistimage.ArtistImage; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteTranscoder; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.util.ArtistSignatureUtil; -import code.name.monkey.retromusic.util.CustomArtistImageUtil; - -public class ArtistGlideRequest { - - private static final int DEFAULT_ANIMATION = android.R.anim.fade_in; - private static final DiskCacheStrategy DEFAULT_DISK_CACHE_STRATEGY = DiskCacheStrategy.ALL; - private static final int DEFAULT_ERROR_IMAGE = R.drawable.default_artist_art; - - private static DrawableTypeRequest createBaseRequest(RequestManager requestManager, Artist artist, - boolean noCustomImage, boolean forceDownload) { - boolean hasCustomImage = CustomArtistImageUtil.getInstance(App.Companion.getInstance()) - .hasCustomArtistImage(artist); - if (noCustomImage || !hasCustomImage) { - return requestManager.load(new ArtistImage(artist.getName(), forceDownload)); - } else { - return requestManager.load(CustomArtistImageUtil.getFile(artist)); - } - } - - private static Key createSignature(Artist artist) { - return ArtistSignatureUtil.getInstance(App.Companion.getInstance()) - .getArtistSignature(artist.getName()); - } - - public static class Builder { - - final RequestManager requestManager; - final Artist artist; - boolean noCustomImage; - boolean forceDownload; - - private Builder(@NonNull RequestManager requestManager, Artist artist) { - this.requestManager = requestManager; - this.artist = artist; - } - - public static Builder from(@NonNull RequestManager requestManager, Artist artist) { - return new Builder(requestManager, artist); - } - - public PaletteBuilder generatePalette(Context context) { - return new PaletteBuilder(this, context); - } - - public BitmapBuilder asBitmap() { - return new BitmapBuilder(this); - } - - public Builder noCustomImage(boolean noCustomImage) { - this.noCustomImage = noCustomImage; - return this; - } - - public Builder forceDownload(boolean forceDownload) { - this.forceDownload = forceDownload; - return this; - } - - public DrawableRequestBuilder build() { - //noinspection unchecked - return createBaseRequest(requestManager, artist, noCustomImage, forceDownload) - .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) - .error(DEFAULT_ERROR_IMAGE) - .animate(DEFAULT_ANIMATION) - .priority(Priority.LOW) - .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) - .signature(createSignature(artist)); - } - } - - public static class BitmapBuilder { - - private final Builder builder; - - BitmapBuilder(Builder builder) { - this.builder = builder; - } - - public BitmapRequestBuilder build() { - //noinspection unchecked - return createBaseRequest(builder.requestManager, builder.artist, builder.noCustomImage, - builder.forceDownload) - .asBitmap() - .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) - .error(DEFAULT_ERROR_IMAGE) - .animate(DEFAULT_ANIMATION) - .priority(Priority.LOW) - .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) - .signature(createSignature(builder.artist)); - } - } - - public static class PaletteBuilder { - - final Context context; - private final Builder builder; - - PaletteBuilder(Builder builder, Context context) { - this.builder = builder; - this.context = context; - } - - public BitmapRequestBuilder build() { - //noinspection unchecked - return createBaseRequest(builder.requestManager, builder.artist, builder.noCustomImage, - builder.forceDownload) - .asBitmap() - .transcode(new BitmapPaletteTranscoder(context), BitmapPaletteWrapper.class) - - .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) - .error(DEFAULT_ERROR_IMAGE) - .animate(DEFAULT_ANIMATION) - .priority(Priority.LOW) - .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) - .signature(createSignature(builder.artist)); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.kt b/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.kt new file mode 100644 index 00000000..619a21d4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/ArtistGlideRequest.kt @@ -0,0 +1,112 @@ +package code.name.monkey.retromusic.glide + +import android.content.Context +import android.graphics.Bitmap +import code.name.monkey.retromusic.App +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.artistimage.ArtistImage +import code.name.monkey.retromusic.glide.palette.BitmapPaletteTranscoder +import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.util.ArtistSignatureUtil +import code.name.monkey.retromusic.util.CustomArtistImageUtil +import com.bumptech.glide.* +import com.bumptech.glide.load.Key +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.request.target.Target + +object ArtistGlideRequest { + + private const val DEFAULT_ANIMATION = android.R.anim.fade_in + private val DEFAULT_DISK_CACHE_STRATEGY = DiskCacheStrategy.ALL + private const val DEFAULT_ERROR_IMAGE = R.drawable.default_artist_art + + private fun createBaseRequest(requestManager: RequestManager, artist: Artist, noCustomImage: Boolean, forceDownload: Boolean): DrawableTypeRequest<*> { + val hasCustomImage = CustomArtistImageUtil.getInstance(App.instance) + .hasCustomArtistImage(artist) + return if (noCustomImage || !hasCustomImage) { + requestManager.load(ArtistImage(artist.name, forceDownload)) + } else { + requestManager.load(CustomArtistImageUtil.getFile(artist)) + } + } + + private fun createSignature(artist: Artist): Key { + return ArtistSignatureUtil.getInstance(App.instance) + .getArtistSignature(artist.name) + } + + class Builder private constructor(internal val requestManager: RequestManager, internal val artist: Artist) { + internal var noCustomImage: Boolean = false + internal var forceDownload: Boolean = false + + fun generatePalette(context: Context): PaletteBuilder { + return PaletteBuilder(this, context) + } + + fun asBitmap(): BitmapBuilder { + return BitmapBuilder(this) + } + + fun noCustomImage(noCustomImage: Boolean): Builder { + this.noCustomImage = noCustomImage + return this + } + + fun forceDownload(forceDownload: Boolean): Builder { + this.forceDownload = forceDownload + return this + } + + fun build(): DrawableRequestBuilder { + return createBaseRequest(requestManager, artist, noCustomImage, forceDownload) + .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) + .error(DEFAULT_ERROR_IMAGE) + .animate(DEFAULT_ANIMATION) + .priority(Priority.LOW) + .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) + .signature(createSignature(artist)) + } + + companion object { + + fun from(requestManager: RequestManager, artist: Artist): Builder { + return Builder(requestManager, artist) + } + } + } + + class BitmapBuilder internal constructor(private val builder: Builder) { + + fun build(): BitmapRequestBuilder<*, Bitmap> { + + return createBaseRequest(builder.requestManager, builder.artist, builder.noCustomImage, + builder.forceDownload) + .asBitmap() + .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) + .error(DEFAULT_ERROR_IMAGE) + .animate(DEFAULT_ANIMATION) + .priority(Priority.LOW) + .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) + .signature(createSignature(builder.artist)) + } + } + + class PaletteBuilder internal constructor(private val builder: Builder, internal val context: Context) { + + fun build(): BitmapRequestBuilder<*, BitmapPaletteWrapper> { + + return createBaseRequest(builder.requestManager, builder.artist, builder.noCustomImage, + builder.forceDownload) + .asBitmap() + .transcode(BitmapPaletteTranscoder(context), BitmapPaletteWrapper::class.java) + + .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) + .error(DEFAULT_ERROR_IMAGE) + .animate(DEFAULT_ANIMATION) + .priority(Priority.LOW) + .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) + .signature(createSignature(builder.artist)) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.java b/app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.java deleted file mode 100644 index ef2bb7e6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.java +++ /dev/null @@ -1,147 +0,0 @@ -package code.name.monkey.retromusic.glide; - -import android.content.Context; -import android.graphics.Bitmap; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.os.Build; -import android.renderscript.Allocation; -import android.renderscript.Element; -import android.renderscript.RSRuntimeException; -import android.renderscript.RenderScript; -import android.renderscript.ScriptIntrinsicBlur; -import androidx.annotation.FloatRange; -import androidx.annotation.NonNull; - -import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; -import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; -import code.name.monkey.retromusic.helper.StackBlur; - -import code.name.monkey.retromusic.BuildConfig; -import code.name.monkey.retromusic.util.ImageUtil; - - -public class BlurTransformation extends BitmapTransformation { - static final float DEFAULT_BLUR_RADIUS = 5f; - - private Context context; - private float blurRadius; - private int sampling; - - private BlurTransformation(Builder builder) { - super(builder.context); - init(builder); - } - - private BlurTransformation(Builder builder, BitmapPool bitmapPool) { - super(bitmapPool); - init(builder); - } - - private void init(Builder builder) { - this.context = builder.context; - this.blurRadius = builder.blurRadius; - this.sampling = builder.sampling; - } - - @Override - protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { - int sampling; - if (this.sampling == 0) { - sampling = ImageUtil.calculateInSampleSize(toTransform.getWidth(), toTransform.getHeight(), 100); - } else { - sampling = this.sampling; - } - - int width = toTransform.getWidth(); - int height = toTransform.getHeight(); - int scaledWidth = width / sampling; - int scaledHeight = height / sampling; - - Bitmap out = pool.get(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888); - if (out == null) { - out = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888); - } - - Canvas canvas = new Canvas(out); - canvas.scale(1 / (float) sampling, 1 / (float) sampling); - Paint paint = new Paint(); - paint.setFlags(Paint.FILTER_BITMAP_FLAG); - canvas.drawBitmap(toTransform, 0, 0, paint); - - if (Build.VERSION.SDK_INT >= 17) { - try { - final RenderScript rs = RenderScript.create(context.getApplicationContext()); - final Allocation input = Allocation.createFromBitmap(rs, out, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); - final Allocation output = Allocation.createTyped(rs, input.getType()); - final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); - - script.setRadius(blurRadius); - script.setInput(input); - script.forEach(output); - - output.copyTo(out); - - rs.destroy(); - - return out; - - } catch (RSRuntimeException e) { - // on some devices RenderScript.create() throws: android.support.v8.renderscript.RSRuntimeException: Error loading libRSSupport library - if (BuildConfig.DEBUG) e.printStackTrace(); - } - } - - return StackBlur.blur(out, blurRadius); - } - - @Override - public String getId() { - return "BlurTransformation(radius=" + blurRadius + ", sampling=" + sampling + ")"; - } - - public static class Builder { - private Context context; - private BitmapPool bitmapPool; - private float blurRadius = DEFAULT_BLUR_RADIUS; - private int sampling; - - public Builder(@NonNull Context context) { - this.context = context; - } - - /** - * @param blurRadius The radius to use. Must be between 0 and 25. Default is 5. - * @return the same Builder - */ - public Builder blurRadius(@FloatRange(from = 0.0f, to = 25.0f) float blurRadius) { - this.blurRadius = blurRadius; - return this; - } - - /** - * @param sampling The inSampleSize to use. Must be a power of 2, or 1 for no down sampling or 0 for auto detect sampling. Default is 0. - * @return the same Builder - */ - public Builder sampling(int sampling) { - this.sampling = sampling; - return this; - } - - /** - * @param bitmapPool The BitmapPool to use. - * @return the same Builder - */ - public Builder bitmapPool(BitmapPool bitmapPool) { - this.bitmapPool = bitmapPool; - return this; - } - - public BlurTransformation build() { - if (bitmapPool != null) { - return new BlurTransformation(this, bitmapPool); - } - return new BlurTransformation(this); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.kt b/app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.kt new file mode 100644 index 00000000..860e0481 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/BlurTransformation.kt @@ -0,0 +1,142 @@ +package code.name.monkey.retromusic.glide + +import android.annotation.SuppressLint +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Paint +import android.os.Build +import android.renderscript.Allocation +import android.renderscript.Element +import android.renderscript.RSRuntimeException +import android.renderscript.RenderScript +import android.renderscript.ScriptIntrinsicBlur +import androidx.annotation.FloatRange + +import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool +import com.bumptech.glide.load.resource.bitmap.BitmapTransformation +import code.name.monkey.retromusic.helper.StackBlur + +import code.name.monkey.retromusic.BuildConfig +import code.name.monkey.retromusic.util.ImageUtil + + +class BlurTransformation : BitmapTransformation { + + private var context: Context? = null + private var blurRadius: Float = 0.toFloat() + private var sampling: Int = 0 + + private constructor(builder: Builder) : super(builder.context) { + init(builder) + } + + private constructor(builder: Builder, bitmapPool: BitmapPool) : super(bitmapPool) { + init(builder) + } + + private fun init(builder: Builder) { + this.context = builder.context + this.blurRadius = builder.blurRadius + this.sampling = builder.sampling + } + + + override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap? { + val sampling: Int + if (this.sampling == 0) { + sampling = ImageUtil.calculateInSampleSize(toTransform.width, toTransform.height, 100) + } else { + sampling = this.sampling + } + + val width = toTransform.width + val height = toTransform.height + val scaledWidth = width / sampling + val scaledHeight = height / sampling + + var out: Bitmap? = pool.get(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888) + if (out == null) { + out = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888) + } + + val canvas = Canvas(out!!) + canvas.scale(1 / sampling.toFloat(), 1 / sampling.toFloat()) + val paint = Paint() + paint.flags = Paint.FILTER_BITMAP_FLAG + canvas.drawBitmap(toTransform, 0f, 0f, paint) + + if (Build.VERSION.SDK_INT >= 17) { + try { + val rs = RenderScript.create(context!!.applicationContext) + val input = Allocation.createFromBitmap(rs, out, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT) + val output = Allocation.createTyped(rs, input.type) + val script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)) + + script.setRadius(blurRadius) + script.setInput(input) + script.forEach(output) + + output.copyTo(out) + + rs.destroy() + + return out + + } catch (e: RSRuntimeException) { + // on some devices RenderScript.create() throws: android.support.v8.renderscript.RSRuntimeException: Error loading libRSSupport library + if (BuildConfig.DEBUG) e.printStackTrace() + } + + } + + return StackBlur.blur(out, blurRadius) + } + + override fun getId(): String { + return "BlurTransformation(radius=$blurRadius, sampling=$sampling)" + } + + class Builder(internal val context: Context) { + private var bitmapPool: BitmapPool? = null + internal var blurRadius = DEFAULT_BLUR_RADIUS + internal var sampling: Int = 0 + + /** + * @param blurRadius The radius to use. Must be between 0 and 25. Default is 5. + * @return the same Builder + */ + fun blurRadius(@FloatRange(from = 0.0, to = 25.0) blurRadius: Float): Builder { + this.blurRadius = blurRadius + return this + } + + /** + * @param sampling The inSampleSize to use. Must be a power of 2, or 1 for no down sampling or 0 for auto detect sampling. Default is 0. + * @return the same Builder + */ + fun sampling(sampling: Int): Builder { + this.sampling = sampling + return this + } + + /** + * @param bitmapPool The BitmapPool to use. + * @return the same Builder + */ + fun bitmapPool(bitmapPool: BitmapPool): Builder { + this.bitmapPool = bitmapPool + return this + } + + fun build(): BlurTransformation { + return if (bitmapPool != null) { + BlurTransformation(this, bitmapPool!!) + } else BlurTransformation(this) + } + } + + companion object { + internal const val DEFAULT_BLUR_RADIUS = 5f + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.java b/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.java deleted file mode 100644 index ae2074b1..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.java +++ /dev/null @@ -1,27 +0,0 @@ -package code.name.monkey.retromusic.glide; - -import android.content.Context; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.GlideBuilder; -import com.bumptech.glide.module.GlideModule; -import code.name.monkey.retromusic.glide.artistimage.ArtistImage; -import code.name.monkey.retromusic.glide.artistimage.ArtistImageLoader; -import code.name.monkey.retromusic.glide.audiocover.AudioFileCover; -import code.name.monkey.retromusic.glide.audiocover.AudioFileCoverLoader; - -import java.io.InputStream; - - -public class RetroMusicGlideModule implements GlideModule { - @Override - public void applyOptions(Context context, GlideBuilder builder) { - - } - - @Override - public void registerComponents(Context context, Glide glide) { - glide.register(AudioFileCover.class, InputStream.class, new AudioFileCoverLoader.Factory()); - glide.register(ArtistImage.class, InputStream.class, new ArtistImageLoader.Factory(context)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.kt b/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.kt new file mode 100644 index 00000000..11487480 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/RetroMusicGlideModule.kt @@ -0,0 +1,25 @@ +package code.name.monkey.retromusic.glide + +import android.content.Context + +import com.bumptech.glide.Glide +import com.bumptech.glide.GlideBuilder +import com.bumptech.glide.module.GlideModule +import code.name.monkey.retromusic.glide.artistimage.ArtistImage +import code.name.monkey.retromusic.glide.artistimage.ArtistImageLoader +import code.name.monkey.retromusic.glide.audiocover.AudioFileCover +import code.name.monkey.retromusic.glide.audiocover.AudioFileCoverLoader + +import java.io.InputStream + + +class RetroMusicGlideModule : GlideModule { + override fun applyOptions(context: Context, builder: GlideBuilder) { + + } + + override fun registerComponents(context: Context, glide: Glide) { + glide.register(AudioFileCover::class.java, InputStream::class.java, AudioFileCoverLoader.Factory()) + glide.register(ArtistImage::class.java, InputStream::class.java, ArtistImageLoader.Factory(context)) + } +} 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 deleted file mode 100644 index 39e28d7b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.java +++ /dev/null @@ -1,124 +0,0 @@ -package code.name.monkey.retromusic.glide; - -import android.content.Context; -import android.graphics.Bitmap; -import androidx.annotation.NonNull; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.glide.audiocover.AudioFileCover; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteTranscoder; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import com.bumptech.glide.BitmapRequestBuilder; -import com.bumptech.glide.DrawableRequestBuilder; -import com.bumptech.glide.DrawableTypeRequest; -import com.bumptech.glide.RequestManager; -import com.bumptech.glide.load.Key; -import com.bumptech.glide.load.engine.DiskCacheStrategy; -import com.bumptech.glide.load.resource.drawable.GlideDrawable; -import com.bumptech.glide.signature.MediaStoreSignature; - - -public class SongGlideRequest { - - static final DiskCacheStrategy DEFAULT_DISK_CACHE_STRATEGY = DiskCacheStrategy.NONE; - static final int DEFAULT_ANIMATION = android.R.anim.fade_in; - static final int DEFAULT_ERROR_IMAGE = R.drawable.default_album_art; - - static DrawableTypeRequest createBaseRequest(RequestManager requestManager, Song song, - boolean ignoreMediaStore) { - if (ignoreMediaStore) { - return requestManager.load(new AudioFileCover(song.getData())); - } else { - return requestManager.loadFromMediaStore(MusicUtil.getMediaStoreAlbumCoverUri(song.getAlbumId())); - } - } - - static Key createSignature(Song song) { - return new MediaStoreSignature("", song.getDateModified(), 0); - } - - public static class Builder { - - final RequestManager requestManager; - final Song song; - boolean ignoreMediaStore; - - private Builder(@NonNull RequestManager requestManager, Song song) { - this.requestManager = requestManager; - this.song = song; - } - - public static Builder from(@NonNull RequestManager requestManager, Song song) { - return new Builder(requestManager, song); - } - - public PaletteBuilder generatePalette(Context context) { - return new PaletteBuilder(this, context); - } - - public BitmapBuilder asBitmap() { - return new BitmapBuilder(this); - } - - public Builder checkIgnoreMediaStore(Context context) { - return ignoreMediaStore(PreferenceUtil.getInstance().ignoreMediaStoreArtwork()); - } - - Builder ignoreMediaStore(boolean ignoreMediaStore) { - this.ignoreMediaStore = ignoreMediaStore; - return this; - } - - public DrawableRequestBuilder build() { - //noinspection unchecked - return createBaseRequest(requestManager, song, ignoreMediaStore) - .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) - .error(DEFAULT_ERROR_IMAGE) - .animate(DEFAULT_ANIMATION) - .signature(createSignature(song)); - } - } - - public static class BitmapBuilder { - - private final Builder builder; - - BitmapBuilder(Builder builder) { - this.builder = builder; - } - - public BitmapRequestBuilder build() { - //noinspection unchecked - return createBaseRequest(builder.requestManager, builder.song, builder.ignoreMediaStore) - .asBitmap() - .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) - .error(DEFAULT_ERROR_IMAGE) - .animate(DEFAULT_ANIMATION) - .signature(createSignature(builder.song)); - } - } - - public static class PaletteBuilder { - - final Context context; - private final Builder builder; - - PaletteBuilder(Builder builder, Context context) { - this.builder = builder; - this.context = context; - } - - public BitmapRequestBuilder build() { - //noinspection unchecked - return createBaseRequest(builder.requestManager, builder.song, builder.ignoreMediaStore) - .asBitmap() - .transcode(new BitmapPaletteTranscoder(context), BitmapPaletteWrapper.class) - .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) - .error(DEFAULT_ERROR_IMAGE) - .animate(DEFAULT_ANIMATION) - .signature(createSignature(builder.song)); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.kt b/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.kt new file mode 100644 index 00000000..92bd8f61 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/SongGlideRequest.kt @@ -0,0 +1,102 @@ +package code.name.monkey.retromusic.glide + +import android.content.Context +import android.graphics.Bitmap +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.glide.audiocover.AudioFileCover +import code.name.monkey.retromusic.glide.palette.BitmapPaletteTranscoder +import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import com.bumptech.glide.BitmapRequestBuilder +import com.bumptech.glide.DrawableRequestBuilder +import com.bumptech.glide.DrawableTypeRequest +import com.bumptech.glide.RequestManager +import com.bumptech.glide.load.Key +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.signature.MediaStoreSignature + + +object SongGlideRequest { + + internal val DEFAULT_DISK_CACHE_STRATEGY = DiskCacheStrategy.NONE + internal const val DEFAULT_ANIMATION = android.R.anim.fade_in + internal const val DEFAULT_ERROR_IMAGE = R.drawable.default_album_art + + internal fun createBaseRequest(requestManager: RequestManager, song: Song, + ignoreMediaStore: Boolean): DrawableTypeRequest<*> { + return if (ignoreMediaStore) { + requestManager.load(AudioFileCover(song.data!!)) + } else { + requestManager.loadFromMediaStore(MusicUtil.getMediaStoreAlbumCoverUri(song.albumId)) + } + } + + internal fun createSignature(song: Song): Key { + return MediaStoreSignature("", song.dateModified, 0) + } + + class Builder private constructor(internal val requestManager: RequestManager, internal val song: Song) { + internal var ignoreMediaStore: Boolean = false + + fun generatePalette(context: Context): PaletteBuilder { + return PaletteBuilder(this, context) + } + + fun asBitmap(): BitmapBuilder { + return BitmapBuilder(this) + } + + fun checkIgnoreMediaStore(context: Context): Builder { + return ignoreMediaStore(PreferenceUtil.getInstance().ignoreMediaStoreArtwork()) + } + + fun ignoreMediaStore(ignoreMediaStore: Boolean): Builder { + this.ignoreMediaStore = ignoreMediaStore + return this + } + + fun build(): DrawableRequestBuilder { + return createBaseRequest(requestManager, song, ignoreMediaStore) + .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) + .error(DEFAULT_ERROR_IMAGE) + .animate(DEFAULT_ANIMATION) + .signature(createSignature(song)) + } + + companion object { + + fun from(requestManager: RequestManager, song: Song): Builder { + return Builder(requestManager, song) + } + } + } + + class BitmapBuilder internal constructor(private val builder: Builder) { + + fun build(): BitmapRequestBuilder<*, Bitmap> { + + return createBaseRequest(builder.requestManager, builder.song, builder.ignoreMediaStore) + .asBitmap() + .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) + .error(DEFAULT_ERROR_IMAGE) + .animate(DEFAULT_ANIMATION) + .signature(createSignature(builder.song)) + } + } + + class PaletteBuilder internal constructor(private val builder: Builder, internal val context: Context) { + + fun build(): BitmapRequestBuilder<*, BitmapPaletteWrapper> { + + return createBaseRequest(builder.requestManager, builder.song, builder.ignoreMediaStore) + .asBitmap() + .transcode(BitmapPaletteTranscoder(context), BitmapPaletteWrapper::class.java) + .diskCacheStrategy(DEFAULT_DISK_CACHE_STRATEGY) + .error(DEFAULT_ERROR_IMAGE) + .animate(DEFAULT_ANIMATION) + .signature(createSignature(builder.song)) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.java b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.java deleted file mode 100644 index ad858466..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.java +++ /dev/null @@ -1,12 +0,0 @@ -package code.name.monkey.retromusic.glide.artistimage; - - -public class ArtistImage { - public final String artistName; - public final boolean skipOkHttpCache; - - public ArtistImage(String artistName, boolean skipOkHttpCache) { - this.artistName = artistName; - this.skipOkHttpCache = skipOkHttpCache; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.kt b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.kt new file mode 100644 index 00000000..6ce2ac9e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImage.kt @@ -0,0 +1,4 @@ +package code.name.monkey.retromusic.glide.artistimage + + +class ArtistImage(val artistName: String, val skipOkHttpCache: Boolean) diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.java b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.java deleted file mode 100644 index 5e65535d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.java +++ /dev/null @@ -1,83 +0,0 @@ -package code.name.monkey.retromusic.glide.artistimage; - -import android.content.Context; - -import com.bumptech.glide.Priority; -import com.bumptech.glide.load.data.DataFetcher; -import com.bumptech.glide.load.model.GlideUrl; -import com.bumptech.glide.load.model.ModelLoader; -import code.name.monkey.retromusic.rest.LastFMRestClient; -import code.name.monkey.retromusic.rest.model.LastFmArtist; - -import code.name.monkey.retromusic.util.LastFMUtil; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.RetroUtil; - -import java.io.IOException; -import java.io.InputStream; - -import retrofit2.Response; - - -public class ArtistImageFetcher implements DataFetcher { - public static final String TAG = ArtistImageFetcher.class.getSimpleName(); - private final LastFMRestClient lastFMRestClient; - private final ArtistImage model; - private final int width; - private final int height; - private Context context; - private ModelLoader urlLoader; - private volatile boolean isCancelled; - private DataFetcher urlFetcher; - - public ArtistImageFetcher(Context context, LastFMRestClient lastFMRestClient, ArtistImage model, ModelLoader urlLoader, int width, int height) { - this.context = context; - this.lastFMRestClient = lastFMRestClient; - this.model = model; - this.urlLoader = urlLoader; - this.width = width; - this.height = height; - } - - @Override - public String getId() { - // makes sure we never ever return null here - return String.valueOf(model.artistName); - } - - @Override - public InputStream loadData(Priority priority) throws Exception { - if (!MusicUtil.isArtistNameUnknown(model.artistName) && RetroUtil.isAllowedToDownloadMetadata(context)) { - Response response = lastFMRestClient.getApiService().getArtistInfo(model.artistName, null, model.skipOkHttpCache ? "no-cache" : null).execute(); - - if (!response.isSuccessful()) { - throw new IOException("Request failed with code: " + response.code()); - } - - LastFmArtist lastFmArtist = response.body(); - - if (isCancelled) return null; - - GlideUrl url = new GlideUrl(LastFMUtil.getLargestArtistImageUrl(lastFmArtist.getArtist().getImage())); - urlFetcher = urlLoader.getResourceFetcher(url, width, height); - - return urlFetcher.loadData(priority); - } - return null; - } - - @Override - public void cleanup() { - if (urlFetcher != null) { - urlFetcher.cleanup(); - } - } - - @Override - public void cancel() { - isCancelled = true; - if (urlFetcher != null) { - urlFetcher.cancel(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.kt b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.kt new file mode 100644 index 00000000..55b0739b --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageFetcher.kt @@ -0,0 +1,69 @@ +package code.name.monkey.retromusic.glide.artistimage + +import android.content.Context + +import com.bumptech.glide.Priority +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.model.GlideUrl +import com.bumptech.glide.load.model.ModelLoader +import code.name.monkey.retromusic.rest.LastFMRestClient +import code.name.monkey.retromusic.rest.model.LastFmArtist + +import code.name.monkey.retromusic.util.LastFMUtil +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.RetroUtil + +import java.io.IOException +import java.io.InputStream + +import retrofit2.Response + + +class ArtistImageFetcher(private val context: Context, private val lastFMRestClient: LastFMRestClient, private val model: ArtistImage, private val urlLoader: ModelLoader, private val width: Int, private val height: Int) : DataFetcher { + @Volatile + private var isCancelled: Boolean = false + private var urlFetcher: DataFetcher? = null + + override fun getId(): String { + // makes sure we never ever return null here + return model.artistName + } + + @Throws(Exception::class) + override fun loadData(priority: Priority): InputStream? { + if (!MusicUtil.isArtistNameUnknown(model.artistName) && RetroUtil.isAllowedToDownloadMetadata(context)) { + val response = lastFMRestClient.apiService.getArtistInfo(model.artistName, null, if (model.skipOkHttpCache) "no-cache" else null).execute() + + if (!response.isSuccessful) { + throw IOException("Request failed with code: " + response.code()) + } + + val lastFmArtist = response.body() + + if (isCancelled) return null + + val url = GlideUrl(LastFMUtil.getLargestArtistImageUrl(lastFmArtist!!.artist.image)) + urlFetcher = urlLoader.getResourceFetcher(url, width, height) + + return urlFetcher!!.loadData(priority) + } + return null + } + + override fun cleanup() { + if (urlFetcher != null) { + urlFetcher!!.cleanup() + } + } + + override fun cancel() { + isCancelled = true + if (urlFetcher != null) { + urlFetcher!!.cancel() + } + } + + companion object { + val TAG = ArtistImageFetcher::class.java.simpleName + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.java b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.java deleted file mode 100644 index 09392ced..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.java +++ /dev/null @@ -1,68 +0,0 @@ -package code.name.monkey.retromusic.glide.artistimage; - -import android.content.Context; - -import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader; -import com.bumptech.glide.load.data.DataFetcher; -import com.bumptech.glide.load.model.GenericLoaderFactory; -import com.bumptech.glide.load.model.GlideUrl; -import com.bumptech.glide.load.model.ModelLoader; -import com.bumptech.glide.load.model.ModelLoaderFactory; -import com.bumptech.glide.load.model.stream.StreamModelLoader; -import code.name.monkey.retromusic.rest.LastFMRestClient; - -import java.io.InputStream; -import java.util.concurrent.TimeUnit; - -import okhttp3.OkHttpClient; - - - -public class ArtistImageLoader implements StreamModelLoader { - // we need these very low values to make sure our artist image loading calls doesn't block the image loading queue - private static final int TIMEOUT = 500; - - private Context context; - private LastFMRestClient lastFMClient; - private ModelLoader urlLoader; - - public ArtistImageLoader(Context context, LastFMRestClient lastFMRestClient, ModelLoader urlLoader) { - this.context = context; - this.lastFMClient = lastFMRestClient; - this.urlLoader = urlLoader; - } - - @Override - public DataFetcher getResourceFetcher(ArtistImage model, int width, int height) { - return new ArtistImageFetcher(context, lastFMClient, model, urlLoader, width, height); - } - - public static class Factory implements ModelLoaderFactory { - private LastFMRestClient lastFMClient; - private OkHttpUrlLoader.Factory okHttpFactory; - - public Factory(Context context) { - okHttpFactory = new OkHttpUrlLoader.Factory(new OkHttpClient.Builder() - .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS) - .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS) - .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS) - .build()); - lastFMClient = new LastFMRestClient(LastFMRestClient.createDefaultOkHttpClientBuilder(context) - .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS) - .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS) - .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS) - .build()); - } - - @Override - public ModelLoader build(Context context, GenericLoaderFactory factories) { - return new ArtistImageLoader(context, lastFMClient, okHttpFactory.build(context, factories)); - } - - @Override - public void teardown() { - okHttpFactory.teardown(); - } - } -} - diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.kt b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.kt new file mode 100644 index 00000000..7b8c1133 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/artistimage/ArtistImageLoader.kt @@ -0,0 +1,52 @@ +package code.name.monkey.retromusic.glide.artistimage + +import android.content.Context + +import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.model.GenericLoaderFactory +import com.bumptech.glide.load.model.GlideUrl +import com.bumptech.glide.load.model.ModelLoader +import com.bumptech.glide.load.model.ModelLoaderFactory +import com.bumptech.glide.load.model.stream.StreamModelLoader +import code.name.monkey.retromusic.rest.LastFMRestClient + +import java.io.InputStream +import java.util.concurrent.TimeUnit + +import okhttp3.OkHttpClient + + +class ArtistImageLoader(private val context: Context, private val lastFMClient: LastFMRestClient, private val urlLoader: ModelLoader) : StreamModelLoader { + + override fun getResourceFetcher(model: ArtistImage, width: Int, height: Int): DataFetcher { + return ArtistImageFetcher(context, lastFMClient, model, urlLoader, width, height) + } + + class Factory(context: Context) : ModelLoaderFactory { + private val lastFMClient: LastFMRestClient = LastFMRestClient(LastFMRestClient.createDefaultOkHttpClientBuilder(context) + .connectTimeout(TIMEOUT.toLong(), TimeUnit.MILLISECONDS) + .readTimeout(TIMEOUT.toLong(), TimeUnit.MILLISECONDS) + .writeTimeout(TIMEOUT.toLong(), TimeUnit.MILLISECONDS) + .build()) + private val okHttpFactory: OkHttpUrlLoader.Factory = OkHttpUrlLoader.Factory(OkHttpClient.Builder() + .connectTimeout(TIMEOUT.toLong(), TimeUnit.MILLISECONDS) + .readTimeout(TIMEOUT.toLong(), TimeUnit.MILLISECONDS) + .writeTimeout(TIMEOUT.toLong(), TimeUnit.MILLISECONDS) + .build()) + + override fun build(context: Context, factories: GenericLoaderFactory): ModelLoader { + return ArtistImageLoader(context, lastFMClient, okHttpFactory.build(context, factories)) + } + + override fun teardown() { + okHttpFactory.teardown() + } + } + + companion object { + // we need these very low values to make sure our artist image loading calls doesn't block the image loading queue + private const val TIMEOUT = 500 + } +} + diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.java b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.java deleted file mode 100644 index 3a163bc1..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.java +++ /dev/null @@ -1,10 +0,0 @@ -package code.name.monkey.retromusic.glide.audiocover; - - -public class AudioFileCover { - public final String filePath; - - public AudioFileCover(String filePath) { - this.filePath = filePath; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.kt b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.kt new file mode 100644 index 00000000..abf89e1e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCover.kt @@ -0,0 +1,4 @@ +package code.name.monkey.retromusic.glide.audiocover + + +class AudioFileCover(val filePath: String) diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.java b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.java deleted file mode 100644 index 8985da7c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.java +++ /dev/null @@ -1,95 +0,0 @@ -package code.name.monkey.retromusic.glide.audiocover; - -import android.media.MediaMetadataRetriever; - -import com.bumptech.glide.Priority; -import com.bumptech.glide.load.data.DataFetcher; - -import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException; -import org.jaudiotagger.audio.exceptions.ReadOnlyFileException; -import org.jaudiotagger.audio.mp3.MP3File; -import org.jaudiotagger.tag.TagException; -import org.jaudiotagger.tag.images.Artwork; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - - -public class AudioFileCoverFetcher implements DataFetcher { - private static final String[] FALLBACKS = {"cover.jpg", "album.jpg", "folder.jpg", "cover.png", "album.png", "folder.png"}; - private final AudioFileCover model; - private FileInputStream stream; - - public AudioFileCoverFetcher(AudioFileCover model) { - this.model = model; - } - - @Override - public String getId() { - // makes sure we never ever return null here - return String.valueOf(model.filePath); - } - - @Override - public InputStream loadData(Priority priority) throws Exception { - MediaMetadataRetriever retriever = new MediaMetadataRetriever(); - try { - retriever.setDataSource(model.filePath); - byte[] picture = retriever.getEmbeddedPicture(); - if (picture != null) { - return new ByteArrayInputStream(picture); - } else { - return fallback(model.filePath); - } - } finally { - retriever.release(); - } - } - - private InputStream fallback(String path) throws FileNotFoundException { - // Method 1: use embedded high resolution album art if there is any - try { - MP3File mp3File = new MP3File(path); - if (mp3File.hasID3v2Tag()) { - Artwork art = mp3File.getTag().getFirstArtwork(); - if (art != null) { - byte[] imageData = art.getBinaryData(); - return new ByteArrayInputStream(imageData); - } - } - // If there are any exceptions, we ignore them and continue to the other fallback method - } catch (ReadOnlyFileException | InvalidAudioFrameException | TagException | IOException ignored) { - } - - // Method 2: look for album art in external files - File parent = new File(path).getParentFile(); - for (String fallback : FALLBACKS) { - File cover = new File(parent, fallback); - if (cover.exists()) { - return stream = new FileInputStream(cover); - } - } - return null; - } - - @Override - public void cleanup() { - // already cleaned up in loadData and ByteArrayInputStream will be GC'd - if (stream != null) { - try { - stream.close(); - } catch (IOException ignore) { - // can't do much about it - } - } - } - - @Override - public void cancel() { - // cannot cancel - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.kt b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.kt new file mode 100644 index 00000000..9609cd04 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverFetcher.kt @@ -0,0 +1,87 @@ +package code.name.monkey.retromusic.glide.audiocover + +import android.media.MediaMetadataRetriever +import com.bumptech.glide.Priority +import com.bumptech.glide.load.data.DataFetcher +import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException +import org.jaudiotagger.audio.exceptions.ReadOnlyFileException +import org.jaudiotagger.audio.mp3.MP3File +import org.jaudiotagger.tag.TagException +import java.io.* + + +class AudioFileCoverFetcher(private val model: AudioFileCover) : DataFetcher { + private var stream: FileInputStream? = null + + override fun getId(): String { + // makes sure we never ever return null here + return model.filePath + } + + @Throws(Exception::class) + override fun loadData(priority: Priority): InputStream? { + val retriever = MediaMetadataRetriever() + try { + retriever.setDataSource(model.filePath) + val picture = retriever.embeddedPicture + return if (picture != null) { + ByteArrayInputStream(picture) + } else { + fallback(model.filePath) + } + } finally { + retriever.release() + } + } + + @Throws(FileNotFoundException::class) + private fun fallback(path: String): InputStream? { + // Method 1: use embedded high resolution album art if there is any + try { + val mp3File = MP3File(path) + if (mp3File.hasID3v2Tag()) { + val art = mp3File.tag.firstArtwork + if (art != null) { + val imageData = art.binaryData + return ByteArrayInputStream(imageData) + } + } + // If there are any exceptions, we ignore them and continue to the other fallback method + } catch (ignored: ReadOnlyFileException) { + } catch (ignored: InvalidAudioFrameException) { + } catch (ignored: TagException) { + } catch (ignored: IOException) { + } + + // Method 2: look for album art in external files + val parent = File(path).parentFile + for (fallback in FALLBACKS) { + val cover = File(parent, fallback) + if (cover.exists()) { + stream = FileInputStream(cover) + return stream + } + } + return null + } + + override fun cleanup() { + // already cleaned up in loadData and ByteArrayInputStream will be GC'd + if (stream != null) { + try { + stream!!.close() + } catch (ignore: IOException) { + // can't do much about it + } + + } + } + + override fun cancel() { + // cannot cancel + } + + companion object { + private val FALLBACKS = arrayOf("cover.jpg", "album.jpg", "folder.jpg", "cover.png", "album.png", "folder.png") + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.java b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.java deleted file mode 100644 index 2b02c9b3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.java +++ /dev/null @@ -1,32 +0,0 @@ -package code.name.monkey.retromusic.glide.audiocover; - -import android.content.Context; - -import com.bumptech.glide.load.data.DataFetcher; -import com.bumptech.glide.load.model.GenericLoaderFactory; -import com.bumptech.glide.load.model.ModelLoader; -import com.bumptech.glide.load.model.ModelLoaderFactory; -import com.bumptech.glide.load.model.stream.StreamModelLoader; - -import java.io.InputStream; - - -public class AudioFileCoverLoader implements StreamModelLoader { - - @Override - public DataFetcher getResourceFetcher(AudioFileCover model, int width, int height) { - return new AudioFileCoverFetcher(model); - } - - public static class Factory implements ModelLoaderFactory { - @Override - public ModelLoader build(Context context, GenericLoaderFactory factories) { - return new AudioFileCoverLoader(); - } - - @Override - public void teardown() { - } - } -} - diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.kt b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.kt new file mode 100644 index 00000000..c3e2997c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/audiocover/AudioFileCoverLoader.kt @@ -0,0 +1,28 @@ +package code.name.monkey.retromusic.glide.audiocover + +import android.content.Context + +import com.bumptech.glide.load.data.DataFetcher +import com.bumptech.glide.load.model.GenericLoaderFactory +import com.bumptech.glide.load.model.ModelLoader +import com.bumptech.glide.load.model.ModelLoaderFactory +import com.bumptech.glide.load.model.stream.StreamModelLoader + +import java.io.InputStream + + +class AudioFileCoverLoader : StreamModelLoader { + + override fun getResourceFetcher(model: AudioFileCover, width: Int, height: Int): DataFetcher { + return AudioFileCoverFetcher(model) + } + + class Factory : ModelLoaderFactory { + override fun build(context: Context, factories: GenericLoaderFactory): ModelLoader { + return AudioFileCoverLoader() + } + + override fun teardown() {} + } +} + diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.java b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.java deleted file mode 100644 index 201e43b7..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.java +++ /dev/null @@ -1,34 +0,0 @@ -package code.name.monkey.retromusic.glide.palette; - -import com.bumptech.glide.load.engine.Resource; -import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; -import com.bumptech.glide.util.Util; - - -public class BitmapPaletteResource implements Resource { - - private final BitmapPaletteWrapper bitmapPaletteWrapper; - private final BitmapPool bitmapPool; - - public BitmapPaletteResource(BitmapPaletteWrapper bitmapPaletteWrapper, BitmapPool bitmapPool) { - this.bitmapPaletteWrapper = bitmapPaletteWrapper; - this.bitmapPool = bitmapPool; - } - - @Override - public BitmapPaletteWrapper get() { - return bitmapPaletteWrapper; - } - - @Override - public int getSize() { - return Util.getBitmapByteSize(bitmapPaletteWrapper.getBitmap()); - } - - @Override - public void recycle() { - if (!bitmapPool.put(bitmapPaletteWrapper.getBitmap())) { - bitmapPaletteWrapper.getBitmap().recycle(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.kt b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.kt new file mode 100644 index 00000000..9ce2896e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteResource.kt @@ -0,0 +1,23 @@ +package code.name.monkey.retromusic.glide.palette + +import com.bumptech.glide.load.engine.Resource +import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool +import com.bumptech.glide.util.Util + + +class BitmapPaletteResource(private val bitmapPaletteWrapper: BitmapPaletteWrapper, private val bitmapPool: BitmapPool) : Resource { + + override fun get(): BitmapPaletteWrapper { + return bitmapPaletteWrapper + } + + override fun getSize(): Int { + return Util.getBitmapByteSize(bitmapPaletteWrapper.bitmap) + } + + override fun recycle() { + if (!bitmapPool.put(bitmapPaletteWrapper.bitmap)) { + bitmapPaletteWrapper.bitmap.recycle() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.java b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.java deleted file mode 100644 index ad5cf47a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.java +++ /dev/null @@ -1,34 +0,0 @@ -package code.name.monkey.retromusic.glide.palette; - -import android.content.Context; -import android.graphics.Bitmap; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.load.engine.Resource; -import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; -import com.bumptech.glide.load.resource.transcode.ResourceTranscoder; -import code.name.monkey.retromusic.util.RetroColorUtil; - -public class BitmapPaletteTranscoder implements ResourceTranscoder { - private final BitmapPool bitmapPool; - - public BitmapPaletteTranscoder(Context context) { - this(Glide.get(context).getBitmapPool()); - } - - public BitmapPaletteTranscoder(BitmapPool bitmapPool) { - this.bitmapPool = bitmapPool; - } - - @Override - public Resource transcode(Resource bitmapResource) { - Bitmap bitmap = bitmapResource.get(); - BitmapPaletteWrapper bitmapPaletteWrapper = new BitmapPaletteWrapper(bitmap, RetroColorUtil.generatePalette(bitmap)); - return new BitmapPaletteResource(bitmapPaletteWrapper, bitmapPool); - } - - @Override - public String getId() { - return "BitmapPaletteTranscoder.code.name.monkey.retromusic.glide.palette"; - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.kt b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.kt new file mode 100644 index 00000000..bc85737e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteTranscoder.kt @@ -0,0 +1,25 @@ +package code.name.monkey.retromusic.glide.palette + +import android.content.Context +import android.graphics.Bitmap + +import com.bumptech.glide.Glide +import com.bumptech.glide.load.engine.Resource +import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool +import com.bumptech.glide.load.resource.transcode.ResourceTranscoder +import code.name.monkey.retromusic.util.RetroColorUtil + +class BitmapPaletteTranscoder(private val bitmapPool: BitmapPool) : ResourceTranscoder { + + constructor(context: Context) : this(Glide.get(context).bitmapPool) {} + + override fun transcode(bitmapResource: Resource): Resource { + val bitmap = bitmapResource.get() + val bitmapPaletteWrapper = BitmapPaletteWrapper(bitmap, RetroColorUtil.generatePalette(bitmap)!!) + return BitmapPaletteResource(bitmapPaletteWrapper, bitmapPool) + } + + override fun getId(): String { + return "BitmapPaletteTranscoder.code.name.monkey.retromusic.glide.palette" + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.java b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.java deleted file mode 100644 index 8c65631b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.java +++ /dev/null @@ -1,22 +0,0 @@ -package code.name.monkey.retromusic.glide.palette; - -import android.graphics.Bitmap; -import androidx.palette.graphics.Palette; - -public class BitmapPaletteWrapper { - private final Bitmap mBitmap; - private final Palette mPalette; - - public BitmapPaletteWrapper(Bitmap bitmap, Palette palette) { - mBitmap = bitmap; - mPalette = palette; - } - - public Bitmap getBitmap() { - return mBitmap; - } - - public Palette getPalette() { - return mPalette; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.kt b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.kt new file mode 100644 index 00000000..aab11d46 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/glide/palette/BitmapPaletteWrapper.kt @@ -0,0 +1,6 @@ +package code.name.monkey.retromusic.glide.palette + +import android.graphics.Bitmap +import androidx.palette.graphics.Palette + +class BitmapPaletteWrapper(val bitmap: Bitmap, val palette: Palette) diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.java deleted file mode 100644 index 68a4e9f4..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.java +++ /dev/null @@ -1,12 +0,0 @@ -package code.name.monkey.retromusic.mvp; - -/** - * Created by hemanths on 09/08/17. - */ - -public interface BasePresenter { - - void subscribe(); - - void unsubscribe(); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.kt new file mode 100644 index 00000000..9f2ed73f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/BasePresenter.kt @@ -0,0 +1,12 @@ +package code.name.monkey.retromusic.mvp + +/** + * Created by hemanths on 09/08/17. + */ + +interface BasePresenter { + + fun subscribe() + + fun unsubscribe() +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.java b/app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.java deleted file mode 100644 index 70f08539..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.java +++ /dev/null @@ -1,15 +0,0 @@ -package code.name.monkey.retromusic.mvp; - -/** - * Created by hemanths on 09/08/17. - */ - -public interface BaseView { - void loading(); - - void showData(T list); - - void showEmptyView(); - - void completed(); -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.kt new file mode 100644 index 00000000..7d9ca96e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/BaseView.kt @@ -0,0 +1,15 @@ +package code.name.monkey.retromusic.mvp + +/** + * Created by hemanths on 09/08/17. + */ + +interface BaseView { + fun loading() + + fun showData(list: T) + + fun showEmptyView() + + fun completed() +} 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 deleted file mode 100644 index 59e52b04..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.java +++ /dev/null @@ -1,27 +0,0 @@ -package code.name.monkey.retromusic.mvp; - -import androidx.annotation.NonNull; - -import code.name.monkey.retromusic.Injection; -import code.name.monkey.retromusic.providers.interfaces.Repository; -import code.name.monkey.retromusic.util.schedulers.BaseSchedulerProvider; -import io.reactivex.disposables.CompositeDisposable; - -/** - * Created by hemanths on 16/08/17. - */ - -public class Presenter { - @NonNull - protected Repository repository; - @NonNull - protected CompositeDisposable disposable; - @NonNull - protected BaseSchedulerProvider schedulerProvider; - - public Presenter() { - 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/mvp/Presenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.kt new file mode 100644 index 00000000..d854edf7 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/Presenter.kt @@ -0,0 +1,16 @@ +package code.name.monkey.retromusic.mvp + +import code.name.monkey.retromusic.Injection +import code.name.monkey.retromusic.providers.interfaces.Repository +import code.name.monkey.retromusic.util.schedulers.BaseSchedulerProvider +import io.reactivex.disposables.CompositeDisposable + +/** + * Created by hemanths on 16/08/17. + */ + +open class Presenter { + protected var repository: Repository = Injection.provideRepository() + protected var disposable: CompositeDisposable = CompositeDisposable() + protected var schedulerProvider: BaseSchedulerProvider = Injection.provideSchedulerProvider() +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.java deleted file mode 100644 index ae3a8838..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.java +++ /dev/null @@ -1,19 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; -import java.util.ArrayList; - -public interface AlbumContract { - - interface AlbumView extends BaseView> { - - } - - interface Presenter extends BasePresenter { - - void loadAlbums(); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.kt new file mode 100644 index 00000000..6a8b9e35 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumContract.kt @@ -0,0 +1,17 @@ +package code.name.monkey.retromusic.mvp.contract + +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView +import java.util.ArrayList + +interface AlbumContract { + + interface AlbumView : BaseView> + + interface Presenter : BasePresenter { + + fun loadAlbums() + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.java deleted file mode 100644 index d22d5b0a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.java +++ /dev/null @@ -1,18 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - - -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -public interface AlbumDetailsContract { - - interface AlbumDetailsView extends BaseView { - - } - - interface Presenter extends BasePresenter { - - void loadAlbumSongs(int albumId); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.kt new file mode 100644 index 00000000..34f80461 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/AlbumDetailsContract.kt @@ -0,0 +1,16 @@ +package code.name.monkey.retromusic.mvp.contract + + +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +interface AlbumDetailsContract { + + interface AlbumDetailsView : BaseView + + interface Presenter : BasePresenter { + + fun loadAlbumSongs(albumId: Int) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.java deleted file mode 100644 index b9d179c3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.java +++ /dev/null @@ -1,23 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - - -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - - -/** - * Created by hemanths on 16/08/17. - */ - -public interface ArtistContract { - interface ArtistView extends BaseView> { - - } - - interface Presenter extends BasePresenter { - void loadArtists(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.kt new file mode 100644 index 00000000..620febba --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistContract.kt @@ -0,0 +1,21 @@ +package code.name.monkey.retromusic.mvp.contract + + +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + + +/** + * Created by hemanths on 16/08/17. + */ + +interface ArtistContract { + interface ArtistView : BaseView> + + interface Presenter : BasePresenter { + fun loadArtists() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.java deleted file mode 100644 index 90b5a2c3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.java +++ /dev/null @@ -1,21 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - - -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - - -/** - * Created by hemanths on 20/08/17. - */ - -public interface ArtistDetailContract { - interface ArtistsDetailsView extends BaseView { - - } - - interface Presenter extends BasePresenter { - void loadArtistById(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.kt new file mode 100644 index 00000000..1d749cf9 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/ArtistDetailContract.kt @@ -0,0 +1,19 @@ +package code.name.monkey.retromusic.mvp.contract + + +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + + +/** + * Created by hemanths on 20/08/17. + */ + +interface ArtistDetailContract { + interface ArtistsDetailsView : BaseView + + interface Presenter : BasePresenter { + fun loadArtistById() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.java deleted file mode 100644 index d47d14f9..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.java +++ /dev/null @@ -1,21 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - -/** - * @author Hemanth S (h4h13). - */ - -public interface GenreContract { - interface GenreView extends BaseView> { - - } - - interface Presenter extends BasePresenter { - void loadGenre(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.kt new file mode 100644 index 00000000..22d0d8a8 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreContract.kt @@ -0,0 +1,19 @@ +package code.name.monkey.retromusic.mvp.contract + +import code.name.monkey.retromusic.model.Genre +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + +/** + * @author Hemanth S (h4h13). + */ + +interface GenreContract { + interface GenreView : BaseView> + + interface Presenter : BasePresenter { + fun loadGenre() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.java deleted file mode 100644 index 7eeb5b6a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.java +++ /dev/null @@ -1,20 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - -/** - * @author Hemanth S (h4h13). - */ - -public interface GenreDetailsContract { - interface GenreDetailsView extends BaseView> { - } - - interface Presenter extends BasePresenter { - void loadGenre(int genreId); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.kt new file mode 100644 index 00000000..298d45c4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/GenreDetailsContract.kt @@ -0,0 +1,19 @@ +package code.name.monkey.retromusic.mvp.contract + +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + +/** + * @author Hemanth S (h4h13). + */ + +interface GenreDetailsContract { + interface GenreDetailsView : BaseView> + + interface Presenter : BasePresenter { + fun loadGenre(genreId: Int) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.java deleted file mode 100644 index b5dd863c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.java +++ /dev/null @@ -1,47 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.AbsCustomPlaylist; -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.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -public interface HomeContract { - - interface HomeView extends BaseView> { - - void recentArtist(ArrayList artists); - - void recentAlbum(ArrayList albums); - - void topArtists(ArrayList artists); - - void topAlbums(ArrayList albums); - - void suggestions(ArrayList songs); - - void playlists(ArrayList playlists); - - void geners(ArrayList songs); - } - - interface HomePresenter extends BasePresenter { - - void loadRecentAlbums(); - - void loadTopAlbums(); - - void loadRecentArtists(); - - void loadTopArtists(); - - void loadSuggestions(); - - void loadGenres(); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.kt new file mode 100644 index 00000000..418e0764 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/HomeContract.kt @@ -0,0 +1,47 @@ +package code.name.monkey.retromusic.mvp.contract + +import java.util.ArrayList + +import code.name.monkey.retromusic.model.AbsCustomPlaylist +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.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +interface HomeContract { + + interface HomeView : BaseView> { + + fun recentArtist(artists: ArrayList) + + fun recentAlbum(albums: ArrayList) + + fun topArtists(artists: ArrayList) + + fun topAlbums(albums: ArrayList) + + fun suggestions(songs: ArrayList) + + fun playlists(playlists: ArrayList) + + fun geners(songs: ArrayList) + } + + interface HomePresenter : BasePresenter { + + fun loadRecentAlbums() + + fun loadTopAlbums() + + fun loadRecentArtists() + + fun loadTopArtists() + + fun loadSuggestions() + + fun loadGenres() + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.java deleted file mode 100644 index 7a40a5e5..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.java +++ /dev/null @@ -1,21 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - -/** - * Created by hemanths on 19/08/17. - */ - -public interface PlaylistContract { - interface PlaylistView extends BaseView > { - - } - - interface Presenter extends BasePresenter { - void loadPlaylists(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.kt new file mode 100644 index 00000000..fd9ffb10 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistContract.kt @@ -0,0 +1,19 @@ +package code.name.monkey.retromusic.mvp.contract + +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + +/** + * Created by hemanths on 19/08/17. + */ + +interface PlaylistContract { + interface PlaylistView : BaseView> + + interface Presenter : BasePresenter { + fun loadPlaylists() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.java deleted file mode 100644 index 48639a8f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.java +++ /dev/null @@ -1,23 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - - -/** - * Created by hemanths on 20/08/17. - */ - -public interface PlaylistSongsContract { - interface PlaylistSongsView extends BaseView> { - - } - - interface Presenter extends BasePresenter { - void loadSongs(Playlist playlist); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.kt new file mode 100644 index 00000000..81db8bbe --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/PlaylistSongsContract.kt @@ -0,0 +1,21 @@ +package code.name.monkey.retromusic.mvp.contract + +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + + +/** + * Created by hemanths on 20/08/17. + */ + +interface PlaylistSongsContract { + interface PlaylistSongsView : BaseView> + + interface Presenter : BasePresenter { + fun loadSongs(playlist: Playlist) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.java deleted file mode 100644 index 2684894e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.java +++ /dev/null @@ -1,21 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - - -/** - * Created by hemanths on 20/08/17. - */ - -public interface SearchContract { - interface SearchView extends BaseView> { - - } - - interface SearchPresenter extends BasePresenter { - void search(String query); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.kt new file mode 100644 index 00000000..193b9247 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SearchContract.kt @@ -0,0 +1,19 @@ +package code.name.monkey.retromusic.mvp.contract + +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + + +/** + * Created by hemanths on 20/08/17. + */ + +interface SearchContract { + interface SearchView : BaseView> + + interface SearchPresenter : BasePresenter { + fun search(query: String) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.java b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.java deleted file mode 100644 index 2ec627e0..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.java +++ /dev/null @@ -1,24 +0,0 @@ -package code.name.monkey.retromusic.mvp.contract; - - -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.BasePresenter; -import code.name.monkey.retromusic.mvp.BaseView; - -import java.util.ArrayList; - - -/** - * Created by hemanths on 10/08/17. - */ - -public interface SongContract { - - interface SongView extends BaseView> { - - } - - interface Presenter extends BasePresenter { - void loadSongs(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.kt new file mode 100644 index 00000000..2c0b156d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/contract/SongContract.kt @@ -0,0 +1,22 @@ +package code.name.monkey.retromusic.mvp.contract + + +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.mvp.BasePresenter +import code.name.monkey.retromusic.mvp.BaseView + +import java.util.ArrayList + + +/** + * Created by hemanths on 10/08/17. + */ + +interface SongContract { + + interface SongView : BaseView> + + interface Presenter : BasePresenter { + fun loadSongs() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.java deleted file mode 100644 index b136089e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.java +++ /dev/null @@ -1,54 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.AlbumDetailsContract; - - -/** - * Created by hemanths on 20/08/17. - */ - -public class AlbumDetailsPresenter extends Presenter implements AlbumDetailsContract.Presenter { - - @NonNull - private final int albumId; - @NonNull - private AlbumDetailsContract.AlbumDetailsView view; - - public AlbumDetailsPresenter(@NonNull AlbumDetailsContract.AlbumDetailsView view, int albumId) { - - this.view = view; - this.albumId = albumId; - } - - @Override - public void subscribe() { - loadAlbumSongs(albumId); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - @Override - public void loadAlbumSongs(int albumId) { - disposable.add(repository.getAlbum(albumId) - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(this::showAlbum, - throwable -> view.showEmptyView(), - () -> view.completed())); - } - - private void showAlbum(Album album) { - if (album != null) { - view.showData(album); - } else { - view.showEmptyView(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.kt new file mode 100644 index 00000000..d5a4f82c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumDetailsPresenter.kt @@ -0,0 +1,39 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.AlbumDetailsContract + + +/** + * Created by hemanths on 20/08/17. + */ + +class AlbumDetailsPresenter(private val view: AlbumDetailsContract.AlbumDetailsView, private val albumId: Int) : Presenter(), AlbumDetailsContract.Presenter { + + override fun subscribe() { + loadAlbumSongs(albumId) + } + + override fun unsubscribe() { + disposable.clear() + } + + override fun loadAlbumSongs(albumId: Int) { + disposable.add(repository.getAlbum(albumId) + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showAlbum(it) }, + { view.showEmptyView() }, + { view.completed() })) + } + + private fun showAlbum(album: Album?) { + if (album != null) { + view.showData(album) + } else { + view.showEmptyView() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.java deleted file mode 100644 index dc2ba3ef..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.java +++ /dev/null @@ -1,49 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Album; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.AlbumContract; - - -/** - * Created by hemanths on 12/08/17. - */ - -public class AlbumPresenter extends Presenter implements AlbumContract.Presenter { - @NonNull - private AlbumContract.AlbumView view; - - - public AlbumPresenter(@NonNull AlbumContract.AlbumView view) { - this.view = view; - } - - @Override - public void subscribe() { - loadAlbums(); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - private void showList(@NonNull ArrayList albums) { - view.showData(albums); - } - - @Override - public void loadAlbums() { - disposable.add(repository.getAllAlbums() - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(this::showList, - throwable -> view.showEmptyView(), - () -> view.completed())); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.kt new file mode 100644 index 00000000..5b04de0b --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/AlbumPresenter.kt @@ -0,0 +1,36 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Album +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.AlbumContract +import java.util.* + + +/** + * Created by hemanths on 12/08/17. + */ + +class AlbumPresenter(private val view: AlbumContract.AlbumView) : Presenter(), AlbumContract.Presenter { + + override fun subscribe() { + loadAlbums() + } + + override fun unsubscribe() { + disposable.clear() + } + + private fun showList(albums: ArrayList) { + view.showData(albums) + } + + override fun loadAlbums() { + disposable.add(repository.allAlbums + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showList(it) }, + { view.showEmptyView() }, + { view.completed() })) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.java deleted file mode 100644 index c09e12fc..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.java +++ /dev/null @@ -1,56 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import android.os.Bundle; - -import androidx.annotation.NonNull; -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.ArtistDetailContract; -import code.name.monkey.retromusic.ui.activities.ArtistDetailActivity; - - -/** - * Created by hemanths on 20/08/17. - */ - -public class ArtistDetailsPresenter extends Presenter implements ArtistDetailContract.Presenter { - - @NonNull - private final ArtistDetailContract.ArtistsDetailsView view; - private Bundle bundle; - - public ArtistDetailsPresenter(@NonNull ArtistDetailContract.ArtistsDetailsView view, - Bundle artistId) { - this.view = view; - this.bundle = artistId; - } - - @Override - public void subscribe() { - loadArtistById(); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - @Override - public void loadArtistById() { - disposable.add(repository.getArtistById(bundle.getInt(ArtistDetailActivity.EXTRA_ARTIST_ID)) - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(this::showArtist, - throwable -> view.showEmptyView(), - view::completed)); - } - - private void showArtist(Artist album) { - if (album != null) { - view.showData(album); - } else { - view.showEmptyView(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.kt new file mode 100644 index 00000000..915d75ba --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistDetailsPresenter.kt @@ -0,0 +1,42 @@ +package code.name.monkey.retromusic.mvp.presenter + +import android.os.Bundle +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.ArtistDetailContract +import code.name.monkey.retromusic.ui.activities.ArtistDetailActivity + + +/** + * Created by hemanths on 20/08/17. + */ + +class ArtistDetailsPresenter(private val view: ArtistDetailContract.ArtistsDetailsView, + private val bundle: Bundle) : Presenter(), ArtistDetailContract.Presenter { + + override fun subscribe() { + loadArtistById() + } + + override fun unsubscribe() { + disposable.clear() + } + + override fun loadArtistById() { + disposable.add(repository.getArtistById(bundle.getInt(ArtistDetailActivity.EXTRA_ARTIST_ID).toLong()) + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showArtist(it) }, + { view.showEmptyView() }, + { view.completed() })) + } + + private fun showArtist(album: Artist?) { + if (album != null) { + view.showData(album) + } else { + view.showEmptyView() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.java deleted file mode 100644 index 9e2d3526..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.java +++ /dev/null @@ -1,47 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Artist; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.ArtistContract; - -public class ArtistPresenter extends Presenter implements ArtistContract.Presenter { - @NonNull - private ArtistContract.ArtistView mView; - - public ArtistPresenter(@NonNull ArtistContract.ArtistView view) { - mView = view; - } - - @Override - public void subscribe() { - loadArtists(); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - private void showList(@NonNull ArrayList songs) { - if (songs.isEmpty()) { - mView.showEmptyView(); - } else { - mView.showData(songs); - } - } - - @Override - public void loadArtists() { - disposable.add(repository.getAllArtists() - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> mView.loading()) - .subscribe(this::showList, - throwable -> mView.showEmptyView(), - () -> mView.completed())); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.kt new file mode 100644 index 00000000..41ffa10b --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/ArtistPresenter.kt @@ -0,0 +1,35 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Artist +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.ArtistContract +import java.util.* + +class ArtistPresenter(private val mView: ArtistContract.ArtistView) : Presenter(), ArtistContract.Presenter { + + override fun subscribe() { + loadArtists() + } + + override fun unsubscribe() { + disposable.clear() + } + + private fun showList(songs: ArrayList) { + if (songs.isEmpty()) { + mView.showEmptyView() + } else { + mView.showData(songs) + } + } + + override fun loadArtists() { + disposable.add(repository.allArtists + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { mView.loading() } + .subscribe({ this.showList(it) }, + { mView.showEmptyView() }, + { mView.completed() })) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.java deleted file mode 100644 index 9f3e176e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.java +++ /dev/null @@ -1,56 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.GenreDetailsContract; - - -/** - * Created by hemanths on 20/08/17. - */ - -public class GenreDetailsPresenter extends Presenter - implements GenreDetailsContract.Presenter { - private final int genreId; - @NonNull - private GenreDetailsContract.GenreDetailsView view; - - public GenreDetailsPresenter(@NonNull GenreDetailsContract.GenreDetailsView view, - int genreId) { - this.view = view; - this.genreId = genreId; - } - - @Override - public void subscribe() { - loadGenre(genreId); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - @Override - public void loadGenre(int genreId) { - disposable.add(repository.getGenre(genreId) - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(this::showGenre, - throwable -> view.showEmptyView(), - () -> view.completed())); - } - - private void showGenre(ArrayList songs) { - if (songs != null) { - view.showData(songs); - } else { - view.showEmptyView(); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.kt new file mode 100644 index 00000000..d4f88534 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenreDetailsPresenter.kt @@ -0,0 +1,41 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.GenreDetailsContract +import java.util.* + + +/** + * Created by hemanths on 20/08/17. + */ + +class GenreDetailsPresenter(private val view: GenreDetailsContract.GenreDetailsView, + private val genreId: Int) : Presenter(), GenreDetailsContract.Presenter { + + override fun subscribe() { + loadGenre(genreId) + } + + override fun unsubscribe() { + disposable.clear() + } + + override fun loadGenre(genreId: Int) { + disposable.add(repository.getGenre(genreId) + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showGenre(it) }, + { view.showEmptyView() }, + { view.completed() })) + } + + private fun showGenre(songs: ArrayList?) { + if (songs != null) { + view.showData(songs) + } else { + view.showEmptyView() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.java deleted file mode 100644 index 3542a689..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.java +++ /dev/null @@ -1,53 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Genre; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.GenreContract; - -/** - * @author Hemanth S (h4h13). - */ - -public class GenrePresenter extends Presenter - implements GenreContract.Presenter { - @NonNull - private GenreContract.GenreView view; - - public GenrePresenter( - @NonNull GenreContract.GenreView view) { - this.view = view; - } - - @Override - public void subscribe() { - loadGenre(); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - @Override - public void loadGenre() { - disposable.add(repository.getAllGenres() - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(this::showList, - throwable -> view.showEmptyView(), - () -> view.completed())); - } - - private void showList(@NonNull ArrayList genres) { - if (genres.isEmpty()) { - view.showEmptyView(); - } else { - view.showData(genres); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.kt new file mode 100644 index 00000000..4a16b54c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/GenrePresenter.kt @@ -0,0 +1,40 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Genre +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.GenreContract +import java.util.* + +/** + * @author Hemanth S (h4h13). + */ + +class GenrePresenter( + private val view: GenreContract.GenreView) : Presenter(), GenreContract.Presenter { + + override fun subscribe() { + loadGenre() + } + + override fun unsubscribe() { + disposable.clear() + } + + override fun loadGenre() { + disposable.add(repository.allGenres + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showList(it) }, + { view.showEmptyView() }, + { view.completed() })) + } + + private fun showList(genres: ArrayList) { + if (genres.isEmpty()) { + view.showEmptyView() + } else { + view.showData(genres) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.java deleted file mode 100644 index 3d6f435c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.java +++ /dev/null @@ -1,126 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.HomeContract; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class HomePresenter extends Presenter implements HomeContract.HomePresenter { - - @NonNull - private HomeContract.HomeView view; - - public HomePresenter(@NonNull HomeContract.HomeView view) { - this.view = view; - } - - @Override - public void subscribe() { - - loadRecentAlbums(); - loadRecentArtists(); - loadTopAlbums(); - loadTopArtists(); - loadSuggestions(); - - if (PreferenceUtil.getInstance().isGenreShown()) loadGenres(); - - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - public void loadPlaylists() { - disposable.add(repository.getAllPlaylists() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .subscribe(playlist -> { - if (!playlist.isEmpty()) { - view.playlists(playlist); - } - }, - throwable -> view.showEmptyView(), () -> view.completed())); - } - - @Override - public void loadRecentAlbums() { - disposable.add(repository.getRecentAlbums() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(artists -> { - if (!artists.isEmpty()) { - view.recentAlbum(artists); - } - }, - throwable -> view.showEmptyView(), () -> view.completed())); - } - - @Override - public void loadTopAlbums() { - disposable.add(repository.getTopAlbums() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(artists -> { - if (!artists.isEmpty()) { - view.topAlbums(artists); - } - }, - throwable -> view.showEmptyView(), () -> view.completed())); - } - - @Override - public void loadRecentArtists() { - disposable.add(repository.getRecentArtists() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(artists -> { - if (!artists.isEmpty()) { - view.recentArtist(artists); - } - }, - throwable -> view.showEmptyView(), () -> view.completed())); - } - - @Override - public void loadTopArtists() { - disposable.add(repository.getTopArtists() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(artists -> { - if (!artists.isEmpty()) { - view.topArtists(artists); - } - }, - throwable -> view.showEmptyView(), () -> view.completed())); - - } - - @Override - public void loadSuggestions() { - disposable.add(repository.getSuggestionSongs() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(songs -> view.suggestions(songs), throwable -> view.showEmptyView(), () -> view.completed())); - } - - @Override - public void loadGenres() { - disposable.add(repository.getAllGenres() - .observeOn(schedulerProvider.ui()) - .subscribeOn(schedulerProvider.io()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(genres -> { - if (!genres.isEmpty()) { - view.geners(genres); - } - }, - throwable -> view.showEmptyView(), () -> view.completed())); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.kt new file mode 100644 index 00000000..858acc00 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/HomePresenter.kt @@ -0,0 +1,105 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.HomeContract +import code.name.monkey.retromusic.util.PreferenceUtil + +class HomePresenter(private val view: HomeContract.HomeView) : Presenter(), HomeContract.HomePresenter { + + override fun subscribe() { + + loadRecentAlbums() + loadRecentArtists() + loadTopAlbums() + loadTopArtists() + loadSuggestions() + + if (PreferenceUtil.getInstance().isGenreShown) loadGenres() + + } + + override fun unsubscribe() { + disposable.clear() + } + + fun loadPlaylists() { + disposable.add(repository.allPlaylists + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .subscribe({ playlist -> + if (!playlist.isEmpty()) { + view.playlists(playlist) + } + }, { view.showEmptyView() }, { view.completed() })) + } + + override fun loadRecentAlbums() { + disposable.add(repository.recentAlbums + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .doOnSubscribe { view.loading() } + .subscribe({ artists -> + if (!artists.isEmpty()) { + view.recentAlbum(artists) + } + }, { view.showEmptyView() }, { view.completed() })) + } + + override fun loadTopAlbums() { + disposable.add(repository.topAlbums + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .doOnSubscribe { view.loading() } + .subscribe({ artists -> + if (!artists.isEmpty()) { + view.topAlbums(artists) + } + }, { view.showEmptyView() }, { view.completed() })) + } + + override fun loadRecentArtists() { + disposable.add(repository.recentArtists + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .doOnSubscribe { view.loading() } + .subscribe({ artists -> + if (!artists.isEmpty()) { + view.recentArtist(artists) + } + }, { view.showEmptyView() }, { view.completed() })) + } + + override fun loadTopArtists() { + disposable.add(repository.topArtists + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .doOnSubscribe { view.loading() } + .subscribe({ artists -> + if (!artists.isEmpty()) { + view.topArtists(artists) + } + }, { view.showEmptyView() }, { view.completed() })) + + } + + override fun loadSuggestions() { + disposable.add(repository.suggestionSongs + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .doOnSubscribe { view.loading() } + .subscribe({ songs -> view.suggestions(songs) }, { view.showEmptyView() }, { view.completed() })) + } + + override fun loadGenres() { + disposable.add(repository.allGenres + .observeOn(schedulerProvider.ui()) + .subscribeOn(schedulerProvider.io()) + .doOnSubscribe { view.loading() } + .subscribe({ genres -> + if (!genres.isEmpty()) { + view.geners(genres) + } + }, + { view.showEmptyView() }, { view.completed() })) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.java deleted file mode 100644 index 3061072b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.java +++ /dev/null @@ -1,54 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.PlaylistContract; - - -/** - * Created by hemanths on 19/08/17. - */ - -public class PlaylistPresenter extends Presenter - implements PlaylistContract.Presenter { - @NonNull - private PlaylistContract.PlaylistView mView; - - public PlaylistPresenter(@NonNull PlaylistContract.PlaylistView view) { - - mView = view; - } - - @Override - public void subscribe() { - loadPlaylists(); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - @Override - public void loadPlaylists() { - disposable.add(repository.getAllPlaylists() - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> mView.loading()) - .subscribe(this::showList, - throwable -> mView.showEmptyView(), - () -> mView.completed())); - } - - private void showList(@NonNull ArrayList songs) { - if (songs.isEmpty()) { - mView.showEmptyView(); - } else { - mView.showData(songs); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.kt new file mode 100644 index 00000000..652dc4e0 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistPresenter.kt @@ -0,0 +1,40 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.PlaylistContract +import java.util.* + + +/** + * Created by hemanths on 19/08/17. + */ + +class PlaylistPresenter(private val view: PlaylistContract.PlaylistView) : Presenter(), PlaylistContract.Presenter { + + override fun subscribe() { + loadPlaylists() + } + + override fun unsubscribe() { + disposable.clear() + } + + override fun loadPlaylists() { + disposable.add(repository.allPlaylists + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showList(it) }, + { view.showEmptyView() }, + { view.completed() })) + } + + private fun showList(songs: ArrayList) { + if (songs.isEmpty()) { + view.showEmptyView() + } else { + view.showData(songs) + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.java deleted file mode 100644 index 44d20c3a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.java +++ /dev/null @@ -1,48 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import code.name.monkey.retromusic.model.Playlist; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.PlaylistSongsContract; - -/** - * Created by hemanths on 20/08/17. - */ - -public class PlaylistSongsPresenter extends Presenter - implements PlaylistSongsContract.Presenter { - @NonNull - private PlaylistSongsContract.PlaylistSongsView mView; - @NonNull - private Playlist mPlaylist; - - public PlaylistSongsPresenter(@NonNull PlaylistSongsContract.PlaylistSongsView view, - @NonNull Playlist playlist) { - - mView = view; - mPlaylist = playlist; - } - - - @Override - public void subscribe() { - loadSongs(mPlaylist); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - @Override - public void loadSongs(Playlist playlist) { - disposable.add(repository.getPlaylistSongs(playlist) - .subscribeOn(schedulerProvider.io()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> mView.loading()) - .subscribe(songs -> mView.showData(songs), - throwable -> mView.showEmptyView(), - () -> mView.completed())); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.kt new file mode 100644 index 00000000..20329f6e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/PlaylistSongsPresenter.kt @@ -0,0 +1,32 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Playlist +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.PlaylistSongsContract + +/** + * Created by hemanths on 20/08/17. + */ + +class PlaylistSongsPresenter(private val view: PlaylistSongsContract.PlaylistSongsView, + private val mPlaylist: Playlist) : Presenter(), PlaylistSongsContract.Presenter { + + + override fun subscribe() { + loadSongs(mPlaylist) + } + + override fun unsubscribe() { + disposable.clear() + } + + override fun loadSongs(playlist: Playlist) { + disposable.add(repository.getPlaylistSongs(playlist) + .subscribeOn(schedulerProvider.io()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ songs -> view.showData(songs) }, + { view.showEmptyView() }, + { view.completed() })) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.java deleted file mode 100644 index 2d4dbdb0..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.java +++ /dev/null @@ -1,52 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; -import java.util.concurrent.TimeUnit; - -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.SearchContract; - -/** - * Created by hemanths on 20/08/17. - */ - -public class SearchPresenter extends Presenter implements SearchContract.SearchPresenter { - @NonNull - private SearchContract.SearchView mView; - - public SearchPresenter(@NonNull SearchContract.SearchView view) { - mView = view; - } - - @Override - public void subscribe() { - search(""); - } - - @Override - public void unsubscribe() { - disposable.clear(); - } - - private void showList(@NonNull ArrayList albums) { - if (albums.isEmpty()) { - mView.showEmptyView(); - } else { - mView.showData(albums); - } - } - - @Override - public void search(String query) { - disposable.add(repository.search(query) - .debounce(500, TimeUnit.MILLISECONDS) - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> mView.loading()) - .subscribe(this::showList, - throwable -> mView.showEmptyView(), - () -> mView.completed())); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.kt new file mode 100644 index 00000000..064d858c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SearchPresenter.kt @@ -0,0 +1,40 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.SearchContract +import java.util.* +import java.util.concurrent.TimeUnit + +/** + * Created by hemanths on 20/08/17. + */ + +class SearchPresenter(private val view: SearchContract.SearchView) : Presenter(), SearchContract.SearchPresenter { + + override fun subscribe() { + search("") + } + + override fun unsubscribe() { + disposable.clear() + } + + private fun showList(albums: ArrayList) { + if (albums.isEmpty()) { + view.showEmptyView() + } else { + view.showData(albums) + } + } + + override fun search(query: String) { + disposable.add(repository.search(query) + .debounce(500, TimeUnit.MILLISECONDS) + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showList(it) }, + { view.showEmptyView() }, + { view.completed() })) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.java b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.java deleted file mode 100644 index 13aed8fe..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.java +++ /dev/null @@ -1,53 +0,0 @@ -package code.name.monkey.retromusic.mvp.presenter; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.mvp.Presenter; -import code.name.monkey.retromusic.mvp.contract.SongContract; - -/** - * Created by hemanths on 10/08/17. - */ - -public class SongPresenter extends Presenter implements SongContract.Presenter { - - @NonNull - private SongContract.SongView view; - - - public SongPresenter(@NonNull SongContract.SongView view) { - this.view = view; - } - - @Override - public void loadSongs() { - disposable.add(repository.getAllSongs() - .subscribeOn(schedulerProvider.computation()) - .observeOn(schedulerProvider.ui()) - .doOnSubscribe(disposable1 -> view.loading()) - .subscribe(this::showList, - throwable -> view.showEmptyView(), - () -> view.completed())); - } - - @Override - public void subscribe() { - loadSongs(); - } - - private void showList(@NonNull ArrayList songs) { - if (songs.isEmpty()) { - view.showEmptyView(); - } else { - view.showData(songs); - } - } - - @Override - public void unsubscribe() { - disposable.clear(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.kt b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.kt new file mode 100644 index 00000000..3aaa6d47 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/mvp/presenter/SongPresenter.kt @@ -0,0 +1,39 @@ +package code.name.monkey.retromusic.mvp.presenter + +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.mvp.Presenter +import code.name.monkey.retromusic.mvp.contract.SongContract +import java.util.* + +/** + * Created by hemanths on 10/08/17. + */ + +class SongPresenter(private val view: SongContract.SongView) : Presenter(), SongContract.Presenter { + + override fun loadSongs() { + disposable.add(repository.allSongs + .subscribeOn(schedulerProvider.computation()) + .observeOn(schedulerProvider.ui()) + .doOnSubscribe { view.loading() } + .subscribe({ this.showList(it) }, + { view.showEmptyView() }, + { view.completed() })) + } + + override fun subscribe() { + loadSongs() + } + + private fun showList(songs: ArrayList) { + if (songs.isEmpty()) { + view.showEmptyView() + } else { + view.showData(songs) + } + } + + override fun unsubscribe() { + disposable.clear() + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.java b/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.java deleted file mode 100644 index b4720730..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.java +++ /dev/null @@ -1,25 +0,0 @@ -package code.name.monkey.retromusic.preferences; - -import android.content.Context; -import android.util.AttributeSet; - -import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEDialogPreference; - - -public class AlbumCoverStylePreference extends ATEDialogPreference { - public AlbumCoverStylePreference(Context context) { - super(context); - } - - public AlbumCoverStylePreference(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public AlbumCoverStylePreference(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - public AlbumCoverStylePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.kt b/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.kt new file mode 100644 index 00000000..a6e1cc86 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreference.kt @@ -0,0 +1,17 @@ +package code.name.monkey.retromusic.preferences + +import android.content.Context +import android.util.AttributeSet + +import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEDialogPreference + + +class AlbumCoverStylePreference : ATEDialogPreference { + constructor(context: Context) : super(context) + + constructor(context: Context, attrs: AttributeSet) : super(context, attrs) + + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) + + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.java b/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.java deleted file mode 100644 index 00ba6286..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.java +++ /dev/null @@ -1,137 +0,0 @@ -package code.name.monkey.retromusic.preferences; - -import android.annotation.SuppressLint; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -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.ui.fragments.AlbumCoverStyle; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.ViewUtil; - - -public class AlbumCoverStylePreferenceDialog extends DialogFragment implements - ViewPager.OnPageChangeListener, MaterialDialog.SingleButtonCallback { - public static final String TAG = AlbumCoverStylePreferenceDialog.class.getSimpleName(); - - private DialogAction whichButtonClicked; - private int viewPagerPosition; - - public static AlbumCoverStylePreferenceDialog newInstance() { - return new AlbumCoverStylePreferenceDialog(); - } - - @NonNull - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - @SuppressLint("InflateParams") View view = LayoutInflater.from(getActivity()).inflate(R.layout.preference_dialog_now_playing_screen, null); - ViewPager viewPager = view.findViewById(R.id.now_playing_screen_view_pager); - viewPager.setAdapter(new AlbumCoverStyleAdapter(getActivity())); - viewPager.addOnPageChangeListener(this); - viewPager.setPageMargin((int) ViewUtil.convertDpToPixel(32, getResources())); - viewPager.setCurrentItem(PreferenceUtil.getInstance().getAlbumCoverStyle().ordinal()); - - return new MaterialDialog.Builder(getActivity()) - .title(R.string.pref_title_album_cover_style) - .positiveText(android.R.string.ok) - .negativeText(android.R.string.cancel) - .onAny(this) - .customView(view, false) - .build(); - } - - @Override - public void onClick(@NonNull MaterialDialog dialog, - @NonNull DialogAction which) { - whichButtonClicked = which; - } - - @SuppressWarnings("ConstantConditions") - @Override - public void onDismiss(DialogInterface dialog) { - super.onDismiss(dialog); - if (whichButtonClicked == DialogAction.POSITIVE) { - AlbumCoverStyle nowPlayingScreen = AlbumCoverStyle.values()[viewPagerPosition]; - PreferenceUtil.getInstance().setAlbumCoverStyle(nowPlayingScreen); - } - } - - - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - - } - - @Override - public void onPageSelected(int position) { - this.viewPagerPosition = position; - } - - @Override - public void onPageScrollStateChanged(int state) { - - } - - private static class AlbumCoverStyleAdapter extends PagerAdapter { - - private Context context; - - AlbumCoverStyleAdapter(Context context) { - this.context = context; - } - - @NonNull - @Override - public Object instantiateItem(@NonNull ViewGroup collection, int position) { - AlbumCoverStyle albumCoverStyle = AlbumCoverStyle.values()[position]; - - LayoutInflater inflater = LayoutInflater.from(context); - ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.preference_now_playing_screen_item, collection, false); - collection.addView(layout); - - ImageView image = layout.findViewById(R.id.image); - TextView title = layout.findViewById(R.id.title); - Glide.with(context).load(albumCoverStyle.drawableResId).into(image); - title.setText(albumCoverStyle.titleRes); - - return layout; - } - - @Override - public void destroyItem(@NonNull ViewGroup collection, - int position, - @NonNull Object view) { - collection.removeView((View) view); - } - - @Override - public int getCount() { - return AlbumCoverStyle.values().length; - } - - @Override - public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { - return view == object; - } - - @Override - public CharSequence getPageTitle(int position) { - return context.getString(AlbumCoverStyle.values()[position].titleRes); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.kt b/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.kt new file mode 100644 index 00000000..ec2aa7a4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/preferences/AlbumCoverStylePreferenceDialog.kt @@ -0,0 +1,116 @@ +package code.name.monkey.retromusic.preferences + +import android.annotation.SuppressLint +import android.app.Dialog +import android.content.Context +import android.content.DialogInterface +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +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.ui.fragments.AlbumCoverStyle +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.ViewUtil +import com.afollestad.materialdialogs.DialogAction +import com.afollestad.materialdialogs.MaterialDialog +import com.bumptech.glide.Glide + + +class AlbumCoverStylePreferenceDialog : DialogFragment(), ViewPager.OnPageChangeListener, MaterialDialog.SingleButtonCallback { + + private var whichButtonClicked: DialogAction? = null + private var viewPagerPosition: Int = 0 + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + @SuppressLint("InflateParams") val view = LayoutInflater.from(activity).inflate(R.layout.preference_dialog_now_playing_screen, null) + val viewPager = view.findViewById(R.id.now_playing_screen_view_pager) + viewPager.adapter = AlbumCoverStyleAdapter(activity!!) + viewPager.addOnPageChangeListener(this) + viewPager.pageMargin = ViewUtil.convertDpToPixel(32f, resources).toInt() + viewPager.currentItem = PreferenceUtil.getInstance().albumCoverStyle.ordinal + + return MaterialDialog.Builder(activity!!) + .title(R.string.pref_title_album_cover_style) + .positiveText(android.R.string.ok) + .negativeText(android.R.string.cancel) + .onAny(this) + .customView(view, false) + .build() + } + + override fun onClick(dialog: MaterialDialog, + which: DialogAction) { + whichButtonClicked = which + } + + override fun onDismiss(dialog: DialogInterface?) { + super.onDismiss(dialog) + if (whichButtonClicked == DialogAction.POSITIVE) { + val nowPlayingScreen = AlbumCoverStyle.values()[viewPagerPosition] + PreferenceUtil.getInstance().albumCoverStyle = nowPlayingScreen + } + } + + + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { + + } + + override fun onPageSelected(position: Int) { + this.viewPagerPosition = position + } + + override fun onPageScrollStateChanged(state: Int) { + + } + + private class AlbumCoverStyleAdapter internal constructor(private val context: Context) : PagerAdapter() { + + override fun instantiateItem(collection: ViewGroup, position: Int): Any { + val albumCoverStyle = AlbumCoverStyle.values()[position] + + val inflater = LayoutInflater.from(context) + val layout = inflater.inflate(R.layout.preference_now_playing_screen_item, collection, false) as ViewGroup + collection.addView(layout) + + val image = layout.findViewById(R.id.image) + val title = layout.findViewById(R.id.title) + Glide.with(context).load(albumCoverStyle.drawableResId).into(image) + title.setText(albumCoverStyle.titleRes) + + return layout + } + + override fun destroyItem(collection: ViewGroup, + position: Int, + view: Any) { + collection.removeView(view as View) + } + + override fun getCount(): Int { + return AlbumCoverStyle.values().size + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean { + return view === `object` + } + + override fun getPageTitle(position: Int): CharSequence? { + return context.getString(AlbumCoverStyle.values()[position].titleRes) + } + } + + companion object { + val TAG: String = AlbumCoverStylePreferenceDialog::class.java.simpleName + + fun newInstance(): AlbumCoverStylePreferenceDialog { + return AlbumCoverStylePreferenceDialog() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.java b/app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.java deleted file mode 100644 index cc6e3e69..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.java +++ /dev/null @@ -1,25 +0,0 @@ -package code.name.monkey.retromusic.preferences; - -import android.content.Context; -import android.util.AttributeSet; - -import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEDialogPreference; - - -public class BlacklistPreference extends ATEDialogPreference { - public BlacklistPreference(Context context) { - super(context); - } - - public BlacklistPreference(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public BlacklistPreference(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - public BlacklistPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.kt b/app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.kt new file mode 100644 index 00000000..cea074c8 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/preferences/BlacklistPreference.kt @@ -0,0 +1,17 @@ +package code.name.monkey.retromusic.preferences + +import android.content.Context +import android.util.AttributeSet + +import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEDialogPreference + + +class BlacklistPreference : ATEDialogPreference { + constructor(context: Context) : super(context) + + constructor(context: Context, attrs: AttributeSet) : super(context, attrs) + + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) + + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.java b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.java deleted file mode 100644 index a19e22f9..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.java +++ /dev/null @@ -1,25 +0,0 @@ -package code.name.monkey.retromusic.preferences; - -import android.content.Context; -import android.util.AttributeSet; - -import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEDialogPreference; - - -public class NowPlayingScreenPreference extends ATEDialogPreference { - public NowPlayingScreenPreference(Context context) { - super(context); - } - - public NowPlayingScreenPreference(Context context, AttributeSet attrs) { - super(context, attrs); - } - - public NowPlayingScreenPreference(Context context, AttributeSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); - } - - public NowPlayingScreenPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.kt b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.kt new file mode 100644 index 00000000..ee1f85a2 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreference.kt @@ -0,0 +1,17 @@ +package code.name.monkey.retromusic.preferences + +import android.content.Context +import android.util.AttributeSet + +import code.name.monkey.appthemehelper.common.prefs.supportv7.ATEDialogPreference + + +class NowPlayingScreenPreference : ATEDialogPreference { + constructor(context: Context) : super(context) {} + + constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} + + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {} + + constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {} +} \ No newline at end of file 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 deleted file mode 100644 index 59d7fde5..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.java +++ /dev/null @@ -1,166 +0,0 @@ -package code.name.monkey.retromusic.preferences; - -import android.annotation.SuppressLint; -import android.app.Dialog; -import android.content.Context; -import android.content.DialogInterface; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -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.App; -import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.ViewUtil; - - -public class NowPlayingScreenPreferenceDialog extends DialogFragment implements - ViewPager.OnPageChangeListener, MaterialDialog.SingleButtonCallback { - public static final String TAG = NowPlayingScreenPreferenceDialog.class.getSimpleName(); - - private DialogAction whichButtonClicked; - private int viewPagerPosition; - - public static NowPlayingScreenPreferenceDialog newInstance() { - return new NowPlayingScreenPreferenceDialog(); - } - - @NonNull - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - @SuppressLint("InflateParams") View view = LayoutInflater.from(getActivity()) - .inflate(R.layout.preference_dialog_now_playing_screen, null); - ViewPager viewPager = view.findViewById(R.id.now_playing_screen_view_pager); - viewPager.setAdapter(new NowPlayingScreenAdapter(getActivity())); - viewPager.addOnPageChangeListener(this); - viewPager.setPageMargin((int) ViewUtil.convertDpToPixel(32, getResources())); - viewPager.setCurrentItem(PreferenceUtil.getInstance().getNowPlayingScreen().ordinal()); - - return new MaterialDialog.Builder(getActivity()) - .title(R.string.pref_title_now_playing_screen_appearance) - .positiveText(android.R.string.ok) - .negativeText(android.R.string.cancel) - .onAny(this) - .customView(view, false) - .build(); - } - - @Override - public void onClick(@NonNull MaterialDialog dialog, - @NonNull DialogAction which) { - whichButtonClicked = which; - } - - @SuppressWarnings("ConstantConditions") - @Override - public void onDismiss(DialogInterface dialog) { - super.onDismiss(dialog); - if (whichButtonClicked == DialogAction.POSITIVE) { - NowPlayingScreen nowPlayingScreen = NowPlayingScreen.values()[viewPagerPosition]; - if (isNowPlayingThemes(nowPlayingScreen)) { - String result = getString(nowPlayingScreen.titleRes) + " theme is Pro version feature."; - Toast.makeText(getContext(), result, Toast.LENGTH_SHORT).show(); - NavigationUtil.goToProVersion(getActivity()); - } else { - PreferenceUtil.getInstance().setNowPlayingScreen(nowPlayingScreen); - } - } - } - - private boolean isNowPlayingThemes(NowPlayingScreen nowPlayingScreen) { - - /*if (nowPlayingScreen.equals(NowPlayingScreen.BLUR_CARD)) { - PreferenceUtil.getInstance().resetCarouselEffect(); - PreferenceUtil.getInstance().resetCircularAlbumArt(); - }*/ - - /* return (nowPlayingScreen.equals(NowPlayingScreen.FULL) || - nowPlayingScreen.equals(NowPlayingScreen.CARD) || - nowPlayingScreen.equals(NowPlayingScreen.PLAIN) || - nowPlayingScreen.equals(NowPlayingScreen.BLUR) || - nowPlayingScreen.equals(NowPlayingScreen.COLOR) || - nowPlayingScreen.equals(NowPlayingScreen.SIMPLE) || - nowPlayingScreen.equals(NowPlayingScreen.TINY) || - nowPlayingScreen.equals(NowPlayingScreen.BLUR_CARD)|| - nowPlayingScreen.equals(NowPlayingScreen.ADAPTIVE)) - && !App.Companion.isProVersion();*/ - return !App.Companion.isProVersion(); - } - - @Override - public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - - } - - @Override - public void onPageSelected(int position) { - this.viewPagerPosition = position; - } - - @Override - public void onPageScrollStateChanged(int state) { - - } - - private static class NowPlayingScreenAdapter extends PagerAdapter { - - private Context context; - - NowPlayingScreenAdapter(Context context) { - this.context = context; - } - - @NonNull - @Override - public Object instantiateItem(@NonNull ViewGroup collection, int position) { - NowPlayingScreen nowPlayingScreen = NowPlayingScreen.values()[position]; - - LayoutInflater inflater = LayoutInflater.from(context); - ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.preference_now_playing_screen_item, collection, false); - collection.addView(layout); - - ImageView image = layout.findViewById(R.id.image); - TextView title = layout.findViewById(R.id.title); - Glide.with(context).load(nowPlayingScreen.drawableResId).into(image); - title.setText(nowPlayingScreen.titleRes); - - return layout; - } - - @Override - public void destroyItem(@NonNull ViewGroup collection, - int position, - @NonNull Object view) { - collection.removeView((View) view); - } - - @Override - public int getCount() { - return NowPlayingScreen.values().length; - } - - @Override - public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { - return view == object; - } - - @Override - public CharSequence getPageTitle(int position) { - return context.getString(NowPlayingScreen.values()[position].titleRes); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.kt b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.kt new file mode 100644 index 00000000..b0373fe1 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/preferences/NowPlayingScreenPreferenceDialog.kt @@ -0,0 +1,144 @@ +package code.name.monkey.retromusic.preferences + +import android.annotation.SuppressLint +import android.app.Dialog +import android.content.Context +import android.content.DialogInterface +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import android.widget.Toast +import androidx.fragment.app.DialogFragment +import androidx.viewpager.widget.PagerAdapter +import androidx.viewpager.widget.ViewPager +import code.name.monkey.retromusic.App +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.fragments.NowPlayingScreen +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.ViewUtil +import com.afollestad.materialdialogs.DialogAction +import com.afollestad.materialdialogs.MaterialDialog +import com.bumptech.glide.Glide + + +class NowPlayingScreenPreferenceDialog : DialogFragment(), ViewPager.OnPageChangeListener, MaterialDialog.SingleButtonCallback { + + private var whichButtonClicked: DialogAction? = null + private var viewPagerPosition: Int = 0 + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + @SuppressLint("InflateParams") val view = LayoutInflater.from(activity) + .inflate(R.layout.preference_dialog_now_playing_screen, null) + val viewPager = view.findViewById(R.id.now_playing_screen_view_pager) + viewPager.adapter = NowPlayingScreenAdapter(activity!!) + viewPager.addOnPageChangeListener(this) + viewPager.pageMargin = ViewUtil.convertDpToPixel(32f, resources).toInt() + viewPager.currentItem = PreferenceUtil.getInstance().nowPlayingScreen.ordinal + + return MaterialDialog.Builder(activity!!) + .title(R.string.pref_title_now_playing_screen_appearance) + .positiveText(android.R.string.ok) + .negativeText(android.R.string.cancel) + .onAny(this) + .customView(view, false) + .build() + } + + override fun onClick(dialog: MaterialDialog, + which: DialogAction) { + whichButtonClicked = which + } + + override fun onDismiss(dialog: DialogInterface?) { + super.onDismiss(dialog) + if (whichButtonClicked == DialogAction.POSITIVE) { + val nowPlayingScreen = NowPlayingScreen.values()[viewPagerPosition] + if (isNowPlayingThemes(nowPlayingScreen)) { + val result = getString(nowPlayingScreen.titleRes) + " theme is Pro version feature." + Toast.makeText(context, result, Toast.LENGTH_SHORT).show() + NavigationUtil.goToProVersion(activity!!) + } else { + PreferenceUtil.getInstance().nowPlayingScreen = nowPlayingScreen + } + } + } + + private fun isNowPlayingThemes(nowPlayingScreen: NowPlayingScreen): Boolean { + + if (nowPlayingScreen == NowPlayingScreen.BLUR_CARD) { + PreferenceUtil.getInstance().resetCarouselEffect() + PreferenceUtil.getInstance().resetCircularAlbumArt() + } + + return (nowPlayingScreen == NowPlayingScreen.FULL || + nowPlayingScreen == NowPlayingScreen.CARD || + nowPlayingScreen == NowPlayingScreen.PLAIN || + nowPlayingScreen == NowPlayingScreen.BLUR || + nowPlayingScreen == NowPlayingScreen.COLOR || + nowPlayingScreen == NowPlayingScreen.SIMPLE || + nowPlayingScreen == NowPlayingScreen.BLUR_CARD || + nowPlayingScreen == NowPlayingScreen.ADAPTIVE) + && !App.isProVersion + + } + + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { + + } + + override fun onPageSelected(position: Int) { + this.viewPagerPosition = position + } + + override fun onPageScrollStateChanged(state: Int) { + + } + + private class NowPlayingScreenAdapter internal constructor(private val context: Context) : PagerAdapter() { + + override fun instantiateItem(collection: ViewGroup, position: Int): Any { + val nowPlayingScreen = NowPlayingScreen.values()[position] + + val inflater = LayoutInflater.from(context) + val layout = inflater.inflate(R.layout.preference_now_playing_screen_item, collection, false) as ViewGroup + collection.addView(layout) + + val image = layout.findViewById(R.id.image) + val title = layout.findViewById(R.id.title) + Glide.with(context).load(nowPlayingScreen.drawableResId).into(image) + title.setText(nowPlayingScreen.titleRes) + + return layout + } + + override fun destroyItem(collection: ViewGroup, + position: Int, + view: Any) { + collection.removeView(view as View) + } + + override fun getCount(): Int { + return NowPlayingScreen.values().size + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean { + return view === `object` + } + + override fun getPageTitle(position: Int): CharSequence? { + return context.getString(NowPlayingScreen.values()[position].titleRes) + } + } + + companion object { + val TAG: String = NowPlayingScreenPreferenceDialog::class.java.simpleName + + fun newInstance(): NowPlayingScreenPreferenceDialog { + return NowPlayingScreenPreferenceDialog() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.java b/app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.java deleted file mode 100644 index 6d108550..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.java +++ /dev/null @@ -1,60 +0,0 @@ -package code.name.monkey.retromusic.providers.interfaces; - -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.AbsSmartPlaylist; -import io.reactivex.Observable; -import java.io.File; -import java.util.ArrayList; - -/** - * Created by hemanths on 11/08/17. - */ - -public interface Repository { - - Observable> getAllSongs(); - - Observable> getSuggestionSongs(); - - Observable getSong(int id); - - Observable> getAllAlbums(); - - Observable> getRecentAlbums(); - - Observable> getTopAlbums(); - - Observable getAlbum(int albumId); - - Observable> getAllArtists(); - - Observable> getRecentArtists(); - - Observable> getTopArtists(); - - - Observable getArtistById(long artistId); - - Observable> getAllPlaylists(); - - Observable> getFavoriteSongs(); - - Observable> search(String query); - - Observable> getPlaylistSongs(Playlist playlist); - - Observable> getHomeList(); - - Observable> getAllThings(); - - Observable> getAllGenres(); - - Observable> getGenre(int genreId); - - Observable downloadLrcFile(final String title, final String artist, final long duration); - -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.kt b/app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.kt new file mode 100644 index 00000000..f76a7ca0 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/providers/interfaces/Repository.kt @@ -0,0 +1,60 @@ +package code.name.monkey.retromusic.providers.interfaces + +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.AbsSmartPlaylist +import io.reactivex.Observable +import java.io.File +import java.util.ArrayList + +/** + * Created by hemanths on 11/08/17. + */ + +interface Repository { + + val allSongs: Observable> + + val suggestionSongs: Observable> + + val allAlbums: Observable> + + val recentAlbums: Observable> + + val topAlbums: Observable> + + val allArtists: Observable> + + val recentArtists: Observable> + + val topArtists: Observable> + + val allPlaylists: Observable> + + val favoriteSongs: Observable> + + val homeList: Observable> + + val allThings: Observable> + + val allGenres: Observable> + + fun getSong(id: Int): Observable + + fun getAlbum(albumId: Int): Observable + + + fun getArtistById(artistId: Long): Observable + + fun search(query: String): Observable> + + fun getPlaylistSongs(playlist: Playlist): Observable> + + fun getGenre(genreId: Int): Observable> + + fun downloadLrcFile(title: String, artist: String, duration: Long): Observable + +} \ 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 index 39d4e0f0..9cc5fa2a 100644 --- a/app/src/main/java/code/name/monkey/retromusic/service/MusicService.java +++ b/app/src/main/java/code/name/monkey/retromusic/service/MusicService.java @@ -653,7 +653,7 @@ public class MusicService extends Service implements SharedPreferences.OnSharedP if (PreferenceUtil.getInstance().albumArtOnLockscreen()) { final Point screenSize = RetroUtil.getScreenSize(MusicService.this); - final BitmapRequestBuilder request = SongGlideRequest.Builder.from(Glide.with(MusicService.this), song) + final BitmapRequestBuilder request = SongGlideRequest.Builder.Companion.from(Glide.with(MusicService.this), song) .checkIgnoreMediaStore(MusicService.this) .asBitmap().build(); if (PreferenceUtil.getInstance().blurredAlbumArt()) { 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 deleted file mode 100644 index b8404c3c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/daydream/RetroMusicAlbums.kt +++ /dev/null @@ -1,161 +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 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/PlayingNotification.java b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.java deleted file mode 100644 index eb8eb89d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.java +++ /dev/null @@ -1,82 +0,0 @@ -package code.name.monkey.retromusic.service.notification; - - -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.os.Build; - -import androidx.annotation.RequiresApi; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.service.MusicService; - -import static android.content.Context.NOTIFICATION_SERVICE; - - -public abstract class PlayingNotification { - - protected static final float NOTIFICATION_CONTROLS_SIZE_MULTIPLIER = 1.0f; - static final String NOTIFICATION_CHANNEL_ID = "playing_notification"; - private static final int NOTIFICATION_ID = 1; - private static final int NOTIFY_MODE_FOREGROUND = 1; - private static final int NOTIFY_MODE_BACKGROUND = 0; - protected MusicService service; - boolean stopped; - private int notifyMode = NOTIFY_MODE_BACKGROUND; - private NotificationManager notificationManager; - - public synchronized void init(MusicService service) { - this.service = service; - notificationManager = (NotificationManager) service.getSystemService(NOTIFICATION_SERVICE); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - createNotificationChannel(); - } - } - - public abstract void update(); - - public synchronized void stop() { - stopped = true; - service.stopForeground(true); - notificationManager.cancel(NOTIFICATION_ID); - } - - void updateNotifyModeAndPostNotification(Notification notification) { - int newNotifyMode; - if (service.isPlaying()) { - newNotifyMode = NOTIFY_MODE_FOREGROUND; - } else { - newNotifyMode = NOTIFY_MODE_BACKGROUND; - } - - if (notifyMode != newNotifyMode && newNotifyMode == NOTIFY_MODE_BACKGROUND) { - service.stopForeground(false); - } - - if (newNotifyMode == NOTIFY_MODE_FOREGROUND) { - service.startForeground(NOTIFICATION_ID, notification); - } else if (newNotifyMode == NOTIFY_MODE_BACKGROUND) { - notificationManager.notify(NOTIFICATION_ID, notification); - } - - notifyMode = newNotifyMode; - } - - @RequiresApi(26) - private void createNotificationChannel() { - NotificationChannel notificationChannel = notificationManager - .getNotificationChannel(NOTIFICATION_CHANNEL_ID); - if (notificationChannel == null) { - notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, - service.getString(R.string.playing_notification_name), - NotificationManager.IMPORTANCE_LOW); - notificationChannel - .setDescription(service.getString(R.string.playing_notification_description)); - notificationChannel.enableLights(false); - notificationChannel.enableVibration(false); - notificationChannel.setShowBadge(false); - - notificationManager.createNotificationChannel(notificationChannel); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.kt b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.kt new file mode 100644 index 00000000..68e2af27 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotification.kt @@ -0,0 +1,83 @@ +package code.name.monkey.retromusic.service.notification + + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context.NOTIFICATION_SERVICE +import android.os.Build +import androidx.annotation.RequiresApi +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.service.MusicService + + +abstract class PlayingNotification { + protected lateinit var service: MusicService + protected var stopped: Boolean = false + private var notifyMode = NOTIFY_MODE_BACKGROUND + private var notificationManager: NotificationManager? = null + + + @Synchronized + fun init(service: MusicService) { + this.service = service + notificationManager = service.getSystemService(NOTIFICATION_SERVICE) as NotificationManager + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + createNotificationChannel() + } + } + + abstract fun update() + + @Synchronized + fun stop() { + stopped = true + service.stopForeground(true) + notificationManager!!.cancel(NOTIFICATION_ID) + } + + internal fun updateNotifyModeAndPostNotification(notification: Notification) { + val newNotifyMode: Int = if (service.isPlaying) { + NOTIFY_MODE_FOREGROUND + } else { + NOTIFY_MODE_BACKGROUND + } + + if (notifyMode != newNotifyMode && newNotifyMode == NOTIFY_MODE_BACKGROUND) { + service.stopForeground(false) + } + + if (newNotifyMode == NOTIFY_MODE_FOREGROUND) { + service.startForeground(NOTIFICATION_ID, notification) + } else if (newNotifyMode == NOTIFY_MODE_BACKGROUND) { + notificationManager!!.notify(NOTIFICATION_ID, notification) + } + + notifyMode = newNotifyMode + } + + @RequiresApi(26) + private fun createNotificationChannel() { + var notificationChannel: NotificationChannel? = notificationManager!! + .getNotificationChannel(NOTIFICATION_CHANNEL_ID) + if (notificationChannel == null) { + notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, + service.getString(R.string.playing_notification_name), + NotificationManager.IMPORTANCE_LOW) + notificationChannel.description = service.getString(R.string.playing_notification_description) + notificationChannel.enableLights(false) + notificationChannel.enableVibration(false) + notificationChannel.setShowBadge(false) + + notificationManager!!.createNotificationChannel(notificationChannel) + } + } + + companion object { + const val NOTIFICATION_CONTROLS_SIZE_MULTIPLIER = 1.0f + internal const val NOTIFICATION_CHANNEL_ID = "playing_notification" + private const val NOTIFICATION_ID = 1 + private const val NOTIFY_MODE_FOREGROUND = 1 + private const val NOTIFY_MODE_BACKGROUND = 0 + } +} \ No newline at end of file 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 deleted file mode 100644 index 8cffe5f2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.java +++ /dev/null @@ -1,225 +0,0 @@ -package code.name.monkey.retromusic.service.notification; - - -import android.app.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.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.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.MainActivity; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroColorUtil; -import code.name.monkey.retromusic.util.RetroUtil; - -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; - -public class PlayingNotificationImpl extends PlayingNotification { - - private Target target; - - - @Override - public synchronized void update() { - stopped = false; - - final Song song = service.getCurrentSong(); - - final boolean isPlaying = service.isPlaying(); - - final RemoteViews notificationLayout = new RemoteViews(service.getPackageName(), - R.layout.notification); - final RemoteViews notificationLayoutBig = new RemoteViews(service.getPackageName(), - R.layout.notification_big); - - 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.getTitle()); - notificationLayout.setTextViewText(R.id.text, song.getArtistName()); - } - - 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.getTitle()); - notificationLayoutBig.setTextViewText(R.id.text, song.getArtistName()); - notificationLayoutBig.setTextViewText(R.id.text2, song.getAlbumName()); - } - - linkButtons(notificationLayout, notificationLayoutBig); - - 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 PendingIntent deleteIntent = buildPendingIntent(service, ACTION_QUIT, null); - - final Notification notification = 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) - .setContent(notificationLayout) - .setCustomBigContentView(notificationLayoutBig) - .setOngoing(isPlaying) - .build(); - - 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) { - update(resource.getBitmap(), - PreferenceUtil.getInstance().isDominantColor() ? - RetroColorUtil.getDominantColor(resource.getBitmap(), Color.TRANSPARENT) : - RetroColorUtil.getColor(resource.getPalette(), Color.TRANSPARENT)); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - update(null, Color.WHITE); - } - - private void update(@Nullable Bitmap bitmap, int bgColor) { - if (bitmap != null) { - notificationLayout.setImageViewBitmap(R.id.image, bitmap); - notificationLayoutBig.setImageViewBitmap(R.id.image, bitmap); - } else { - notificationLayout.setImageViewResource(R.id.image, R.drawable.default_album_art); - notificationLayoutBig - .setImageViewResource(R.id.image, 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(notification); - } - - private void setBackgroundColor(int color) { - notificationLayout.setInt(R.id.root, "setBackgroundColor", color); - notificationLayoutBig.setInt(R.id.root, "setBackgroundColor", 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), - 1.5f); - Bitmap prev = createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, - primary), 1.5f); - Bitmap next = createBitmap( - RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, - primary), 1.5f); - Bitmap playPause = createBitmap(RetroUtil.getTintedVectorDrawable(service, - isPlaying ? R.drawable.ic_pause_white_24dp - : R.drawable.ic_play_arrow_white_24dp, primary), 1.5f); - - notificationLayout.setTextColor(R.id.title, primary); - notificationLayout.setTextColor(R.id.text, 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.text, secondary); - notificationLayoutBig.setTextColor(R.id.text2, 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); - - } - }); - } - }); - } - - private void linkButtons(final RemoteViews notificationLayout, - final RemoteViews notificationLayoutBig) { - 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); - notificationLayoutBig.setOnClickPendingIntent(R.id.action_prev, pendingIntent); - - // Play and pause - pendingIntent = buildPendingIntent(service, ACTION_TOGGLE_PAUSE, serviceName); - notificationLayout.setOnClickPendingIntent(R.id.action_play_pause, pendingIntent); - notificationLayoutBig.setOnClickPendingIntent(R.id.action_play_pause, pendingIntent); - - // Next track - pendingIntent = buildPendingIntent(service, ACTION_SKIP, serviceName); - notificationLayout.setOnClickPendingIntent(R.id.action_next, pendingIntent); - notificationLayoutBig.setOnClickPendingIntent(R.id.action_next, pendingIntent); - - // Close - pendingIntent = buildPendingIntent(service, ACTION_QUIT, serviceName); - notificationLayoutBig.setOnClickPendingIntent(R.id.action_quit, pendingIntent); - } - - 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); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.kt b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.kt new file mode 100644 index 00000000..92f1e333 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl.kt @@ -0,0 +1,219 @@ +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.text.TextUtils +import android.view.View +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.service.MusicService +import code.name.monkey.retromusic.ui.activities.MainActivity +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroColorUtil +import code.name.monkey.retromusic.util.RetroUtil +import code.name.monkey.retromusic.util.RetroUtil.createBitmap +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 + +class PlayingNotificationImpl : PlayingNotification() { + + private var target: Target? = null + + + @Synchronized + override fun update() { + stopped = false + + val song = service.currentSong + + val isPlaying = service.isPlaying + + val notificationLayout = RemoteViews(service.packageName, + R.layout.notification) + val notificationLayoutBig = RemoteViews(service.packageName, + R.layout.notification_big) + + if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName)) { + 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) + } + + if (TextUtils.isEmpty(song.title) && TextUtils.isEmpty(song.artistName) && TextUtils + .isEmpty(song.albumName)) { + 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) + } + + linkButtons(notificationLayout, notificationLayoutBig) + + 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 notification = 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) + .setContent(notificationLayout) + .setCustomBigContentView(notificationLayoutBig) + .setOngoing(isPlaying) + .build() + + val bigNotificationImageSize = service.resources + .getDimensionPixelSize(R.dimen.notification_big_image_size) + service.runOnUiThread { + 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) { + update(resource.bitmap, + if (PreferenceUtil.getInstance().isDominantColor) + RetroColorUtil.getDominantColor(resource.bitmap, Color.TRANSPARENT) + else + RetroColorUtil.getColor(resource.palette, Color.TRANSPARENT)) + } + + 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.image, bitmap) + notificationLayoutBig.setImageViewBitmap(R.id.image, bitmap) + } else { + notificationLayout.setImageViewResource(R.id.image, R.drawable.default_album_art) + notificationLayoutBig + .setImageViewResource(R.id.image, 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(notification) + } + + private fun setBackgroundColor(color: Int) { + notificationLayout.setInt(R.id.root, "setBackgroundColor", color) + notificationLayoutBig.setInt(R.id.root, "setBackgroundColor", 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)!!, + 1.5f) + val prev = createBitmap( + RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_previous_white_24dp, + primary)!!, 1.5f) + val next = createBitmap( + RetroUtil.getTintedVectorDrawable(service, R.drawable.ic_skip_next_white_24dp, + primary)!!, 1.5f) + val playPause = createBitmap(RetroUtil.getTintedVectorDrawable(service, + if (isPlaying) + R.drawable.ic_pause_white_24dp + else + R.drawable.ic_play_arrow_white_24dp, primary)!!, 1.5f) + + notificationLayout.setTextColor(R.id.title, primary) + notificationLayout.setTextColor(R.id.text, 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.text, secondary) + notificationLayoutBig.setTextColor(R.id.text2, 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) + + } + }) + } + } + + + private fun linkButtons(notificationLayout: RemoteViews, + notificationLayoutBig: 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) + notificationLayoutBig.setOnClickPendingIntent(R.id.action_prev, pendingIntent) + + // Play and pause + pendingIntent = buildPendingIntent(service, ACTION_TOGGLE_PAUSE, serviceName) + notificationLayout.setOnClickPendingIntent(R.id.action_play_pause, pendingIntent) + notificationLayoutBig.setOnClickPendingIntent(R.id.action_play_pause, pendingIntent) + + // Next track + pendingIntent = buildPendingIntent(service, ACTION_SKIP, serviceName) + notificationLayout.setOnClickPendingIntent(R.id.action_next, pendingIntent) + notificationLayoutBig.setOnClickPendingIntent(R.id.action_next, pendingIntent) + + // Close + pendingIntent = buildPendingIntent(service, ACTION_QUIT, serviceName) + notificationLayoutBig.setOnClickPendingIntent(R.id.action_quit, pendingIntent) + } + + private fun buildPendingIntent(context: Context, action: String, + serviceName: ComponentName?): PendingIntent { + val intent = Intent(action) + intent.component = serviceName + return PendingIntent.getService(context, 0, intent, 0) + } +} \ No newline at end of file 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 deleted file mode 100644 index 2efe0fbf..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.java +++ /dev/null @@ -1,143 +0,0 @@ -package code.name.monkey.retromusic.service.notification; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.os.Build; -import android.text.Html; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; - -import androidx.core.app.NotificationCompat; -import androidx.media.app.NotificationCompat.MediaStyle; -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.RetroColorUtil; - -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; - -public class PlayingNotificationImpl24 extends PlayingNotification { - - @Override - public synchronized void update() { - stopped = false; - - final Song song = service.getCurrentSong(); - final boolean isPlaying = service.isPlaying(); - - final int playButtonResId = isPlaying ? R.drawable.ic_pause_white_24dp : - R.drawable.ic_play_arrow_white_24dp; - - 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(ACTION_QUIT); - intent.setComponent(serviceName); - final PendingIntent deleteIntent = PendingIntent.getService(service, 0, intent, 0); - - final int bigNotificationImageSize = service.getResources() - .getDimensionPixelSize(R.dimen.notification_big_image_size); - service.runOnUiThread(() -> 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) { - update(resource.getBitmap(), - PreferenceUtil.getInstance().isDominantColor() ? - RetroColorUtil.getDominantColor(resource.getBitmap(), Color.TRANSPARENT) : - RetroColorUtil.getColor(resource.getPalette(), Color.TRANSPARENT)); - } - - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - update(null, Color.TRANSPARENT); - } - - void update(Bitmap bitmap, int color) { - if (bitmap == null) { - bitmap = BitmapFactory - .decodeResource(service.getResources(), R.drawable.default_album_art); - } - NotificationCompat.Action playPauseAction = new NotificationCompat.Action( - playButtonResId, - service.getString(R.string.action_play_pause), - retrievePlaybackAction(ACTION_TOGGLE_PAUSE)); - - NotificationCompat.Action closeAction = new NotificationCompat.Action( - R.drawable.ic_close_white_24dp, - service.getString(R.string.close_notification), - retrievePlaybackAction(ACTION_QUIT)); - - NotificationCompat.Action previousAction = new NotificationCompat.Action( - R.drawable.ic_skip_previous_white_24dp, - service.getString(R.string.action_previous), - retrievePlaybackAction(ACTION_REWIND)); - - NotificationCompat.Action nextAction = new NotificationCompat.Action( - R.drawable.ic_skip_next_white_24dp, - service.getString(R.string.action_next), - retrievePlaybackAction(ACTION_SKIP)); - - NotificationCompat.Builder builder = new NotificationCompat.Builder(service, - NOTIFICATION_CHANNEL_ID) - .setSmallIcon(R.drawable.ic_notification) - .setLargeIcon(bitmap) - .setContentIntent(clickIntent) - .setDeleteIntent(deleteIntent) - .setContentTitle(Html.fromHtml("" + song.getTitle() + "")) - .setContentText(song.getArtistName()) - .setSubText(Html.fromHtml("" + song.getAlbumName() + "")) - .setOngoing(isPlaying) - .setShowWhen(false) - .addAction(previousAction) - .addAction(playPauseAction) - .addAction(nextAction) - .addAction(closeAction); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - builder.setStyle(new MediaStyle() - .setMediaSession(service.getMediaSession().getSessionToken()) - .setShowActionsInCompactView(0, 1, 2, 3, 4)) - .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); - if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O && - PreferenceUtil.getInstance().coloredNotification()) { - builder.setColor(color); - } - } - - if (stopped) { - return; // notification has been stopped before loading was finished - } - updateNotifyModeAndPostNotification(builder.build()); - } - })); - } - - private PendingIntent retrievePlaybackAction(final String action) { - final ComponentName serviceName = new ComponentName(service, MusicService.class); - Intent intent = new Intent(action); - intent.setComponent(serviceName); - return PendingIntent.getService(service, 0, intent, 0); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.kt b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.kt new file mode 100644 index 00000000..9736d0d4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/service/notification/PlayingNotificationImpl24.kt @@ -0,0 +1,138 @@ +package code.name.monkey.retromusic.service.notification + +import android.app.PendingIntent +import android.content.ComponentName +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Color +import android.graphics.drawable.Drawable +import android.os.Build +import android.text.Html +import androidx.core.app.NotificationCompat +import androidx.media.app.NotificationCompat.MediaStyle +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.service.MusicService +import code.name.monkey.retromusic.ui.activities.MainActivity +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroColorUtil +import com.bumptech.glide.Glide +import com.bumptech.glide.request.animation.GlideAnimation +import com.bumptech.glide.request.target.SimpleTarget + +class PlayingNotificationImpl24 : PlayingNotification() { + + @Synchronized + override fun update() { + stopped = false + + val song = service.currentSong + val isPlaying = service.isPlaying + + val playButtonResId = if (isPlaying) + R.drawable.ic_pause_white_24dp + else + R.drawable.ic_play_arrow_white_24dp + + 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 serviceName = ComponentName(service, MusicService::class.java) + val intent = Intent(ACTION_QUIT) + intent.component = serviceName + val deleteIntent = PendingIntent.getService(service, 0, intent, 0) + + val bigNotificationImageSize = service.resources + .getDimensionPixelSize(R.dimen.notification_big_image_size) + service.runOnUiThread { + SongGlideRequest.Builder.from(Glide.with(service), song) + .checkIgnoreMediaStore(service) + .generatePalette(service).build() + .into(object : SimpleTarget(bigNotificationImageSize, bigNotificationImageSize) { + override fun onResourceReady(resource: BitmapPaletteWrapper, glideAnimation: GlideAnimation) { + update(resource.bitmap, when { + PreferenceUtil.getInstance().isDominantColor -> RetroColorUtil.getDominantColor(resource.bitmap, Color.TRANSPARENT) + else -> RetroColorUtil.getColor(resource.palette, Color.TRANSPARENT) + }) + } + + override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) { + update(null, Color.TRANSPARENT) + } + + fun update(bitmap: Bitmap?, color: Int) { + var bitmapFinal = bitmap + if (bitmapFinal == null) { + bitmapFinal = BitmapFactory.decodeResource(service.resources, R.drawable.default_album_art) + } + val playPauseAction = NotificationCompat.Action( + playButtonResId, + service.getString(R.string.action_play_pause), + retrievePlaybackAction(ACTION_TOGGLE_PAUSE)) + + val closeAction = NotificationCompat.Action( + R.drawable.ic_close_white_24dp, + service.getString(R.string.close_notification), + retrievePlaybackAction(ACTION_QUIT)) + + val previousAction = NotificationCompat.Action( + R.drawable.ic_skip_previous_white_24dp, + service.getString(R.string.action_previous), + retrievePlaybackAction(ACTION_REWIND)) + + val nextAction = NotificationCompat.Action( + R.drawable.ic_skip_next_white_24dp, + service.getString(R.string.action_next), + retrievePlaybackAction(ACTION_SKIP)) + + val builder = NotificationCompat.Builder(service, + PlayingNotification.NOTIFICATION_CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setLargeIcon(bitmapFinal) + .setContentIntent(clickIntent) + .setDeleteIntent(deleteIntent) + .setContentTitle(Html.fromHtml("" + song.title + "")) + .setContentText(song.artistName) + .setSubText(Html.fromHtml("" + song.albumName + "")) + .setOngoing(isPlaying) + .setShowWhen(false) + .addAction(previousAction) + .addAction(playPauseAction) + .addAction(nextAction) + .addAction(closeAction) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + builder.setStyle(MediaStyle() + .setMediaSession(service.mediaSession.sessionToken) + .setShowActionsInCompactView(0, 1, 2, 3, 4)) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O && PreferenceUtil.getInstance().coloredNotification()) { + builder.color = color + } + } + + if (stopped) { + return // notification has been stopped before loading was finished + } + updateNotifyModeAndPostNotification(builder.build()) + } + }) + } + } + + private fun retrievePlaybackAction(action: String): PendingIntent { + val serviceName = ComponentName(service, MusicService::class.java) + val intent = Intent(action) + intent.component = serviceName + return PendingIntent.getService(service, 0, intent, 0) + } +} \ No newline at end of file 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 index 85b5aa40..1559444d 100644 --- 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 @@ -87,7 +87,7 @@ class PlayingNotificationOreo : PlayingNotification() { val bigNotificationImageSize = service.resources .getDimensionPixelSize(R.dimen.notification_big_image_size) - service.runOnUiThread(Runnable { + service.runOnUiThread { if (target != null) { Glide.clear(target!!) } @@ -179,7 +179,7 @@ class PlayingNotificationOreo : PlayingNotification() { } }) - }) + } if (stopped) { return // notification has been stopped before loading was finished diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.java b/app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.java deleted file mode 100644 index 997f3fcf..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.java +++ /dev/null @@ -1,45 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.content.Context; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -/** - * 实现ViewPager左右滑动时的时差 - * Created by xmuSistone on 2016/9/18. - */ -public class CarousalPagerTransformer implements ViewPager.PageTransformer { - - private int maxTranslateOffsetX; - private ViewPager viewPager; - - public CarousalPagerTransformer(Context context) { - this.maxTranslateOffsetX = dp2px(context, 180); - } - - public void transformPage(@NonNull View view, float position) { - if (viewPager == null) { - viewPager = (ViewPager) view.getParent(); - } - - int leftInScreen = view.getLeft() - viewPager.getScrollX(); - int centerXInViewPager = leftInScreen + view.getMeasuredWidth() / 2; - int offsetX = centerXInViewPager - viewPager.getMeasuredWidth() / 2; - float offsetRate = (float) offsetX * 0.20f / viewPager.getMeasuredWidth(); - float scaleFactor = 1 - Math.abs(offsetRate); - if (scaleFactor > 0) { - view.setScaleX(scaleFactor); - view.setScaleY(scaleFactor); - view.setTranslationX(-maxTranslateOffsetX * offsetRate); - } - } - - private int dp2px(Context context, float dipValue) { - float m = context.getResources().getDisplayMetrics().density; - return (int) (dipValue * m + 0.5f); - } - - -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.kt b/app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.kt new file mode 100644 index 00000000..b68f434c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/CarousalPagerTransformer.kt @@ -0,0 +1,43 @@ +package code.name.monkey.retromusic.transform + +import android.content.Context +import android.view.View +import androidx.viewpager.widget.ViewPager + +/** + * 实现ViewPager左右滑动时的时差 + * Created by xmuSistone on 2016/9/18. + */ +class CarousalPagerTransformer(context: Context) : ViewPager.PageTransformer { + + private val maxTranslateOffsetX: Int + private var viewPager: ViewPager? = null + + init { + this.maxTranslateOffsetX = dp2px(context, 180f) + } + + override fun transformPage(view: View, position: Float) { + if (viewPager == null) { + viewPager = view.parent as ViewPager + } + + val leftInScreen = view.left - viewPager!!.scrollX + val centerXInViewPager = leftInScreen + view.measuredWidth / 2 + val offsetX = centerXInViewPager - viewPager!!.measuredWidth / 2 + val offsetRate = offsetX.toFloat() * 0.20f / viewPager!!.measuredWidth + val scaleFactor = 1 - Math.abs(offsetRate) + if (scaleFactor > 0) { + view.scaleX = scaleFactor + view.scaleY = scaleFactor + view.translationX = -maxTranslateOffsetX * offsetRate + } + } + + private fun dp2px(context: Context, dipValue: Float): Int { + val m = context.resources.displayMetrics.density + return (dipValue * m + 0.5f).toInt() + } + + +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.java b/app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.java deleted file mode 100644 index 2f18ae9b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.java +++ /dev/null @@ -1,57 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.annotation.SuppressLint; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -/******************************************************************* - * * * * * * * * * * * Created by OCN.Yang - * * * * * * * Time:2017/12/7 19:32. - * * * * * * * Email address:ocnyang@gmail.com - * * * * * * * * * * *.Yang Web site:www.ocnyang.com - *******************************************************************/ - -public class CascadingPageTransformer implements ViewPager.PageTransformer { - /** - * 偏移量 - */ - private int mScaleOffset = 40; - - - /** - * @param mScaleOffset 缩放偏移量 单位 px - */ - public void setScaleOffset(int mScaleOffset) { - this.mScaleOffset = mScaleOffset; - } - - @SuppressLint("NewApi") - public void transformPage(@NonNull View page, float position) { - if (position <= 0.0f) {//被滑动的那页 position 是-下标~ 0 - page.setTranslationX(0f); - //旋转角度 45° * -0.1 = -4.5° - page.setRotation((45 * position)); - //X轴偏移 li: 300/3 * -0.1 = -10 - page.setTranslationX((page.getWidth() / 3 * position)); - } else if (position <= 1f) { - float scale = (page.getWidth() - mScaleOffset * position) / (float) (page.getWidth()); - - page.setScaleX(scale); - page.setScaleY(scale); - - page.setTranslationX((-page.getWidth() * position)); - page.setTranslationY((mScaleOffset * 0.8f) * position); - } else { - //缩放比例 - float scale = (page.getWidth() - mScaleOffset * position) / (float) (page.getWidth()); - - page.setScaleX(scale); - page.setScaleY(scale); - - page.setTranslationX((-page.getWidth() * position)); - page.setTranslationY((mScaleOffset * 0.7f) * position); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.kt b/app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.kt new file mode 100644 index 00000000..8848f56d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/CascadingPageTransformer.kt @@ -0,0 +1,55 @@ +package code.name.monkey.retromusic.transform + +import android.annotation.SuppressLint +import android.view.View +import androidx.viewpager.widget.ViewPager + +/******************************************************************* + * * * * * * * * * * * Created by OCN.Yang + * * * * * * * Time:2017/12/7 19:32. + * * * * * * * Email address:ocnyang@gmail.com + * * * * * * * * * * *.Yang Web site:www.ocnyang.com + */ + +class CascadingPageTransformer : ViewPager.PageTransformer { + /** + * 偏移量 + */ + private var mScaleOffset = 40 + + + /** + * @param mScaleOffset 缩放偏移量 单位 px + */ + fun setScaleOffset(mScaleOffset: Int) { + this.mScaleOffset = mScaleOffset + } + + @SuppressLint("NewApi") + override fun transformPage(page: View, position: Float) { + if (position <= 0.0f) {//被滑动的那页 position 是-下标~ 0 + page.translationX = 0f + //旋转角度 45° * -0.1 = -4.5° + page.rotation = 45 * position + //X轴偏移 li: 300/3 * -0.1 = -10 + page.translationX = page.width / 3 * position + } else if (position <= 1f) { + val scale = (page.width - mScaleOffset * position) / page.width.toFloat() + + page.scaleX = scale + page.scaleY = scale + + page.translationX = -page.width * position + page.translationY = mScaleOffset * 0.8f * position + } else { + //缩放比例 + val scale = (page.width - mScaleOffset * position) / page.width.toFloat() + + page.scaleX = scale + page.scaleY = scale + + page.translationX = -page.width * position + page.translationY = mScaleOffset * 0.7f * position + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.java b/app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.java deleted file mode 100644 index 6796f9cf..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.java +++ /dev/null @@ -1,30 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -public class DepthTransformation implements ViewPager.PageTransformer { - @Override - public void transformPage(@NonNull View page, float position) { - if (position < -1) { // [-Infinity,-1) - // This page is way off-screen to the left. - page.setAlpha(0); - } else if (position <= 0) { // [-1,0] - page.setAlpha(1); - page.setTranslationX(0); - page.setScaleX(1); - page.setScaleY(1); - } else if (position <= 1) { // (0,1] - page.setTranslationX(-position * page.getWidth()); - page.setAlpha(1 - Math.abs(position)); - page.setScaleX(1 - Math.abs(position)); - page.setScaleY(1 - Math.abs(position)); - } else { // (1,+Infinity] - // This page is way off-screen to the right. - page.setAlpha(0); - - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.kt b/app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.kt new file mode 100644 index 00000000..9da6356e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/DepthTransformation.kt @@ -0,0 +1,27 @@ +package code.name.monkey.retromusic.transform + +import android.view.View +import androidx.viewpager.widget.ViewPager + +class DepthTransformation : ViewPager.PageTransformer { + override fun transformPage(page: View, position: Float) { + if (position < -1) { // [-Infinity,-1) + // This page is way off-screen to the left. + page.alpha = 0f + } else if (position <= 0) { // [-1,0] + page.alpha = 1f + page.translationX = 0f + page.scaleX = 1f + page.scaleY = 1f + } else if (position <= 1) { // (0,1] + page.translationX = -position * page.width + page.alpha = 1 - Math.abs(position) + page.scaleX = 1 - Math.abs(position) + page.scaleY = 1 - Math.abs(position) + } else { // (1,+Infinity] + // This page is way off-screen to the right. + page.alpha = 0f + + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.java b/app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.java deleted file mode 100644 index cedc2e65..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.java +++ /dev/null @@ -1,35 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -public class HingeTransformation implements ViewPager.PageTransformer { - @Override - public void transformPage(@NonNull View page, float position) { - - page.setTranslationX(-position * page.getWidth()); - page.setPivotX(0); - page.setPivotY(0); - - - if (position < -1) { // [-Infinity,-1) - // This page is way off-screen to the left. - page.setAlpha(0); - - } else if (position <= 0) { // [-1,0] - page.setRotation(90 * Math.abs(position)); - page.setAlpha(1 - Math.abs(position)); - - } else if (position <= 1) { // (0,1] - page.setRotation(0); - page.setAlpha(1); - - } else { // (1,+Infinity] - // This page is way off-screen to the right. - page.setAlpha(0); - - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.kt b/app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.kt new file mode 100644 index 00000000..30d0c330 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/HingeTransformation.kt @@ -0,0 +1,32 @@ +package code.name.monkey.retromusic.transform + +import android.view.View +import androidx.viewpager.widget.ViewPager + +class HingeTransformation : ViewPager.PageTransformer { + override fun transformPage(page: View, position: Float) { + + page.translationX = -position * page.width + page.pivotX = 0f + page.pivotY = 0f + + + if (position < -1) { // [-Infinity,-1) + // This page is way off-screen to the left. + page.alpha = 0f + + } else if (position <= 0) { // [-1,0] + page.rotation = 90 * Math.abs(position) + page.alpha = 1 - Math.abs(position) + + } else if (position <= 1) { // (0,1] + page.rotation = 0f + page.alpha = 1f + + } else { // (1,+Infinity] + // This page is way off-screen to the right. + page.alpha = 0f + + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.java b/app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.java deleted file mode 100644 index dfd12a89..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.java +++ /dev/null @@ -1,39 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -public class HorizontalFlipTransformation implements ViewPager.PageTransformer { - @Override - public void transformPage(@NonNull View page, float position) { - - page.setTranslationX(-position * page.getWidth()); - page.setCameraDistance(20000); - - if (position < 0.5 && position > -0.5) { - page.setVisibility(View.VISIBLE); - } else { - page.setVisibility(View.INVISIBLE); - } - - - if (position < -1) { // [-Infinity,-1) - // This page is way off-screen to the left. - page.setAlpha(0); - - } else if (position <= 0) { // [-1,0] - page.setAlpha(1); - page.setRotationX(180 * (1 - Math.abs(position) + 1)); - - } else if (position <= 1) { // (0,1] - page.setAlpha(1); - page.setRotationX(-180 * (1 - Math.abs(position) + 1)); - - } else { // (1,+Infinity] - // This page is way off-screen to the right. - page.setAlpha(0); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.kt b/app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.kt new file mode 100644 index 00000000..7523e1bb --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/HorizontalFlipTransformation.kt @@ -0,0 +1,36 @@ +package code.name.monkey.retromusic.transform + +import android.view.View +import androidx.viewpager.widget.ViewPager + +class HorizontalFlipTransformation : ViewPager.PageTransformer { + override fun transformPage(page: View, position: Float) { + + page.translationX = -position * page.width + page.cameraDistance = 20000f + + if (position < 0.5 && position > -0.5) { + page.visibility = View.VISIBLE + } else { + page.visibility = View.INVISIBLE + } + + + if (position < -1) { // [-Infinity,-1) + // This page is way off-screen to the left. + page.alpha = 0f + + } else if (position <= 0) { // [-1,0] + page.alpha = 1f + page.rotationX = 180 * (1 - Math.abs(position) + 1) + + } else if (position <= 1) { // (0,1] + page.alpha = 1f + page.rotationX = -180 * (1 - Math.abs(position) + 1) + + } else { // (1,+Infinity] + // This page is way off-screen to the right. + page.alpha = 0f + } + } +} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.java b/app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.java deleted file mode 100644 index c943d42c..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.java +++ /dev/null @@ -1,49 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -/** - * @author Hemanth S (h4h13). - */ - -public class NormalPageTransformer implements ViewPager.PageTransformer { - private static final float MIN_SCALE = 0.85f; - private static final float MIN_ALPHA = 0.5f; - - @Override - public void transformPage(@NonNull View view, float position) { - int pageWidth = view.getWidth(); - int pageHeight = view.getHeight(); - - if (position < -1) { // [-Infinity,-1) - // This page is way off-screen to the left. - view.setAlpha(1); - view.setScaleY(0.7f); - } else if (position <= 1) { // [-1,1] - // Modify the default slide transition to shrink the page as well - float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)); - float vertMargin = pageHeight * (1 - scaleFactor) / 2; - float horzMargin = pageWidth * (1 - scaleFactor) / 2; - if (position < 0) { - view.setTranslationX(horzMargin - vertMargin / 2); - } else { - view.setTranslationX(-horzMargin + vertMargin / 2); - } - - // Scale the page down (between MIN_SCALE and 1) - view.setScaleX(scaleFactor); - view.setScaleY(scaleFactor); - - // Fade the page relative to its size. - //view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); - - } else { // (1,+Infinity] - // This page is way off-screen to the right. - view.setAlpha(1); - view.setScaleY(0.7f); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.kt b/app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.kt new file mode 100644 index 00000000..7c1c78ac --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/NormalPageTransformer.kt @@ -0,0 +1,49 @@ +package code.name.monkey.retromusic.transform + +import android.view.View +import androidx.viewpager.widget.ViewPager + +/** + * @author Hemanth S (h4h13). + */ + +class NormalPageTransformer : ViewPager.PageTransformer { + + override fun transformPage(view: View, position: Float) { + val pageWidth = view.width + val pageHeight = view.height + + if (position < -1) { // [-Infinity,-1) + // This page is way off-screen to the left. + view.alpha = 1f + view.scaleY = 0.7f + } else if (position <= 1) { // [-1,1] + // Modify the default slide transition to shrink the page as well + val scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position)) + val vertMargin = pageHeight * (1 - scaleFactor) / 2 + val horzMargin = pageWidth * (1 - scaleFactor) / 2 + if (position < 0) { + view.translationX = horzMargin - vertMargin / 2 + } else { + view.translationX = -horzMargin + vertMargin / 2 + } + + // Scale the page down (between MIN_SCALE and 1) + view.scaleX = scaleFactor + view.scaleY = scaleFactor + + // Fade the page relative to its size. + //view.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); + + } else { // (1,+Infinity] + // This page is way off-screen to the right. + view.alpha = 1f + view.scaleY = 0.7f + } + } + + companion object { + private val MIN_SCALE = 0.85f + private val MIN_ALPHA = 0.5f + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.java b/app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.java deleted file mode 100644 index 3c26cefd..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.java +++ /dev/null @@ -1,57 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.annotation.TargetApi; -import android.os.Build; -import android.util.Log; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -/** - * Created by xgc1986 on 2/Apr/2016 - */ - -public class ParallaxPagerTransformer implements ViewPager.PageTransformer { - private int id; - private int border = 0; - private float speed = 0.2f; - - public ParallaxPagerTransformer(int id) { - this.id = id; - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - @Override - public void transformPage(@NonNull View view, float position) { - - View parallaxView = view.findViewById(id); - - if (view == null) { - Log.w("ParallaxPager", "There is no view"); - } - - if (parallaxView != null) { - if (position > -1 && position < 1) { - float width = parallaxView.getWidth(); - parallaxView.setTranslationX(-(position * width * speed)); - float sc = ((float) view.getWidth() - border) / view.getWidth(); - if (position == 0) { - view.setScaleX(1); - view.setScaleY(1); - } else { - view.setScaleX(sc); - view.setScaleY(sc); - } - } - } - } - - public void setBorder(int px) { - border = px; - } - - public void setSpeed(float speed) { - this.speed = speed; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.kt b/app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.kt new file mode 100644 index 00000000..58b10789 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/ParallaxPagerTransformer.kt @@ -0,0 +1,45 @@ +package code.name.monkey.retromusic.transform + +import android.annotation.TargetApi +import android.os.Build +import android.util.Log +import android.view.View +import androidx.viewpager.widget.ViewPager + +/** + * Created by xgc1986 on 2/Apr/2016 + */ + +class ParallaxPagerTransformer(private val id: Int) : ViewPager.PageTransformer { + private var border = 0 + private var speed = 0.2f + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + override fun transformPage(view: View, position: Float) { + + val parallaxView = view.findViewById(id) + + if (parallaxView != null) { + if (position > -1 && position < 1) { + val width = parallaxView.width.toFloat() + parallaxView.translationX = -(position * width * speed) + val sc = (view.width.toFloat() - border) / view.width + if (position == 0f) { + view.scaleX = 1f + view.scaleY = 1f + } else { + view.scaleX = sc + view.scaleY = sc + } + } + } + } + + fun setBorder(px: Int) { + border = px + } + + fun setSpeed(speed: Float) { + this.speed = speed + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.java b/app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.java deleted file mode 100644 index 3ff8c08b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.java +++ /dev/null @@ -1,28 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -public class StackPagerTransformer implements ViewPager.PageTransformer { - private static final float MIN_SCALE = 0.75f; - - - @Override - public void transformPage(@NonNull View view, float position) { - if (position <= 0f) { - view.setTranslationX(0f); - view.setScaleX(1f); - view.setScaleY(1f); - - } else if (position <= 1f) { - - final float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); - view.setPivotY(0.5f * view.getHeight()); - view.setTranslationX(view.getWidth() * -position); - view.setScaleX(scaleFactor); - view.setScaleY(scaleFactor); - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.kt b/app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.kt new file mode 100644 index 00000000..74310d72 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/StackPagerTransformer.kt @@ -0,0 +1,28 @@ +package code.name.monkey.retromusic.transform + +import android.view.View +import androidx.viewpager.widget.ViewPager + +class StackPagerTransformer : ViewPager.PageTransformer { + + + override fun transformPage(view: View, position: Float) { + if (position <= 0f) { + view.translationX = 0f + view.scaleX = 1f + view.scaleY = 1f + + } else if (position <= 1f) { + + val scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)) + view.pivotY = 0.5f * view.height + view.translationX = view.width * -position + view.scaleX = scaleFactor + view.scaleY = scaleFactor + } + } + + companion object { + private val MIN_SCALE = 0.75f + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.java b/app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.java deleted file mode 100644 index 2d7430bf..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.java +++ /dev/null @@ -1,42 +0,0 @@ -package code.name.monkey.retromusic.transform; - -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.viewpager.widget.ViewPager; - -public class VerticalFlipTransformation implements ViewPager.PageTransformer { - @Override - public void transformPage(@NonNull View page, float position) { - - page.setTranslationX(-position * page.getWidth()); - page.setCameraDistance(100000); - - if (position < 0.5 && position > -0.5) { - page.setVisibility(View.VISIBLE); - } else { - page.setVisibility(View.INVISIBLE); - } - - - if (position < -1) { // [-Infinity,-1) - // This page is way off-screen to the left. - page.setAlpha(0); - - } else if (position <= 0) { // [-1,0] - page.setAlpha(1); - page.setRotationY(180 * (1 - Math.abs(position) + 1)); - - } else if (position <= 1) { // (0,1] - page.setAlpha(1); - page.setRotationY(-180 * (1 - Math.abs(position) + 1)); - - } else { // (1,+Infinity] - // This page is way off-screen to the right. - page.setAlpha(0); - - } - - - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.kt b/app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.kt new file mode 100644 index 00000000..2c3eafaa --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/transform/VerticalFlipTransformation.kt @@ -0,0 +1,39 @@ +package code.name.monkey.retromusic.transform + +import android.view.View +import androidx.viewpager.widget.ViewPager + +class VerticalFlipTransformation : ViewPager.PageTransformer { + override fun transformPage(page: View, position: Float) { + + page.translationX = -position * page.width + page.cameraDistance = 100000f + + if (position < 0.5 && position > -0.5) { + page.visibility = View.VISIBLE + } else { + page.visibility = View.INVISIBLE + } + + + if (position < -1) { // [-Infinity,-1) + // This page is way off-screen to the left. + page.alpha = 0f + + } else if (position <= 0) { // [-1,0] + page.alpha = 1f + page.rotationY = 180 * (1 - Math.abs(position) + 1) + + } else if (position <= 1) { // (0,1] + page.alpha = 1f + page.rotationY = -180 * (1 - Math.abs(position) + 1) + + } else { // (1,+Infinity] + // This page is way off-screen to the right. + page.alpha = 0f + + } + + + } +} \ No newline at end of file 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 deleted file mode 100644 index 4d94c2d3..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.java +++ /dev/null @@ -1,227 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.Intent; -import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.os.Bundle; -import android.view.MenuItem; -import android.view.View; -import android.widget.TextView; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.google.android.material.appbar.AppBarLayout; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -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; -import androidx.core.app.ShareCompat; -import androidx.recyclerview.widget.DefaultItemAnimator; -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.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.model.Contributor; -import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; -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; -import static code.name.monkey.retromusic.Constants.TELEGRAM_CHANGE_LOG; -import static code.name.monkey.retromusic.Constants.TRANSLATE; - -/** - * @author Hemanth S (h4h13) - */ - -public class AboutActivity extends AbsBaseActivity { - - @BindView(R.id.app_bar) - AppBarLayout appBarLayout; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.app_version) - TextView appVersion; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.recycler_view) - RecyclerView recyclerView; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_about); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setLightNavigationBar(true); - - loadContributors(); - setUpToolbar(); - - appVersion.setText(getAppVersion()); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - private void setUpToolbar() { - appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)); - toolbar.setBackgroundColor(ThemeStore.primaryColor(this)); - setSupportActionBar(toolbar); - //noinspection ConstantConditions - //getSupportActionBar().setDisplayHomeAsUpEnabled(true); - setTitle(null); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - } - - private void openUrl(String url) { - Intent i = new Intent(Intent.ACTION_VIEW); - i.setData(Uri.parse(url)); - i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(i); - } - - - @OnClick({R.id.app_github, R.id.faq_link, R.id.app_google_plus, R.id.app_translation, - R.id.app_rate, R.id.app_share, R.id.instagram_link, R.id.twitter_link, R.id.changelog, - R.id.open_source, R.id.discord_link, R.id.telegram_link, R.id.donate_link}) - public void onViewClicked(View view) { - switch (view.getId()) { - case R.id.faq_link: - openUrl(FAQ_LINK); - break; - case R.id.telegram_link: - openUrl(APP_TELEGRAM_LINK); - break; - case R.id.discord_link: - openUrl(DISCORD_LINK); - break; - case R.id.app_github: - openUrl(GITHUB_PROJECT); - break; - case R.id.app_google_plus: - openUrl(GOOGLE_PLUS_COMMUNITY); - break; - case R.id.app_translation: - openUrl(TRANSLATE); - break; - case R.id.app_rate: - openUrl(RATE_ON_GOOGLE_PLAY); - break; - case R.id.app_share: - shareApp(); - break; - case R.id.donate_link: - NavigationUtil.goToSupportDevelopment(this); - break; - case R.id.instagram_link: - openUrl(APP_INSTAGRAM_LINK); - break; - case R.id.twitter_link: - openUrl(APP_TWITTER_LINK); - break; - case R.id.changelog: - showChangeLogOptions(); - break; - case R.id.open_source: - NavigationUtil.goToOpenSource(this); - break; - } - } - - private void showChangeLogOptions() { - new MaterialDialog.Builder(this) - .items(new String[]{"Telegram Channel", "App"}) - .itemsCallback(new MaterialDialog.ListCallback() { - @Override - public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) { - if (position == 0) { - openUrl(TELEGRAM_CHANGE_LOG); - } else { - NavigationUtil.gotoWhatNews(AboutActivity.this); - } - } - }) - .build() - .show(); - } - - private String getAppVersion() { - try { - PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); - return packageInfo.versionName; - } catch (PackageManager.NameNotFoundException e) { - e.printStackTrace(); - return "0.0.0"; - } - } - - private void shareApp() { - Intent shareIntent = ShareCompat.IntentBuilder.from(this) - .setType("songText/plain") - .setText(String.format(getString(R.string.app_share), getPackageName())) - .getIntent(); - if (shareIntent.resolveActivity(getPackageManager()) != null) { - startActivity( - Intent.createChooser(shareIntent, getResources().getText(R.string.action_share))); - } - } - - public void loadContributors() { - String data = getAssetJsonData(); - Type type = new TypeToken>() { - }.getType(); - List contributors = new Gson().fromJson(data, type); - - ContributorAdapter contributorAdapter = new ContributorAdapter((ArrayList) contributors); - recyclerView.setLayoutManager(new LinearLayoutManager(this)); - recyclerView.setItemAnimator(new DefaultItemAnimator()); - recyclerView.setAdapter(contributorAdapter); - } - - public String getAssetJsonData() { - String json = null; - try { - InputStream is = getAssets().open("contributors.json"); - int size = is.available(); - byte[] buffer = new byte[size]; - is.read(buffer); - is.close(); - json = new String(buffer, StandardCharsets.UTF_8); - } catch (IOException ex) { - ex.printStackTrace(); - return null; - } - return json; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.kt new file mode 100644 index 00000000..bbbf4d6f --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/AboutActivity.kt @@ -0,0 +1,181 @@ +package code.name.monkey.retromusic.ui.activities + +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Bundle +import android.view.MenuItem +import android.view.View +import androidx.core.app.ShareCompat +import androidx.recyclerview.widget.DefaultItemAnimator +import androidx.recyclerview.widget.LinearLayoutManager +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.Constants.APP_INSTAGRAM_LINK +import code.name.monkey.retromusic.Constants.APP_TELEGRAM_LINK +import code.name.monkey.retromusic.Constants.APP_TWITTER_LINK +import code.name.monkey.retromusic.Constants.DISCORD_LINK +import code.name.monkey.retromusic.Constants.FAQ_LINK +import code.name.monkey.retromusic.Constants.GITHUB_PROJECT +import code.name.monkey.retromusic.Constants.GOOGLE_PLUS_COMMUNITY +import code.name.monkey.retromusic.Constants.RATE_ON_GOOGLE_PLAY +import code.name.monkey.retromusic.Constants.TELEGRAM_CHANGE_LOG +import code.name.monkey.retromusic.Constants.TRANSLATE +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.model.Contributor +import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity +import code.name.monkey.retromusic.ui.adapter.ContributorAdapter +import code.name.monkey.retromusic.util.NavigationUtil +import com.afollestad.materialdialogs.MaterialDialog +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import kotlinx.android.synthetic.main.activity_about.* +import kotlinx.android.synthetic.main.card_credit.* +import kotlinx.android.synthetic.main.card_other.* +import kotlinx.android.synthetic.main.card_retro_info.* +import kotlinx.android.synthetic.main.card_social.* +import java.io.IOException +import java.nio.charset.StandardCharsets +import java.util.* + +class AboutActivity : AbsBaseActivity(), View.OnClickListener { + + private val assetJsonData: String? + get() { + val json: String + try { + val inputStream = assets.open("contributors.json") + val size = inputStream.available() + val buffer = ByteArray(size) + inputStream.read(buffer) + inputStream.close() + json = String(buffer, StandardCharsets.UTF_8) + } catch (ex: IOException) { + ex.printStackTrace() + return null + } + + return json + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_about) + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setLightNavigationBar(true) + + loadContributors() + setUpToolbar() + + appVersion.text = getAppVersion() + + setUpView() + } + + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + onBackPressed() + return true + } + return super.onOptionsItemSelected(item) + } + + private fun setUpToolbar() { + appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)) + toolbar.setBackgroundColor(ThemeStore.primaryColor(this)) + setSupportActionBar(toolbar) + title = null + ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)) + } + + private fun openUrl(url: String) { + val i = Intent(Intent.ACTION_VIEW) + i.data = Uri.parse(url) + i.flags = Intent.FLAG_ACTIVITY_NEW_TASK + startActivity(i) + } + + private fun setUpView() { + appGithub.setOnClickListener(this) + faqLink.setOnClickListener(this) + telegramLink.setOnClickListener(this) + appRate.setOnClickListener(this) + googlePlus.setOnClickListener(this) + appTranslation.setOnClickListener(this) + appShare.setOnClickListener(this) + donateLink.setOnClickListener(this) + instagramLink.setOnClickListener(this) + twitterLink.setOnClickListener(this) + changelog.setOnClickListener(this) + openSource.setOnClickListener(this) + } + + override fun onClick(view: View) { + when (view.id) { + R.id.faqLink -> openUrl(FAQ_LINK) + R.id.telegramLink -> openUrl(APP_TELEGRAM_LINK) + R.id.discordLink -> openUrl(DISCORD_LINK) + R.id.appGithub -> openUrl(GITHUB_PROJECT) + R.id.googlePlus -> openUrl(GOOGLE_PLUS_COMMUNITY) + R.id.appTranslation -> openUrl(TRANSLATE) + R.id.appRate -> openUrl(RATE_ON_GOOGLE_PLAY) + R.id.appShare -> shareApp() + R.id.donateLink -> NavigationUtil.goToSupportDevelopment(this) + R.id.instagramLink -> openUrl(APP_INSTAGRAM_LINK) + R.id.twitterLink -> openUrl(APP_TWITTER_LINK) + R.id.changelog -> showChangeLogOptions() + R.id.openSource -> NavigationUtil.goToOpenSource(this) + } + } + + private fun showChangeLogOptions() { + MaterialDialog.Builder(this) + .items("Telegram Channel", "App") + .itemsCallback { _, _, position, _ -> + if (position == 0) { + openUrl(TELEGRAM_CHANGE_LOG) + } else { + NavigationUtil.gotoWhatNews(this@AboutActivity) + } + } + .build() + .show() + } + + private fun getAppVersion(): String { + return try { + val packageInfo = packageManager.getPackageInfo(packageName, 0) + packageInfo.versionName + } catch (e: PackageManager.NameNotFoundException) { + e.printStackTrace() + "0.0.0" + } + } + + private fun shareApp() { + val shareIntent = ShareCompat.IntentBuilder.from(this) + .setType("songText/plain") + .setText(String.format(getString(R.string.app_share), packageName)) + .intent + if (shareIntent.resolveActivity(packageManager) != null) { + startActivity( + Intent.createChooser(shareIntent, resources.getText(R.string.action_share))) + } + } + + private fun loadContributors() { + val data = assetJsonData + val type = object : TypeToken>() { + + }.type + val contributors = Gson().fromJson>(data, type) + + val contributorAdapter = ContributorAdapter(contributors as ArrayList) + recyclerView.layoutManager = LinearLayoutManager(this) + recyclerView.itemAnimator = DefaultItemAnimator() + recyclerView.adapter = contributorAdapter + } +} 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 index 1876a809..dbd2f503 100644 --- 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 @@ -12,7 +12,6 @@ import androidx.core.widget.NestedScrollView import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.ColorUtil import code.name.monkey.appthemehelper.util.TintHelper @@ -71,7 +70,6 @@ class AlbumDetailsActivity : AbsSlidingMusicPanelActivity(), AlbumDetailsContrac setDrawUnderStatusBar() setupWindowTransition() super.onCreate(savedInstanceState) - ButterKnife.bind(this) toggleBottomNavigationView(true) setLightNavigationBar(true) @@ -175,20 +173,20 @@ class AlbumDetailsActivity : AbsSlidingMusicPanelActivity(), AlbumDetailsContrac ActivityCompat.startPostponedEnterTransition(this) } - override fun showData(album: Album) { - if (album.songs!!.isEmpty()) { + override fun showData(list: Album) { + if (list.songs!!.isEmpty()) { finish() return } - this.album = album + this.album = list - albumTitle.text = album.title - albumText.text = String.format("%s • %s • %s", album.artistName, MusicUtil.getYearString(album.year), MusicUtil.getReadableDurationString(MusicUtil.getTotalDuration(this, album.songs))) + albumTitle.text = list.title + albumText.text = String.format("%s • %s • %s", list.artistName, MusicUtil.getYearString(list.year), MusicUtil.getReadableDurationString(MusicUtil.getTotalDuration(this, list.songs))) loadAlbumCover() - loadMoreFrom(album) + loadMoreFrom(list) - simpleSongAdapter.swapDataSet(album.songs) + simpleSongAdapter.swapDataSet(list.songs) } private fun loadMoreFrom(album: Album) { diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.kt index c47a6074..508fcadc 100755 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.kt +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ArtistDetailActivity.kt @@ -16,7 +16,6 @@ import androidx.core.widget.NestedScrollView import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.ColorUtil import code.name.monkey.appthemehelper.util.TintHelper @@ -71,7 +70,7 @@ class ArtistDetailActivity : AbsSlidingMusicPanelActivity(), ArtistDetailContrac setDrawUnderStatusBar() setupWindowTransistion() super.onCreate(savedInstanceState) - ButterKnife.bind(this) + toggleBottomNavigationView(true) setNavigationbarColorAuto() @@ -273,7 +272,7 @@ class ArtistDetailActivity : AbsSlidingMusicPanelActivity(), ArtistDetailContrac private fun loadArtistImage() { - ArtistGlideRequest.Builder.from(Glide.with(this), artist) + ArtistGlideRequest.Builder.from(Glide.with(this), artist!!) .forceDownload(forceDownload) .generatePalette(this).build() .dontAnimate() 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 deleted file mode 100644 index 65095ed2..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.java +++ /dev/null @@ -1,232 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.os.Bundle; -import com.google.android.material.appbar.AppBarLayout; -import androidx.appcompat.widget.SwitchCompat; -import androidx.appcompat.widget.Toolbar; -import android.transition.TransitionManager; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CompoundButton; -import android.widget.LinearLayout; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.helper.EqualizerHelper; -import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity; - -/** - * @author Hemanth S (h4h13). - */ - -public class EqualizerActivity extends AbsMusicServiceActivity implements - AdapterView.OnItemSelectedListener { - - @BindView(R.id.equalizer) - SwitchCompat mEnable; - - @BindView(R.id.content) - LinearLayout mContent; - - @BindView(R.id.bands) - LinearLayout mLinearLayout; - - @BindView(R.id.bass_boost_strength) - SeekBar mBassBoostStrength; - - @BindView(R.id.virtualizer_strength) - SeekBar mVirtualizerStrength; - - @BindView(R.id.bass_boost) - TextView mBassBoost; - - @BindView(R.id.virtualizer) - TextView mVirtualizer; - - @BindView(R.id.toolbar) - Toolbar mToolbar; - - @BindView(R.id.app_bar) - AppBarLayout mAppBar; - - @BindView(R.id.presets) - Spinner mPresets; - - @BindView(R.id.title) - TextView mTitle; - - private CompoundButton.OnCheckedChangeListener mListener = (buttonView, isChecked) -> { - switch (buttonView.getId()) { - case R.id.equalizer: - EqualizerHelper.Companion.getInstance().getEqualizer().setEnabled(isChecked); - TransitionManager.beginDelayedTransition(mContent); - mContent.setVisibility(isChecked ? View.VISIBLE : View.GONE); - break; - } - }; - private SeekBar.OnSeekBarChangeListener mSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() { - @Override - public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { - if (fromUser) { - if (seekBar == mBassBoostStrength) { - mBassBoost.setEnabled(progress > 0); - EqualizerHelper.Companion.getInstance().setBassBoostStrength(progress); - EqualizerHelper.Companion.getInstance().setBassBoostEnabled(progress > 0); - } else if (seekBar == mVirtualizerStrength) { - mVirtualizer.setEnabled(progress > 0); - EqualizerHelper.Companion.getInstance().setVirtualizerEnabled(progress > 0); - EqualizerHelper.Companion.getInstance().setVirtualizerStrength(progress); - } - } - } - - @Override - public void onStartTrackingTouch(SeekBar seekBar) { - - } - - @Override - public void onStopTrackingTouch(SeekBar seekBar) { - - } - }; - private ArrayAdapter mPresetsNamesAdapter; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_equalizer); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - setupToolbar(); - - 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.Companion.getInstance().getBassBoostStrength()); - mBassBoostStrength.setOnSeekBarChangeListener(mSeekBarChangeListener); - - mVirtualizerStrength.setProgress(EqualizerHelper.Companion.getInstance().getVirtualizerStrength()); - mVirtualizerStrength.setOnSeekBarChangeListener(mSeekBarChangeListener); - - setupUI(); - addPresets(); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - private void setupToolbar() { - mTitle.setTextColor(ThemeStore.textColorPrimary(this)); - int primaryColor = ThemeStore.primaryColor(this); - mToolbar.setBackgroundColor(primaryColor); - mAppBar.setBackgroundColor(primaryColor); - mToolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp); - mToolbar.setNavigationOnClickListener(v -> onBackPressed()); - setSupportActionBar(mToolbar); - setTitle(null); - } - - private void addPresets() { - mPresetsNamesAdapter.clear(); - mPresetsNamesAdapter.add("Custom"); - for (int j = 0; j < EqualizerHelper.Companion.getInstance().getEqualizer().getNumberOfPresets(); j++) { - mPresetsNamesAdapter - .add(EqualizerHelper.Companion.getInstance().getEqualizer().getPresetName((short) j)); - mPresetsNamesAdapter.notifyDataSetChanged(); - } - mPresets - .setSelection((int) EqualizerHelper.Companion.getInstance().getEqualizer().getCurrentPreset() + 1); - } - - private void setupUI() { - mLinearLayout.removeAllViews(); - short bands; - try { - // get number of supported bands - 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 - for (short i = 0; i < bands; i++) { - final short band = i; - - 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.Companion.getInstance().getCenterFreq((int) band) / 1000)); - - TextView minDbTextView = view.findViewById(R.id.minus_db); - minDbTextView - .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.Companion.getInstance().getBandLevelHigh() / 100)); - - SeekBar bar = view.findViewById(R.id.seekbar); - bar.setMax(EqualizerHelper.Companion.getInstance().getBandLevelHigh() - EqualizerHelper.Companion.getInstance() - .getBandLevelLow()); - bar.setProgress( - 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.Companion.getInstance().setBandLevel((int) band, - (int) (progress + EqualizerHelper.Companion.getInstance().getBandLevelLow())); - if (fromUser) { - mPresets.setSelection(0); - } - } - - public void onStartTrackingTouch(SeekBar seekBar) { - } - - public void onStopTrackingTouch(SeekBar seekBar) { - } - }); - - mLinearLayout.addView(view); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (position == 0) { - return; - } - EqualizerHelper.Companion.getInstance().getEqualizer().usePreset((short) (position - 1)); - setupUI(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.kt new file mode 100644 index 00000000..f72b17b4 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/EqualizerActivity.kt @@ -0,0 +1,189 @@ +package code.name.monkey.retromusic.ui.activities + +import android.os.Bundle +import android.transition.TransitionManager +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.widget.AdapterView +import android.widget.ArrayAdapter +import android.widget.SeekBar +import android.widget.TextView +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.helper.EqualizerHelper +import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity +import kotlinx.android.synthetic.main.activity_equalizer.* + +/** + * @author Hemanth S (h4h13). + */ + +class EqualizerActivity : AbsMusicServiceActivity(), AdapterView.OnItemSelectedListener { + + + /*private val mListener = { buttonView, isChecked -> + when (buttonView.getId()) { + R.id.equalizerSwitch -> { + EqualizerHelper.instance!!.equalizer.enabled = isChecked + TransitionManager.beginDelayedTransition(content) + content.visibility = if (isChecked) View.VISIBLE else View.GONE + } + } + }*/ + private val mSeekBarChangeListener = object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { + if (fromUser) { + if (seekBar === bassBoostStrength) { + bassBoost.isEnabled = progress > 0 + EqualizerHelper.instance!!.bassBoostStrength = progress + EqualizerHelper.instance!!.isBassBoostEnabled = progress > 0 + } else if (seekBar === virtualizerStrength) { + virtualizer.isEnabled = progress > 0 + EqualizerHelper.instance!!.isVirtualizerEnabled = progress > 0 + EqualizerHelper.instance!!.virtualizerStrength = progress + } + } + } + + override fun onStartTrackingTouch(seekBar: SeekBar) { + + } + + override fun onStopTrackingTouch(seekBar: SeekBar) { + + } + } + + + private var mPresetsNamesAdapter: ArrayAdapter? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_equalizer) + + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + setupToolbar() + + equalizerSwitch.isChecked = EqualizerHelper.instance!!.equalizer.enabled + equalizerSwitch.setOnCheckedChangeListener { buttonView, isChecked -> + when (buttonView.id) { + R.id.equalizerSwitch -> { + EqualizerHelper.instance!!.equalizer.enabled = isChecked + TransitionManager.beginDelayedTransition(content) + content.visibility = if (isChecked) View.VISIBLE else View.GONE + } + } + } + + mPresetsNamesAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1) + presets.adapter = mPresetsNamesAdapter + presets.onItemSelectedListener = this + + bassBoostStrength.progress = EqualizerHelper.instance!!.bassBoostStrength + bassBoostStrength.setOnSeekBarChangeListener(mSeekBarChangeListener) + + virtualizerStrength.progress = EqualizerHelper.instance!!.virtualizerStrength + virtualizerStrength.setOnSeekBarChangeListener(mSeekBarChangeListener) + + setupUI() + addPresets() + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + onBackPressed() + return true + } + return super.onOptionsItemSelected(item) + } + + private fun setupToolbar() { + bannerTitle.setTextColor(ThemeStore.textColorPrimary(this)) + val primaryColor = ThemeStore.primaryColor(this) + appBarLayout.setBackgroundColor(primaryColor) + toolbar.apply { + setBackgroundColor(primaryColor) + setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp) + setNavigationOnClickListener { onBackPressed() } + setSupportActionBar(this) + } + title = null + } + + private fun addPresets() { + mPresetsNamesAdapter!!.clear() + mPresetsNamesAdapter!!.add("Custom") + for (j in 0 until EqualizerHelper.instance!!.equalizer.numberOfPresets) { + mPresetsNamesAdapter!! + .add(EqualizerHelper.instance!!.equalizer.getPresetName(j.toShort())) + mPresetsNamesAdapter!!.notifyDataSetChanged() + } + presets.setSelection(EqualizerHelper.instance!!.equalizer.currentPreset.toInt() + 1) + } + + private fun setupUI() { + frequencyBands.removeAllViews() + val bands: Short + try { + // get number of supported bands + bands = EqualizerHelper.instance!!.numberOfBands.toShort() + + // 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 + for (i in 0 until bands) { + + val view = LayoutInflater.from(this).inflate(R.layout.retro_seekbar, frequencyBands, false) + val freqTextView = view.findViewById(R.id.hurtz) + freqTextView.text = String.format("%d Hz", EqualizerHelper.instance!!.getCenterFreq(i) / 1000) + + val minDbTextView = view.findViewById(R.id.minus_db) + minDbTextView.text = String.format("%d dB", EqualizerHelper.instance!!.bandLevelLow / 100) + + val maxDbTextView = view.findViewById(R.id.plus_db) + maxDbTextView.text = String.format("%d dB", EqualizerHelper.instance!!.bandLevelHigh / 100) + + val bar = view.findViewById(R.id.seekbar) + bar.max = EqualizerHelper.instance!!.bandLevelHigh - EqualizerHelper.instance!! + .bandLevelLow + bar.progress = EqualizerHelper.instance!!.getBandLevel(i) - EqualizerHelper.instance!! + .bandLevelLow + bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { + EqualizerHelper.instance!!.setBandLevel(i, + progress + EqualizerHelper.instance!!.bandLevelLow) + if (fromUser) { + presets.setSelection(0) + } + } + + override fun onStartTrackingTouch(seekBar: SeekBar) {} + + override fun onStopTrackingTouch(seekBar: SeekBar) {} + }) + + frequencyBands.addView(view) + } + } catch (e: Exception) { + e.printStackTrace() + } + + } + + override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { + if (position == 0) { + return + } + EqualizerHelper.instance!!.equalizer.usePreset((position - 1).toShort()) + setupUI() + } + + override fun onNothingSelected(parent: AdapterView<*>) { + + } +} 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 10253ff9..4d2ba132 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.App; 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) { App.Companion.deleteAppData(); } } \ No newline at end of file +package code.name.monkey.retromusic.ui.activities; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import code.name.monkey.retromusic.R; public class ErrorHandlerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_error_handler); } } \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.kt index b1178cc1..2f6a8da9 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.kt +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/GenreDetailsActivity.kt @@ -7,7 +7,6 @@ import android.view.View import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper import code.name.monkey.retromusic.R @@ -44,7 +43,7 @@ class GenreDetailsActivity : AbsSlidingMusicPanelActivity(), GenreDetailsContrac override fun onCreate(savedInstanceState: Bundle?) { setDrawUnderStatusBar() super.onCreate(savedInstanceState) - ButterKnife.bind(this) + setStatusbarColorAuto() setNavigationbarColorAuto() @@ -140,8 +139,8 @@ class GenreDetailsActivity : AbsSlidingMusicPanelActivity(), GenreDetailsContrac }) } - override fun showData(songs: ArrayList) { - songAdapter!!.swapDataSet(songs) + override fun showData(list: ArrayList) { + songAdapter!!.swapDataSet(list) } override fun openCab(menuRes: Int, callback: MaterialCab.Callback): MaterialCab { diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.java deleted file mode 100644 index 0a14f900..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.java +++ /dev/null @@ -1,62 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import com.google.android.material.appbar.AppBarLayout; -import androidx.appcompat.widget.Toolbar; -import android.view.MenuItem; -import android.webkit.WebView; -import android.widget.TextView; - -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; - -public class LicenseActivity extends AbsBaseActivity { - @BindView(R.id.license) - WebView mLicense; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.app_bar) - AppBarLayout mAppbar; - - @BindView(R.id.title) - TextView title; - - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_license); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - mLicense.loadUrl("file:///android_asset/index.html"); - - title.setTextColor(ThemeStore.textColorPrimary(this)); - toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp); - toolbar.setNavigationOnClickListener(view -> onBackPressed()); - toolbar.setBackgroundColor(ThemeStore.primaryColor(this)); - mAppbar.setBackgroundColor(ThemeStore.primaryColor(this)); - setTitle(null); - setSupportActionBar(toolbar); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - } -} \ No newline at end of file diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.kt new file mode 100644 index 00000000..b88d27da --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LicenseActivity.kt @@ -0,0 +1,44 @@ +package code.name.monkey.retromusic.ui.activities + +import android.os.Bundle +import android.view.MenuItem +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity +import kotlinx.android.synthetic.main.activity_license.* + +class LicenseActivity : AbsBaseActivity() { + + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + onBackPressed() + return true + } + return super.onOptionsItemSelected(item) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_license) + + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + license.loadUrl("file:///android_asset/index.html") + bannerTitle.setTextColor(ThemeStore.textColorPrimary(this)) + toolbar!!.apply { + setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp) + setNavigationOnClickListener { onBackPressed() } + setBackgroundColor(ThemeStore.primaryColor(this@LicenseActivity)) + } + appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)) + title = null + setSupportActionBar(toolbar) + ToolbarContentTintHelper.colorBackButton(toolbar!!, ThemeStore.accentColor(this)) + } +} \ No newline at end of file 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 deleted file mode 100644 index 8f69927e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.java +++ /dev/null @@ -1,367 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.annotation.SuppressLint; -import android.content.res.ColorStateList; -import android.graphics.Color; -import android.graphics.PorterDuff; -import android.os.AsyncTask; -import android.os.Bundle; -import android.text.InputType; -import android.text.TextUtils; -import android.view.MenuItem; -import android.view.View; -import android.view.WindowManager; -import android.widget.RadioButton; -import android.widget.RadioGroup; -import android.widget.TextView; - -import com.afollestad.materialdialogs.DialogAction; -import com.afollestad.materialdialogs.MaterialDialog; -import com.bumptech.glide.Glide; -import com.google.android.material.bottomappbar.BottomAppBar; -import com.google.android.material.floatingactionbutton.FloatingActionButton; - -import org.jaudiotagger.tag.FieldKey; - -import java.io.File; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.Map; -import java.util.Objects; - -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.TintHelper; -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.MusicProgressViewUpdateHelper; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.model.lyrics.Lyrics; -import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity; -import code.name.monkey.retromusic.ui.activities.tageditor.WriteTagsAsyncTask; -import code.name.monkey.retromusic.util.LyricUtil; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.views.FitSystemWindowsLayout; -import code.name.monkey.retromusic.views.LyricView; -import io.reactivex.disposables.CompositeDisposable; - -public class LyricsActivity extends AbsMusicServiceActivity implements - MusicProgressViewUpdateHelper.Callback { - - @BindView(R.id.bottom_app_bar) - BottomAppBar bottomAppBar; - - @BindView(R.id.lyrics_view) - LyricView lyricView; - - @BindView(R.id.offline_lyrics) - TextView offlineLyrics; - - @BindView(R.id.actions) - RadioGroup actionsLayout; - - - @BindView(R.id.fab) - FloatingActionButton actionButton; - - @BindView(R.id.container) - FitSystemWindowsLayout fitSystemWindowsLayout; - - private MusicProgressViewUpdateHelper updateHelper; - private AsyncTask updateLyricsAsyncTask; - private CompositeDisposable disposable; - private Song song; - private Lyrics lyrics; - - @Override - protected void onCreate(Bundle savedInstanceState) { - setDrawUnderStatusBar(); - //setDrawUnderNavigationBar(); - super.onCreate(savedInstanceState); - - setContentView(R.layout.activity_lyrics); - ButterKnife.bind(this); - - setTaskDescriptionColorAuto(); - setNavigationbarColorAuto(); - - fitSystemWindowsLayout.setFit(!PreferenceUtil.getInstance().getFullScreenMode()); - - setSupportActionBar(bottomAppBar); - Objects.requireNonNull(bottomAppBar.getNavigationIcon()) - .setColorFilter(ThemeStore.textColorPrimary(this), PorterDuff.Mode.SRC_IN); - bottomAppBar.setBackgroundTint(ColorStateList.valueOf(ThemeStore.primaryColor(this))); - - TintHelper.setTintAuto(actionButton, ThemeStore.accentColor(this), true); - - updateHelper = new MusicProgressViewUpdateHelper(this, 500, 1000); - - setupLyricsView(); - setupWakelock(); - loadLrcFile(); - - actionsLayout.setOnCheckedChangeListener((group, checkedId) -> selectLyricsTye(checkedId)); - actionsLayout.check(PreferenceUtil.getInstance().getLastLyricsType()); - } - - private void selectLyricsTye(int group) { - PreferenceUtil.getInstance().setLastLyricsType(group); - RadioButton radioButton = actionsLayout.findViewById(group); - if (radioButton != null) { - radioButton.setBackgroundTintList(ColorStateList.valueOf(Color.WHITE)); - //radioButton.setTextColor(ThemeStore.textColorPrimary(this)); - } - - offlineLyrics.setVisibility(View.GONE); - lyricView.setVisibility(View.GONE); - - switch (group) { - case R.id.synced_lyrics: - loadLRCLyrics(); - lyricView.setVisibility(View.VISIBLE); - break; - default: - case R.id.normal_lyrics: - loadSongLyrics(); - offlineLyrics.setVisibility(View.VISIBLE); - break; - } - } - - private void loadLRCLyrics() { - if (LyricUtil.isLrcFileExist(song.getTitle(), song.getArtistName())) { - showLyricsLocal(LyricUtil.getLocalLyricFile(song.getTitle(), song.getArtistName())); - } - } - - private void setupWakelock() { - getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - - private void setupLyricsView() { - disposable = new CompositeDisposable(); - - lyricView - .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); - lyricView.setHintColor(Color.WHITE); - } - - @Override - public void onPlayingMetaChanged() { - super.onPlayingMetaChanged(); - loadLrcFile(); - } - - @Override - protected void onResume() { - super.onResume(); - updateHelper.start(); - } - - @Override - protected void onPause() { - super.onPause(); - updateHelper.stop(); - } - - @Override - public void onServiceConnected() { - super.onServiceConnected(); - loadLrcFile(); - } - - @Override - public void onDestroy() { - super.onDestroy(); - disposable.clear(); - - if (updateLyricsAsyncTask != null && !updateLyricsAsyncTask.isCancelled()) { - updateLyricsAsyncTask.cancel(true); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onUpdateProgressViews(int progress, int total) { - lyricView.setCurrentTimeMillis(progress); - } - - private void loadLrcFile() { - song = MusicPlayerRemote.INSTANCE.getCurrentSong(); - bottomAppBar.setTitle(song.getTitle()); - bottomAppBar.setSubtitle(song.getArtistName()); - 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) { - if (PreferenceUtil.getInstance().getAdaptiveColor()) { - //background.setBackgroundColor(color); - } - } - }); - } - - private void showLyricsLocal(File file) { - if (file == null) { - lyricView.reset(); - } else { - lyricView.setLyricFile(file, "UTF-8"); - } - } - - @OnClick({R.id.fab}) - public void onViewClicked(View view) { - switch (view.getId()) { - case R.id.back: - onBackPressed(); - break; - case R.id.fab: - switch (actionsLayout.getCheckedRadioButtonId()) { - case R.id.synced_lyrics: - showSyncedLyrics(); - break; - case R.id.normal_lyrics: - showLyricsSaveDialog(); - break; - } - break; - } - } - - @SuppressLint("StaticFieldLeak") - private void loadSongLyrics() { - if (updateLyricsAsyncTask != null) { - updateLyricsAsyncTask.cancel(false); - } - final Song song = MusicPlayerRemote.INSTANCE.getCurrentSong(); - updateLyricsAsyncTask = new AsyncTask() { - @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 onPreExecute() { - super.onPreExecute(); - lyrics = null; - } - - @Override - protected void onPostExecute(Lyrics l) { - lyrics = l; - offlineLyrics.setVisibility(View.VISIBLE); - if (l == null) { - offlineLyrics.setText(R.string.no_lyrics_found); - return; - } - offlineLyrics.setText(l.data); - } - - @Override - protected void onCancelled(Lyrics s) { - onPostExecute(null); - } - }.execute(); - } - - private void showSyncedLyrics() { - String content = ""; - try { - content = LyricUtil.getStringFromFile(song.getTitle(), song.getArtistName()); - } catch (Exception e) { - e.printStackTrace(); - } - new MaterialDialog.Builder(this) - .title("Add lyrics") - .neutralText("Search") - .content("Add time frame lyrics") - .negativeText("Delete") - .onNegative((dialog, which) -> { - 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.getTitle(), song.getArtistName(), input.toString()); - loadLrcFile(); - }).show(); - } - - private String getGoogleSearchLrcUrl() { - String baseUrl = "http://www.google.com/search?"; - String query = song.getTitle() + "+" + song.getArtistName(); - query = "q=" + query.replace(" ", "+") + " .lrc"; - baseUrl += query; - return baseUrl; - } - - private void showLyricsSaveDialog() { - String content = ""; - if (lyrics == null) { - content = ""; - } else { - content = lyrics.data; - } - new MaterialDialog.Builder(this) - .title("Add lyrics") - .neutralText("Search") - .onNeutral(new MaterialDialog.SingleButtonCallback() { - @Override - public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - RetroUtil.openUrl(LyricsActivity.this, getGoogleSearchUrl(song.getTitle(), song.getArtistName())); - } - }) - .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE) - .input("Paste lyrics here", content, (dialog, input) -> { - Map fieldKeyValueMap = new EnumMap<>(FieldKey.class); - fieldKeyValueMap.put(FieldKey.LYRICS, input.toString()); - - new WriteTagsAsyncTask(LyricsActivity.this) - .execute( - new WriteTagsAsyncTask.LoadingInfo(getSongPaths(song), fieldKeyValueMap, null)); - loadLrcFile(); - }) - .show(); - } - - private ArrayList getSongPaths(Song song) { - ArrayList paths = new ArrayList<>(1); - paths.add(song.getData()); - return paths; - } - - private String getGoogleSearchUrl(String title, String text) { - String baseUrl = "http://www.google.com/search?"; - String query = title + "+" + text; - query = "q=" + query.replace(" ", "+") + " lyrics"; - baseUrl += query; - return baseUrl; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.kt new file mode 100644 index 00000000..5741f080 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/LyricsActivity.kt @@ -0,0 +1,307 @@ +package code.name.monkey.retromusic.ui.activities + +import android.annotation.SuppressLint +import android.content.res.ColorStateList +import android.graphics.Color +import android.graphics.PorterDuff +import android.graphics.drawable.Drawable +import android.os.AsyncTask +import android.os.Bundle +import android.text.InputType +import android.text.TextUtils +import android.view.MenuItem +import android.view.View +import android.view.WindowManager +import android.widget.RadioButton +import androidx.core.content.ContextCompat +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.TintHelper +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.MusicProgressViewUpdateHelper +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.model.lyrics.Lyrics +import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity +import code.name.monkey.retromusic.ui.activities.tageditor.WriteTagsAsyncTask +import code.name.monkey.retromusic.util.LyricUtil +import code.name.monkey.retromusic.util.MusicUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import code.name.monkey.retromusic.util.RetroUtil +import com.afollestad.materialdialogs.MaterialDialog +import com.bumptech.glide.Glide +import io.reactivex.disposables.CompositeDisposable +import kotlinx.android.synthetic.main.activity_lyrics.* +import org.jaudiotagger.tag.FieldKey +import java.io.File +import java.util.* + +class LyricsActivity : AbsMusicServiceActivity(), MusicProgressViewUpdateHelper.Callback, View.OnClickListener { + + private var updateHelper: MusicProgressViewUpdateHelper? = null + private var updateLyricsAsyncTask: AsyncTask<*, *, *>? = null + private var disposable: CompositeDisposable? = null + private var song: Song? = null + private var lyrics: Lyrics? = null + + private val googleSearchLrcUrl: String + get() { + var baseUrl = "http://www.google.com/search?" + var query = song!!.title + "+" + song!!.artistName + query = "q=" + query.replace(" ", "+") + " .lrc" + baseUrl += query + return baseUrl + } + + override fun onCreate(savedInstanceState: Bundle?) { + setDrawUnderStatusBar() + //setDrawUnderNavigationBar(); + super.onCreate(savedInstanceState) + + setContentView(R.layout.activity_lyrics) + + + setTaskDescriptionColorAuto() + setNavigationbarColorAuto() + + container.isFit = !PreferenceUtil.getInstance().fullScreenMode + + setSupportActionBar(bottomAppBar) + Objects.requireNonNull(bottomAppBar!!.navigationIcon) + .setColorFilter(ThemeStore.textColorPrimary(this), PorterDuff.Mode.SRC_IN) + bottomAppBar!!.backgroundTint = ColorStateList.valueOf(ThemeStore.primaryColor(this)) + + TintHelper.setTintAuto(fab, ThemeStore.accentColor(this), true) + + updateHelper = MusicProgressViewUpdateHelper(this, 500, 1000) + + setupLyricsView() + setupWakelock() + loadLrcFile() + + actions.setOnCheckedChangeListener { _, checkedId -> selectLyricsTye(checkedId) } + actions.check(PreferenceUtil.getInstance().lastLyricsType) + + + fab.setOnClickListener(this) + } + + private fun selectLyricsTye(group: Int) { + PreferenceUtil.getInstance().lastLyricsType = group + val radioButton = actions.findViewById(group) + if (radioButton != null) { + radioButton.backgroundTintList = ColorStateList.valueOf(Color.WHITE) + //radioButton.setTextColor(ThemeStore.textColorPrimary(this)); + } + + offlineLyrics!!.visibility = View.GONE + lyricsView.visibility = View.GONE + + when (group) { + R.id.syncedLyrics -> { + loadLRCLyrics() + lyricsView!!.visibility = View.VISIBLE + } + R.id.normalLyrics -> { + loadSongLyrics() + offlineLyrics!!.visibility = View.VISIBLE + } + else -> { + loadSongLyrics() + offlineLyrics!!.visibility = View.VISIBLE + } + } + } + + private fun loadLRCLyrics() { + if (LyricUtil.isLrcFileExist(song!!.title, song!!.artistName)) { + showLyricsLocal(LyricUtil.getLocalLyricFile(song!!.title, song!!.artistName)) + } + } + + private fun setupWakelock() { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + + private fun setupLyricsView() { + disposable = CompositeDisposable() + + lyricsView!!.apply { + setOnPlayerClickListener { progress, _ -> MusicPlayerRemote.seekTo(progress.toInt()) } + //lyricView.setHighLightTextColor(ThemeStore.accentColor(this)); + setDefaultColor(ContextCompat.getColor(this@LyricsActivity, R.color.md_grey_400)) + //lyricView.setTouchable(false); + setHintColor(Color.WHITE) + } + } + + override fun onPlayingMetaChanged() { + super.onPlayingMetaChanged() + loadLrcFile() + } + + override fun onResume() { + super.onResume() + updateHelper!!.start() + } + + override fun onPause() { + super.onPause() + updateHelper!!.stop() + } + + override fun onServiceConnected() { + super.onServiceConnected() + loadLrcFile() + } + + override fun onDestroy() { + super.onDestroy() + disposable!!.clear() + + if (updateLyricsAsyncTask != null && !updateLyricsAsyncTask!!.isCancelled) { + updateLyricsAsyncTask!!.cancel(true) + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + onBackPressed() + } + return super.onOptionsItemSelected(item) + } + + override fun onUpdateProgressViews(progress: Int, total: Int) { + lyricsView!!.setCurrentTimeMillis(progress.toLong()) + } + + private fun loadLrcFile() { + song = MusicPlayerRemote.currentSong + bottomAppBar.title = song!!.title + bottomAppBar.subtitle = song!!.artistName + SongGlideRequest.Builder.from(Glide.with(this), song!!) + .checkIgnoreMediaStore(this) + .generatePalette(this) + .build() + .into(object : RetroMusicColoredTarget(findViewById(R.id.image)) { + override fun onColorReady(color: Int) { + if (PreferenceUtil.getInstance().adaptiveColor) { + //background.setBackgroundColor(color); + } + } + }) + } + + private fun showLyricsLocal(file: File?) { + if (file == null) { + lyricsView!!.reset() + } else { + lyricsView!!.setLyricFile(file, "UTF-8") + } + } + + override fun onClick(view: View) { + when (view.id) { + android.R.id.home -> onBackPressed() + R.id.fab -> when (actions.checkedRadioButtonId) { + R.id.syncedLyrics -> showSyncedLyrics() + R.id.normalLyrics -> showLyricsSaveDialog() + } + } + } + + @SuppressLint("StaticFieldLeak") + private fun loadSongLyrics() { + if (updateLyricsAsyncTask != null) { + updateLyricsAsyncTask!!.cancel(false) + } + val song = MusicPlayerRemote.currentSong + updateLyricsAsyncTask = object : AsyncTask() { + override fun doInBackground(vararg params: Void): Lyrics? { + val data = MusicUtil.getLyrics(song) + return if (TextUtils.isEmpty(data)) { + null + } else Lyrics.parse(song, data) + } + + override fun onPreExecute() { + super.onPreExecute() + lyrics = null + } + + override fun onPostExecute(l: Lyrics?) { + lyrics = l + offlineLyrics!!.visibility = View.VISIBLE + if (l == null) { + offlineLyrics!!.setText(R.string.no_lyrics_found) + return + } + offlineLyrics!!.text = l.data + } + + override fun onCancelled(s: Lyrics) { + onPostExecute(null) + } + }.execute() + } + + private fun showSyncedLyrics() { + var content = "" + try { + content = LyricUtil.getStringFromFile(song!!.title, song!!.artistName) + } catch (e: Exception) { + e.printStackTrace() + } + + MaterialDialog.Builder(this) + .title("Add lyrics") + .neutralText("Search") + .content("Add time frame lyrics") + .negativeText("Delete") + .onNegative { _, _ -> + LyricUtil.deleteLrcFile(song!!.title, song!!.artistName) + loadLrcFile() + } + .onNeutral { _, _ -> RetroUtil.openUrl(this@LyricsActivity, googleSearchLrcUrl) } + .inputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE) + .input("Paste lyrics here", content) { _, input -> + LyricUtil.writeLrcToLoc(song!!.title, song!!.artistName, input.toString()) + loadLrcFile() + }.show() + } + + private fun showLyricsSaveDialog() { + val content: String = if (lyrics == null) { + "" + } else { + lyrics!!.data + } + MaterialDialog.Builder(this) + .title("Add lyrics") + .neutralText("Search") + .onNeutral { _, _ -> RetroUtil.openUrl(this@LyricsActivity, getGoogleSearchUrl(song!!.title, song!!.artistName)) } + .inputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE) + .input("Paste lyrics here", content) { _, input -> + val fieldKeyValueMap = EnumMap(FieldKey::class.java) + fieldKeyValueMap[FieldKey.LYRICS] = input.toString() + WriteTagsAsyncTask(this@LyricsActivity).execute(WriteTagsAsyncTask.LoadingInfo(getSongPaths(song!!), fieldKeyValueMap, null)) + loadLrcFile() + } + .show() + } + + private fun getSongPaths(song: Song): ArrayList { + val paths = ArrayList(1) + paths.add(song.data!!) + return paths + } + + private fun getGoogleSearchUrl(title: String?, text: String?): String { + var baseUrl = "http://www.google.com/search?" + var query = "$title+$text" + query = "q=" + query.replace(" ", "+") + " lyrics" + baseUrl += query + return baseUrl + } +} 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 index 81f934b6..0fd77645 100644 --- 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 @@ -11,8 +11,8 @@ import android.util.Log import android.view.MenuItem import android.view.View import android.view.ViewGroup +import androidx.core.app.ShareCompat import androidx.fragment.app.Fragment -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.ATHUtil import code.name.monkey.appthemehelper.util.NavigationViewUtil @@ -29,6 +29,7 @@ import code.name.monkey.retromusic.ui.activities.base.AbsSlidingMusicPanelActivi import code.name.monkey.retromusic.ui.fragments.mainactivity.LibraryFragment import code.name.monkey.retromusic.ui.fragments.mainactivity.folders.FoldersFragment import code.name.monkey.retromusic.ui.fragments.mainactivity.home.BannerHomeFragment +import code.name.monkey.retromusic.util.NavigationUtil import code.name.monkey.retromusic.util.PreferenceUtil import com.afollestad.materialdialogs.MaterialDialog import io.reactivex.disposables.CompositeDisposable @@ -67,7 +68,6 @@ class MainActivity : AbsSlidingMusicPanelActivity(), SharedPreferences.OnSharedP override fun onCreate(savedInstanceState: Bundle?) { setDrawUnderStatusBar() super.onCreate(savedInstanceState) - ButterKnife.bind(this) getBottomNavigationView()!!.setOnNavigationItemSelectedListener { PreferenceUtil.getInstance().lastPage = it.itemId @@ -298,11 +298,31 @@ class MainActivity : AbsSlidingMusicPanelActivity(), SharedPreferences.OnSharedP R.id.nav_home -> Handler().postDelayed({ setMusicChooser(HOME) }, 200) R.id.nav_folders -> Handler().postDelayed({ setMusicChooser(FOLDERS) }, 200) R.id.buy_pro -> Handler().postDelayed({ startActivityForResult(Intent(this@MainActivity, ProVersionActivity::class.java), PURCHASE_REQUEST) }, 200) + R.id.nav_settings -> Handler().postDelayed({ NavigationUtil.goToSettings(this@MainActivity) }, 200) + R.id.nav_equalizer -> Handler().postDelayed({ NavigationUtil.openEqualizer(this@MainActivity) }, 200) + R.id.nav_share_app -> Handler().postDelayed({ shareApp() }, 200) + R.id.nav_report_bug -> Handler().postDelayed({ prepareBugReport() }, 200) } true } } + private fun prepareBugReport() { + + } + + private fun shareApp() { + val shareIntent = ShareCompat.IntentBuilder.from(this) + .setType("songText/plain") + .setText(String.format(getString(R.string.app_share), packageName)) + .intent + if (shareIntent.resolveActivity(packageManager) != null) { + startActivity( + Intent.createChooser(shareIntent, resources.getText(R.string.action_share))) + } + } + + private fun setMusicChooser(key: Int) { PreferenceUtil.getInstance().lastMusicChooser = key when (key) { 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 deleted file mode 100644 index 4f90e5b6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.java +++ /dev/null @@ -1,203 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.widget.TextView; - -import com.google.android.material.appbar.AppBarLayout; -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.NonNull; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindDrawable; -import butterknife.BindString; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.appthemehelper.ThemeStore; -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.ui.activities.base.AbsMusicServiceActivity; -import code.name.monkey.retromusic.ui.adapter.song.PlayingQueueAdapter; -import code.name.monkey.retromusic.util.MusicUtil; -import code.name.monkey.retromusic.views.CollapsingFAB; - - -public class PlayingQueueActivity extends AbsMusicServiceActivity { - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindDrawable(R.drawable.ic_keyboard_backspace_black_24dp) - Drawable close; - - @BindView(R.id.player_queue_sub_header) - TextView textView; - - @BindString(R.string.queue) - String queue; - - @BindView(R.id.app_bar) - AppBarLayout appBarLayout; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.recycler_view) - RecyclerView mRecyclerView; - - @BindView(R.id.clear_queue) - CollapsingFAB clearQueue; - - private RecyclerView.Adapter mWrappedAdapter; - private RecyclerViewDragDropManager mRecyclerViewDragDropManager; - private PlayingQueueAdapter mPlayingQueueAdapter; - private LinearLayoutManager mLayoutManager; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_playing_queue); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - setupToolbar(); - setUpRecyclerView(); - } - - private void setUpRecyclerView() { - mRecyclerViewDragDropManager = new RecyclerViewDragDropManager(); - final GeneralItemAnimator animator = new RefactoredDefaultItemAnimator(); - - mPlayingQueueAdapter = new PlayingQueueAdapter( - this, - MusicPlayerRemote.INSTANCE.getPlayingQueue(), - MusicPlayerRemote.INSTANCE.getPosition(), - R.layout.item_queue); - mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(mPlayingQueueAdapter); - - mLayoutManager = new LinearLayoutManager(this); - - mRecyclerView.setLayoutManager(mLayoutManager); - mRecyclerView.setAdapter(mWrappedAdapter); - mRecyclerView.setItemAnimator(animator); - mRecyclerViewDragDropManager.attachRecyclerView(mRecyclerView); - mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.INSTANCE.getPosition() + 1, 0); - - mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { - @Override - public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { - super.onScrolled(recyclerView, dx, dy); - if (dy > 0) { - clearQueue.setShowTitle(false); - } else if (dy < 0) { - clearQueue.setShowTitle(true); - } - } - }); - } - - @Override - public void onQueueChanged() { - if (MusicPlayerRemote.INSTANCE.getPlayingQueue().isEmpty()) { - finish(); - return; - } - updateQueue(); - updateCurrentSong(); - } - - @Override - public void onMediaStoreChanged() { - updateQueue(); - updateCurrentSong(); - } - - @SuppressWarnings("ConstantConditions") - private void updateCurrentSong() { - } - - @Override - public void onPlayingMetaChanged() { - updateQueuePosition(); - } - - private void updateQueuePosition() { - mPlayingQueueAdapter.setCurrent(MusicPlayerRemote.INSTANCE.getPosition()); - resetToCurrentPosition(); - } - - private void updateQueue() { - mPlayingQueueAdapter.swapDataSet(MusicPlayerRemote.INSTANCE.getPlayingQueue(), MusicPlayerRemote.INSTANCE.getPosition()); - resetToCurrentPosition(); - } - - private void resetToCurrentPosition() { - mRecyclerView.stopScroll(); - mLayoutManager.scrollToPositionWithOffset(MusicPlayerRemote.INSTANCE.getPosition() + 1, 0); - } - - @Override - protected void onPause() { - if (mRecyclerViewDragDropManager != null) { - mRecyclerViewDragDropManager.cancelDrag(); - } - super.onPause(); - } - - @Override - public void onDestroy() { - if (mRecyclerViewDragDropManager != null) { - mRecyclerViewDragDropManager.release(); - mRecyclerViewDragDropManager = null; - } - - if (mRecyclerView != null) { - mRecyclerView.setItemAnimator(null); - mRecyclerView.setAdapter(null); - mRecyclerView = null; - } - - if (mWrappedAdapter != null) { - WrapperAdapterUtils.releaseAll(mWrappedAdapter); - mWrappedAdapter = null; - } - mPlayingQueueAdapter = null; - mLayoutManager = null; - super.onDestroy(); - } - - protected String getUpNextAndQueueTime() { - return getResources().getString(R.string.up_next) + " • " + MusicUtil.getReadableDurationString(MusicPlayerRemote.INSTANCE.getQueueDurationMillis(MusicPlayerRemote.INSTANCE.getPosition())); - } - - private void setupToolbar() { - title.setTextColor(ThemeStore.textColorPrimary(this)); - textView.setText(getUpNextAndQueueTime()); - textView.setTextColor(ThemeStore.accentColor(this)); - - appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)); - toolbar.setBackgroundColor(ThemeStore.primaryColor(this)); - toolbar.setNavigationIcon(close); - setSupportActionBar(toolbar); - setTitle(null); - toolbar.setNavigationOnClickListener(v -> onBackPressed()); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - clearQueue.setColor(ThemeStore.accentColor(this)); - } - - @OnClick(R.id.clear_queue) - void clearQueue() { - MusicPlayerRemote.INSTANCE.clearQueue(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.kt new file mode 100644 index 00000000..ec549e2c --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlayingQueueActivity.kt @@ -0,0 +1,152 @@ +package code.name.monkey.retromusic.ui.activities + +import android.os.Bundle +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.ThemeStore +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.ui.activities.base.AbsMusicServiceActivity +import code.name.monkey.retromusic.ui.adapter.song.PlayingQueueAdapter +import code.name.monkey.retromusic.util.MusicUtil +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 kotlinx.android.synthetic.main.activity_playing_queue.* + + +class PlayingQueueActivity : AbsMusicServiceActivity() { + + private var wrappedAdapter: RecyclerView.Adapter<*>? = null + private var recyclerViewDragDropManager: RecyclerViewDragDropManager? = null + private var playingQueueAdapter: PlayingQueueAdapter? = null + private lateinit var layoutManager: LinearLayoutManager + + private val upNextAndQueueTime: String + get() = resources.getString(R.string.up_next) + " • " + MusicUtil.getReadableDurationString(MusicPlayerRemote.getQueueDurationMillis(MusicPlayerRemote.position)) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_playing_queue) + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + setupToolbar() + setUpRecyclerView() + + clearQueue.setOnClickListener { + MusicPlayerRemote.clearQueue() + } + } + + private fun setUpRecyclerView() { + recyclerViewDragDropManager = RecyclerViewDragDropManager() + val animator = RefactoredDefaultItemAnimator() + + playingQueueAdapter = PlayingQueueAdapter( + this, + MusicPlayerRemote.playingQueue, + MusicPlayerRemote.position, + R.layout.item_queue) + wrappedAdapter = recyclerViewDragDropManager!!.createWrappedAdapter(playingQueueAdapter!!) + + layoutManager = LinearLayoutManager(this) + + recyclerView.apply { + layoutManager = layoutManager + adapter = wrappedAdapter + itemAnimator = animator + recyclerViewDragDropManager!!.attachRecyclerView(this) + } + + layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.position + 1, 0) + + recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { + super.onScrolled(recyclerView, dx, dy) + if (dy > 0) { + clearQueue.setShowTitle(false) + } else if (dy < 0) { + clearQueue.setShowTitle(true) + } + } + }) + } + + override fun onQueueChanged() { + if (MusicPlayerRemote.playingQueue.isEmpty()) { + finish() + return + } + updateQueue() + updateCurrentSong() + } + + override fun onMediaStoreChanged() { + updateQueue() + updateCurrentSong() + } + + private fun updateCurrentSong() {} + + override fun onPlayingMetaChanged() { + updateQueuePosition() + } + + private fun updateQueuePosition() { + playingQueueAdapter!!.setCurrent(MusicPlayerRemote.position) + resetToCurrentPosition() + } + + private fun updateQueue() { + playingQueueAdapter!!.swapDataSet(MusicPlayerRemote.playingQueue, MusicPlayerRemote.position) + resetToCurrentPosition() + } + + private fun resetToCurrentPosition() { + recyclerView.stopScroll() + layoutManager.scrollToPositionWithOffset(MusicPlayerRemote.position + 1, 0) + } + + override fun onPause() { + if (recyclerViewDragDropManager != null) { + recyclerViewDragDropManager!!.cancelDrag() + } + super.onPause() + } + + override fun onDestroy() { + if (recyclerViewDragDropManager != null) { + recyclerViewDragDropManager!!.release() + recyclerViewDragDropManager = null + } + + + + if (wrappedAdapter != null) { + WrapperAdapterUtils.releaseAll(wrappedAdapter) + wrappedAdapter = null + } + playingQueueAdapter = null + super.onDestroy() + } + + private fun setupToolbar() { + bannerTitle.setTextColor(ThemeStore.textColorPrimary(this)) + playerQueueSubHeader.text = upNextAndQueueTime + playerQueueSubHeader.setTextColor(ThemeStore.accentColor(this)) + + appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)) + toolbar.setBackgroundColor(ThemeStore.primaryColor(this)) + toolbar.setNavigationIcon(R.drawable.ic_close_white_24dp) + setSupportActionBar(toolbar) + title = null + toolbar.setNavigationOnClickListener { onBackPressed() } + ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)) + clearQueue.setColor(ThemeStore.accentColor(this)) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.kt index 07ca6e0e..6155b743 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.kt +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/PlaylistDetailActivity.kt @@ -6,7 +6,6 @@ import android.view.MenuItem import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView -import butterknife.ButterKnife import code.name.monkey.appthemehelper.ThemeStore import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper import code.name.monkey.retromusic.R @@ -46,7 +45,6 @@ class PlaylistDetailActivity : AbsSlidingMusicPanelActivity(), CabHolder, Playli override fun onCreate(savedInstanceState: Bundle?) { setDrawUnderStatusBar() super.onCreate(savedInstanceState) - ButterKnife.bind(this) setStatusbarColorAuto() setNavigationbarColorAuto() @@ -243,8 +241,8 @@ class PlaylistDetailActivity : AbsSlidingMusicPanelActivity(), CabHolder, Playli override fun completed() {} - override fun showData(songs: ArrayList) { - adapter.swapDataSet(songs) + override fun showData(list: ArrayList) { + adapter.swapDataSet(list) } companion object { 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 deleted file mode 100644 index cd425bd6..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.java +++ /dev/null @@ -1,214 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.Intent; -import android.os.AsyncTask; -import android.os.Bundle; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.widget.TextView; -import android.widget.Toast; - -import com.anjlab.android.iab.v3.BillingProcessor; -import com.anjlab.android.iab.v3.TransactionDetails; -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.button.MaterialButton; - -import java.lang.ref.WeakReference; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.MaterialUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.BuildConfig; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.App; -import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; - -/** - * @author Hemanth S (h4h13). - */ - -public class ProVersionActivity extends AbsBaseActivity implements - BillingProcessor.IBillingHandler { - - private static final String TAG = "ProVersionActivity"; - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.restore_button) - MaterialButton restoreButton; - - @BindView(R.id.purchase_button) - MaterialButton purchaseButton; - - @BindView(R.id.app_bar) - AppBarLayout appBar; - - @BindView(R.id.title) - TextView title; - - private BillingProcessor billingProcessor; - private AsyncTask restorePurchaseAsyncTask; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_pro_version); - setDrawUnderStatusBar(); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - int primaryColor = ThemeStore.primaryColor(this); - toolbar.setBackgroundColor(primaryColor); - appBar.setBackgroundColor(primaryColor); - - toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp); - toolbar.setNavigationOnClickListener(v -> onBackPressed()); - title.setTextColor(ThemeStore.textColorPrimary(this)); - setSupportActionBar(toolbar); - setTitle(null); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - - restoreButton.setEnabled(false); - purchaseButton.setEnabled(false); - - billingProcessor = new BillingProcessor(this, BuildConfig.GOOGLE_PLAY_LICENSE_KEY, this); - - MaterialUtil.setTint(restoreButton, false); - MaterialUtil.setTint(purchaseButton, true); - - } - - private void restorePurchase() { - if (restorePurchaseAsyncTask != null) { - restorePurchaseAsyncTask.cancel(false); - } - restorePurchaseAsyncTask = new RestorePurchaseAsyncTask(this).execute(); - } - - @OnClick({R.id.restore_button, R.id.purchase_button}) - public void onViewClicked(View view) { - switch (view.getId()) { - case R.id.restore_button: - if (restorePurchaseAsyncTask == null - || restorePurchaseAsyncTask.getStatus() != AsyncTask.Status.RUNNING) { - restorePurchase(); - } - break; - case R.id.purchase_button: - billingProcessor.purchase(ProVersionActivity.this, App.PRO_VERSION_PRODUCT_ID); - break; - } - } - - @Override - public void onProductPurchased(@NonNull String productId, @Nullable TransactionDetails details) { - Toast.makeText(this, R.string.thank_you, Toast.LENGTH_SHORT).show(); - setResult(RESULT_OK); - } - - @Override - public void onPurchaseHistoryRestored() { - if (App.Companion.isProVersion()) { - Toast.makeText(this, R.string.restored_previous_purchase_please_restart, Toast.LENGTH_LONG) - .show(); - setResult(RESULT_OK); - } else { - Toast.makeText(this, R.string.no_purchase_found, Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void onBillingError(int errorCode, @Nullable Throwable error) { - Log.e(TAG, "Billing error: code = " + errorCode, error); - } - - - @Override - public void onBillingInitialized() { - restoreButton.setEnabled(true); - purchaseButton.setEnabled(true); - } - - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - if (!billingProcessor.handleActivityResult(requestCode, resultCode, data)) { - super.onActivityResult(requestCode, resultCode, data); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - break; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onDestroy() { - if (billingProcessor != null) { - billingProcessor.release(); - } - super.onDestroy(); - } - - private static class RestorePurchaseAsyncTask extends AsyncTask { - - private final WeakReference buyActivityWeakReference; - - RestorePurchaseAsyncTask(ProVersionActivity purchaseActivity) { - this.buyActivityWeakReference = new WeakReference<>(purchaseActivity); - } - - @Override - protected void onPreExecute() { - super.onPreExecute(); - ProVersionActivity purchaseActivity = buyActivityWeakReference.get(); - if (purchaseActivity != null) { - Toast.makeText(purchaseActivity, R.string.restoring_purchase, Toast.LENGTH_SHORT).show(); - } else { - cancel(false); - } - } - - @Override - protected Boolean doInBackground(Void... params) { - ProVersionActivity purchaseActivity = buyActivityWeakReference.get(); - if (purchaseActivity != null) { - return purchaseActivity.billingProcessor.loadOwnedPurchasesFromGoogle(); - } - cancel(false); - return null; - } - - @Override - protected void onPostExecute(Boolean b) { - super.onPostExecute(b); - ProVersionActivity purchaseActivity = buyActivityWeakReference.get(); - if (purchaseActivity == null || b == null) { - return; - } - - if (b) { - purchaseActivity.onPurchaseHistoryRestored(); - } else { - Toast.makeText(purchaseActivity, R.string.could_not_restore_purchase, Toast.LENGTH_SHORT) - .show(); - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.kt new file mode 100644 index 00000000..4dd03b97 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/ProVersionActivity.kt @@ -0,0 +1,167 @@ +package code.name.monkey.retromusic.ui.activities + +import android.app.Activity +import android.content.Intent +import android.os.AsyncTask +import android.os.Bundle +import android.util.Log +import android.view.MenuItem +import android.widget.Toast +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.MaterialUtil +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +import code.name.monkey.retromusic.App +import code.name.monkey.retromusic.BuildConfig +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity +import com.anjlab.android.iab.v3.BillingProcessor +import com.anjlab.android.iab.v3.TransactionDetails +import kotlinx.android.synthetic.main.activity_pro_version.* +import kotlinx.android.synthetic.main.activity_pro_version_content.* +import java.lang.ref.WeakReference + + +class ProVersionActivity : AbsBaseActivity(), BillingProcessor.IBillingHandler { + + + private var billingProcessor: BillingProcessor? = null + private var restorePurchaseAsyncTask: AsyncTask<*, *, *>? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_pro_version) + setDrawUnderStatusBar() + + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + val primaryColor = ThemeStore.primaryColor(this) + toolbar.setBackgroundColor(primaryColor) + appBarLayout.setBackgroundColor(primaryColor) + + toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp) + toolbar.setNavigationOnClickListener { v -> onBackPressed() } + bannerTitle.setTextColor(ThemeStore.textColorPrimary(this)) + setSupportActionBar(toolbar) + title = null + ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)) + + restoreButton.isEnabled = false + purchaseButton.isEnabled = false + + billingProcessor = BillingProcessor(this, BuildConfig.GOOGLE_PLAY_LICENSE_KEY, this) + + MaterialUtil.setTint(restoreButton, false) + MaterialUtil.setTint(purchaseButton, true) + + restoreButton.setOnClickListener { + if (restorePurchaseAsyncTask == null || restorePurchaseAsyncTask!!.status != AsyncTask.Status.RUNNING) { + restorePurchase() + } + + } + purchaseButton.setOnClickListener { + billingProcessor!!.purchase(this@ProVersionActivity, App.PRO_VERSION_PRODUCT_ID) + } + } + + private fun restorePurchase() { + if (restorePurchaseAsyncTask != null) { + restorePurchaseAsyncTask!!.cancel(false) + } + restorePurchaseAsyncTask = RestorePurchaseAsyncTask(this).execute() + } + + + override fun onProductPurchased(productId: String, details: TransactionDetails?) { + Toast.makeText(this, R.string.thank_you, Toast.LENGTH_SHORT).show() + setResult(Activity.RESULT_OK) + } + + override fun onPurchaseHistoryRestored() { + if (App.isProVersion) { + Toast.makeText(this, R.string.restored_previous_purchase_please_restart, Toast.LENGTH_LONG) + .show() + setResult(Activity.RESULT_OK) + } else { + Toast.makeText(this, R.string.no_purchase_found, Toast.LENGTH_SHORT).show() + } + } + + override fun onBillingError(errorCode: Int, error: Throwable?) { + Log.e(TAG, "Billing error: code = $errorCode", error) + } + + + override fun onBillingInitialized() { + restoreButton.isEnabled = true + purchaseButton.isEnabled = true + } + + + public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (!billingProcessor!!.handleActivityResult(requestCode, resultCode, data)) { + super.onActivityResult(requestCode, resultCode, data) + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + when (item.itemId) { + android.R.id.home -> finish() + } + return super.onOptionsItemSelected(item) + } + + override fun onDestroy() { + if (billingProcessor != null) { + billingProcessor!!.release() + } + super.onDestroy() + } + + private class RestorePurchaseAsyncTask internal constructor(purchaseActivity: ProVersionActivity) : AsyncTask() { + + private val buyActivityWeakReference: WeakReference = WeakReference(purchaseActivity) + + override fun onPreExecute() { + super.onPreExecute() + val purchaseActivity = buyActivityWeakReference.get() + if (purchaseActivity != null) { + Toast.makeText(purchaseActivity, R.string.restoring_purchase, Toast.LENGTH_SHORT).show() + } else { + cancel(false) + } + } + + override fun doInBackground(vararg params: Void): Boolean? { + val purchaseActivity = buyActivityWeakReference.get() + if (purchaseActivity != null) { + return purchaseActivity.billingProcessor!!.loadOwnedPurchasesFromGoogle() + } + cancel(false) + return null + } + + override fun onPostExecute(b: Boolean?) { + super.onPostExecute(b) + val purchaseActivity = buyActivityWeakReference.get() + if (purchaseActivity == null || b == null) { + return + } + + if (b) { + purchaseActivity.onPurchaseHistoryRestored() + } else { + Toast.makeText(purchaseActivity, R.string.could_not_restore_purchase, Toast.LENGTH_SHORT).show() + } + } + } + + companion object { + + private val TAG: String = "ProVersionActivity" + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.java deleted file mode 100644 index 9c31fb00..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.java +++ /dev/null @@ -1,252 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.app.SearchManager; -import android.content.ActivityNotFoundException; -import android.content.Intent; -import android.os.Bundle; -import android.speech.RecognizerIntent; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; -import androidx.appcompat.widget.SearchView.OnQueryTextListener; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.View; -import android.widget.EditText; -import android.widget.TextView; -import android.widget.TextView.BufferType; -import android.widget.Toast; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Locale; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.mvp.contract.SearchContract; -import code.name.monkey.retromusic.mvp.presenter.SearchPresenter; -import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity; -import code.name.monkey.retromusic.ui.adapter.SearchAdapter; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.util.ViewUtil; - -public class SearchActivity extends AbsMusicServiceActivity implements OnQueryTextListener, - SearchContract.SearchView, TextWatcher { - - public static final String TAG = SearchActivity.class.getSimpleName(); - public static final String QUERY = "query"; - private static final int REQ_CODE_SPEECH_INPUT = 9002; - - @BindView(R.id.voice_search) - View micIcon; - - @BindView(R.id.recycler_view) - RecyclerView recyclerView; - - @BindView(android.R.id.empty) - TextView empty; - - @BindView(R.id.search_view) - EditText searchView; - - @BindView(R.id.status_bar) - View statusBar; - - private SearchPresenter searchPresenter; - private SearchAdapter adapter; - private String query; - - @Override - protected void onCreate(Bundle savedInstanceState) { - setDrawUnderStatusBar(); - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_search); - - ButterKnife.bind(this); - - ViewUtil.setStatusBarHeight(this, statusBar); - - searchPresenter = new SearchPresenter(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - setupRecyclerview(); - setUpToolBar(); - setupSearchView(); - - if (savedInstanceState != null) { - query = savedInstanceState.getString(QUERY); - searchPresenter.search(query); - } - - if (getIntent().getBooleanExtra("mic_search", false)) { - startMicSearch(); - boolean isMicSearch = true; - } - } - - private void setupRecyclerview() { - recyclerView.setLayoutManager(new LinearLayoutManager(this)); - adapter = new SearchAdapter(this, Collections.emptyList()); - adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { - @Override - public void onChanged() { - super.onChanged(); - empty.setVisibility(adapter.getItemCount() < 1 ? View.VISIBLE : View.GONE); - } - }); - recyclerView.setAdapter(adapter); - } - - private void setupSearchView() { - SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); - if (searchManager != null) { - searchView.addTextChangedListener(this); - } - } - - @Override - protected void onResume() { - super.onResume(); - //Log.i(TAG, "onResume: " + query); - searchPresenter.subscribe(); - searchPresenter.search(query); - } - - @Override - public void onDestroy() { - super.onDestroy(); - searchPresenter.unsubscribe(); - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putString(QUERY, query); - } - - @Override - protected void onRestoreInstanceState(Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - searchPresenter.search(savedInstanceState.getString(QUERY, "")); - } - - private void setUpToolBar() { - setTitle(null); - } - - - private void search(@NonNull String query) { - this.query = query.trim(); - micIcon.setVisibility(query.length() > 0 ? View.GONE : View.VISIBLE); - searchPresenter.search(query); - } - - @Override - public void onMediaStoreChanged() { - super.onMediaStoreChanged(); - searchPresenter.search(query); - } - - @Override - public boolean onQueryTextSubmit(String query) { - hideSoftKeyboard(); - return false; - } - - @Override - public boolean onQueryTextChange(String newText) { - search(newText); - return false; - } - - private void hideSoftKeyboard() { - RetroUtil.hideSoftKeyboard(SearchActivity.this); - if (searchView != null) { - searchView.clearFocus(); - } - } - - @Override - public void loading() { - - } - - @Override - public void showEmptyView() { - adapter.swapDataSet(new ArrayList<>()); - } - - @Override - public void completed() { - - } - - @Override - public void showData(ArrayList list) { - adapter.swapDataSet(list); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - switch (requestCode) { - case REQ_CODE_SPEECH_INPUT: { - if (resultCode == RESULT_OK && null != data) { - - ArrayList result = data - .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); - query = result.get(0); - searchView.setText(query, BufferType.EDITABLE); - searchPresenter.search(query); - } - break; - } - } - } - - @OnClick({R.id.voice_search, R.id.back}) - void searchImageView(View view) { - switch (view.getId()) { - case R.id.voice_search: - startMicSearch(); - break; - case R.id.back: - finish(); - break; - } - } - - private void startMicSearch() { - Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); - intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); - intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); - intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)); - try { - startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); - } catch (ActivityNotFoundException e) { - e.printStackTrace(); - Toast.makeText(this, getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show(); - } - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence newText, int start, int before, int count) { - search(newText.toString()); - } - - @Override - public void afterTextChanged(Editable s) { - - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.kt new file mode 100644 index 00000000..31a80aef --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SearchActivity.kt @@ -0,0 +1,201 @@ +package code.name.monkey.retromusic.ui.activities + +import android.app.Activity +import android.app.SearchManager +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.speech.RecognizerIntent +import android.text.Editable +import android.text.TextWatcher +import android.view.View +import android.widget.TextView.BufferType +import android.widget.Toast +import androidx.appcompat.widget.SearchView.OnQueryTextListener +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.mvp.contract.SearchContract +import code.name.monkey.retromusic.mvp.presenter.SearchPresenter +import code.name.monkey.retromusic.ui.activities.base.AbsMusicServiceActivity +import code.name.monkey.retromusic.ui.adapter.SearchAdapter +import code.name.monkey.retromusic.util.RetroUtil +import kotlinx.android.synthetic.main.activity_search.* +import java.util.* + +class SearchActivity : AbsMusicServiceActivity(), OnQueryTextListener, SearchContract.SearchView, TextWatcher { + + private var searchPresenter: SearchPresenter? = null + private var searchAdapter: SearchAdapter? = null + private var query: String? = null + + override fun onCreate(savedInstanceState: Bundle?) { + setDrawUnderStatusBar() + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_search) + + + searchPresenter = SearchPresenter(this) + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + setupRecyclerView() + setUpToolBar() + setupSearchView() + + if (savedInstanceState != null) { + query = savedInstanceState.getString(QUERY) + searchPresenter!!.search(query!!) + } + + if (intent.getBooleanExtra("mic_search", false)) { + startMicSearch() + } + + voiceSearch.setOnClickListener { startMicSearch() } + } + + private fun setupRecyclerView() { + + searchAdapter = SearchAdapter(this, emptyList()) + searchAdapter!!.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { + override fun onChanged() { + super.onChanged() + empty.visibility = if (searchAdapter!!.itemCount < 1) View.VISIBLE else View.GONE + } + }) + recyclerView.apply { + layoutManager = LinearLayoutManager(this@SearchActivity) + adapter = searchAdapter + } + + } + + private fun setupSearchView() { + getSystemService(Context.SEARCH_SERVICE) as SearchManager + searchView.addTextChangedListener(this) + } + + override fun onResume() { + super.onResume() + searchPresenter!!.subscribe() + searchPresenter!!.search(query!!) + } + + override fun onDestroy() { + super.onDestroy() + searchPresenter!!.unsubscribe() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putString(QUERY, query) + } + + override fun onRestoreInstanceState(savedInstanceState: Bundle) { + super.onRestoreInstanceState(savedInstanceState) + searchPresenter!!.search(savedInstanceState.getString(QUERY, "")) + } + + private fun setUpToolBar() { + title = null + } + + + private fun search(query: String) { + this.query = query.trim { it <= ' ' } + voiceSearch.visibility = if (query.isNotEmpty()) View.GONE else View.VISIBLE + searchPresenter!!.search(query) + } + + override fun onMediaStoreChanged() { + super.onMediaStoreChanged() + searchPresenter!!.search(query!!) + } + + override fun onQueryTextSubmit(query: String): Boolean { + hideSoftKeyboard() + return false + } + + override fun onQueryTextChange(newText: String): Boolean { + search(newText) + return false + } + + private fun hideSoftKeyboard() { + RetroUtil.hideSoftKeyboard(this@SearchActivity) + if (searchView != null) { + searchView.clearFocus() + } + } + + override fun loading() { + + } + + override fun showEmptyView() { + searchAdapter!!.swapDataSet(ArrayList()) + } + + override fun completed() { + + } + + override fun showData(list: ArrayList) { + searchAdapter!!.swapDataSet(list) + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + when (requestCode) { + REQ_CODE_SPEECH_INPUT -> { + if (resultCode == Activity.RESULT_OK && null != data) { + + val result = data + .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) + query = result[0] + searchView.setText(query, BufferType.EDITABLE) + searchPresenter!!.search(query!!) + } + } + } + } + + private fun startMicSearch() { + val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()) + intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)) + try { + startActivityForResult(intent, REQ_CODE_SPEECH_INPUT) + } catch (e: ActivityNotFoundException) { + e.printStackTrace() + Toast.makeText(this, getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show() + } + + } + + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + + } + + override fun onTextChanged(newText: CharSequence, start: Int, before: Int, count: Int) { + search(newText.toString()) + } + + override fun afterTextChanged(s: Editable) { + + } + + companion object { + + val TAG: String = SearchActivity::class.java.simpleName + const val QUERY: String = "query" + private const val REQ_CODE_SPEECH_INPUT = 9002 + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.kt index e0fe1e00..6a480286 100755 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.kt +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SettingsActivity.kt @@ -6,7 +6,6 @@ import android.view.MenuItem import androidx.annotation.ColorInt import androidx.annotation.StringRes 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.appthemehelper.util.ToolbarContentTintHelper @@ -43,7 +42,6 @@ class SettingsActivity : AbsBaseActivity(), ColorChooserDialog.ColorCallback, Sh override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) - ButterKnife.bind(this) setStatusbarColorAuto() setNavigationbarColorAuto() 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 deleted file mode 100644 index 4d84ed6d..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.java +++ /dev/null @@ -1,379 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.Intent; -import android.content.res.ColorStateList; -import android.graphics.Paint; -import android.net.Uri; -import android.os.AsyncTask; -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ProgressBar; -import android.widget.TextView; -import android.widget.Toast; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.afollestad.materialdialogs.internal.MDTintHelper; -import com.anjlab.android.iab.v3.BillingProcessor; -import com.anjlab.android.iab.v3.SkuDetails; -import com.anjlab.android.iab.v3.TransactionDetails; -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.button.MaterialButton; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import androidx.annotation.LayoutRes; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import androidx.recyclerview.widget.DefaultItemAnimator; -import androidx.recyclerview.widget.GridLayoutManager; -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.ATHUtil; -import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper; -import code.name.monkey.retromusic.BuildConfig; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; -import code.name.monkey.retromusic.util.RetroUtil; -import code.name.monkey.retromusic.views.IconImageView; - -import static code.name.monkey.retromusic.Constants.PAYPAL_ME_URL; - -/** - * @author Hemanth S (h4h13). - */ - -public class SupportDevelopmentActivity extends AbsBaseActivity implements BillingProcessor.IBillingHandler { - public static final String TAG = SupportDevelopmentActivity.class.getSimpleName(); - private static final int DONATION_PRODUCT_IDS = R.array.donation_ids; - private static final int TEZ_REQUEST_CODE = 123; - private static final String GOOGLE_TEZ_PACKAGE_NAME = "com.google.android.apps.nbu.paisa.user"; - - @BindView(R.id.progress) - ProgressBar progressBar; - @BindView(R.id.progress_container) - View progressContainer; - @BindView(R.id.list) - RecyclerView recyclerView; - @BindView(R.id.toolbar) - Toolbar toolbar; - @BindView(R.id.app_bar) - AppBarLayout appBarLayout; - @BindView(R.id.root) - ViewGroup viewGroup; - @BindView(R.id.title) - TextView title; - @BindView(R.id.donate) - MaterialButton materialButton; - private BillingProcessor billingProcessor; - private AsyncTask skuDetailsLoadAsyncTask; - - private static List getDetails() { - List skuDetails = new ArrayList<>(); - JSONObject jsonObject = new JSONObject(); - try { - for (int i = 0; i < 6; i++) { - jsonObject.put("songTitle", "Coffee"); - jsonObject.put("price", "$100"); - jsonObject.put("description", "" + i); - skuDetails.add(new SkuDetails(jsonObject)); - } - - } catch (JSONException e) { - e.printStackTrace(); - } - - return skuDetails; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - private void donate(int i) { - final String[] ids = getResources().getStringArray(DONATION_PRODUCT_IDS); - billingProcessor.purchase(this, ids[i]); - } - - @OnClick(R.id.donate) - void donate() { - RetroUtil.openUrl(this,PAYPAL_ME_URL); - } - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_donation); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - - setupToolbar(); - - billingProcessor = new BillingProcessor(this, BuildConfig.GOOGLE_PLAY_LICENSE_KEY, this); - MDTintHelper.setTint(progressBar, ThemeStore.accentColor(this)); - - ((TextView) findViewById(R.id.donation)).setTextColor(ThemeStore.accentColor(this)); - } - - private void setupToolbar() { - title.setTextColor(ThemeStore.textColorPrimary(this)); - int primaryColor = ThemeStore.primaryColor(this); - appBarLayout.setBackgroundColor(primaryColor); - toolbar.setBackgroundColor(primaryColor); - - toolbar.setNavigationOnClickListener(view -> onBackPressed()); - toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp); - setSupportActionBar(toolbar); - setTitle(null); - - materialButton.setBackgroundTintList(ColorStateList.valueOf(ThemeStore.accentColor(this))); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - } - - @Override - public void onBillingInitialized() { - loadSkuDetails(); - } - - private void loadSkuDetails() { - if (skuDetailsLoadAsyncTask != null) { - skuDetailsLoadAsyncTask.cancel(false); - } - skuDetailsLoadAsyncTask = new SkuDetailsLoadAsyncTask(this).execute(); - - } - - @Override - public void onProductPurchased(@NonNull String productId, TransactionDetails details) { - //loadSkuDetails(); - Toast.makeText(this, R.string.thank_you, Toast.LENGTH_SHORT).show(); - } - - @Override - public void onBillingError(int errorCode, Throwable error) { - Log.e(TAG, "Billing error: code = " + errorCode, error); - } - - @Override - public void onPurchaseHistoryRestored() { - //loadSkuDetails(); - Toast.makeText(this, R.string.restored_previous_purchases, Toast.LENGTH_SHORT).show(); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - if (!billingProcessor.handleActivityResult(requestCode, resultCode, data)) { - super.onActivityResult(requestCode, resultCode, data); - } - if (requestCode == TEZ_REQUEST_CODE) { - // Process based on the data in response. - Log.d("result", data.getStringExtra("Status")); - } - } - - @Override - public void onDestroy() { - if (billingProcessor != null) { - billingProcessor.release(); - } - if (skuDetailsLoadAsyncTask != null) { - skuDetailsLoadAsyncTask.cancel(true); - } - super.onDestroy(); - } - - @OnClick(R.id.google_pay) - void googlePay() { - - new MaterialDialog.Builder(this) - .title(R.string.support_development) - .input("Enter amount", null, false, (dialog, input) -> { - Uri uri = new Uri.Builder() - .scheme("upi") - .authority("pay") - .appendQueryParameter("pa", "hemanth.vaniraviram@okaxis") - .appendQueryParameter("pn", "Retro Music") - .appendQueryParameter("mc", "1234") - .appendQueryParameter("tr", "7406201323") - .appendQueryParameter("tn", "Retro Music Player Donation") - .appendQueryParameter("am", "10.01") - .appendQueryParameter("cu", "INR") - .build(); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setData(uri); - intent.setPackage(GOOGLE_TEZ_PACKAGE_NAME); - startActivityForResult(intent, TEZ_REQUEST_CODE); - }).positiveText("Donate") - .onPositive((dialog, which) -> { - - }).show(); - } - - private static class SkuDetailsLoadAsyncTask extends AsyncTask> { - private final WeakReference donationDialogWeakReference; - - SkuDetailsLoadAsyncTask(SupportDevelopmentActivity donationsDialog) { - this.donationDialogWeakReference = new WeakReference<>(donationsDialog); - } - - @Override - protected void onPreExecute() { - super.onPreExecute(); - SupportDevelopmentActivity dialog = donationDialogWeakReference.get(); - if (dialog == null) return; - - dialog.progressContainer.setVisibility(View.VISIBLE); - dialog.recyclerView.setVisibility(View.GONE); - } - - @Override - protected List doInBackground(Void... params) { - SupportDevelopmentActivity dialog = donationDialogWeakReference.get(); - if (dialog != null) { - final String[] ids = dialog.getResources().getStringArray(DONATION_PRODUCT_IDS); - return dialog.billingProcessor.getPurchaseListingDetails(new ArrayList<>(Arrays.asList(ids))); - } - cancel(false); - return null; - } - - @Override - protected void onPostExecute(List skuDetails) { - super.onPostExecute(skuDetails); - SupportDevelopmentActivity dialog = donationDialogWeakReference.get(); - if (dialog == null) return; - - if (skuDetails == null || skuDetails.isEmpty()) { - dialog.progressContainer.setVisibility(View.GONE); - return; - } - - //noinspection ConstantConditions - dialog.progressContainer.setVisibility(View.GONE); - dialog.recyclerView.setItemAnimator(new DefaultItemAnimator()); - dialog.recyclerView.setLayoutManager(new GridLayoutManager(dialog, 2)); - dialog.recyclerView.setAdapter(new SkuDetailsAdapter(dialog, skuDetails)); - dialog.recyclerView.setVisibility(View.VISIBLE); - } - - - } - - static class SkuDetailsAdapter extends RecyclerView.Adapter { - @LayoutRes - private static int LAYOUT_RES_ID = R.layout.item_donation_option; - - SupportDevelopmentActivity donationsDialog; - List skuDetailsList = new ArrayList<>(); - - SkuDetailsAdapter(@NonNull SupportDevelopmentActivity donationsDialog, @NonNull List objects) { - this.donationsDialog = donationsDialog; - skuDetailsList = objects; - } - - private static void strikeThrough(TextView textView, boolean strikeThrough) { - textView.setPaintFlags(strikeThrough ? textView.getPaintFlags() | - Paint.STRIKE_THRU_TEXT_FLAG : textView.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); - } - - private int getIcon(int position) { - switch (position) { - case 0: - return R.drawable.ic_cookie_white_24dp; - case 1: - return R.drawable.ic_take_away_white_24dp; - case 2: - return R.drawable.ic_take_away_coffe_white_24dp; - case 3: - return R.drawable.ic_beer_white_24dp; - case 4: - return R.drawable.ic_fast_food_meal_white_24dp; - case 5: - return R.drawable.ic_popcorn_white_24dp; - case 6: - return R.drawable.ic_card_giftcard_white_24dp; - default: - return R.drawable.ic_card_giftcard_white_24dp; - } - } - - @NonNull - @Override - public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { - return new ViewHolder(LayoutInflater.from(donationsDialog) - .inflate(LAYOUT_RES_ID, viewGroup, false)); - } - - @Override - public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) { - SkuDetails skuDetails = skuDetailsList.get(i); - if (skuDetails != null) { - viewHolder.title.setText(skuDetails.title.replace("(Retro Music Player)", "").trim()); - viewHolder.text.setText(skuDetails.description); - viewHolder.text.setVisibility(View.GONE); - viewHolder.price.setText(skuDetails.priceText); - viewHolder.image.setImageResource(getIcon(i)); - - final boolean purchased = donationsDialog.billingProcessor.isPurchased(skuDetails.productId); - int titleTextColor = purchased ? ATHUtil.resolveColor(donationsDialog, android.R.attr.textColorHint) : ThemeStore.textColorPrimary(donationsDialog); - int contentTextColor = purchased ? titleTextColor : ThemeStore.textColorSecondary(donationsDialog); - - //noinspection ResourceAsColor - viewHolder.title.setTextColor(titleTextColor); - viewHolder.text.setTextColor(contentTextColor); - viewHolder.price.setTextColor(titleTextColor); - - strikeThrough(viewHolder.title, purchased); - strikeThrough(viewHolder.text, purchased); - strikeThrough(viewHolder.price, purchased); - - viewHolder.itemView.setOnTouchListener((v, event) -> purchased); - viewHolder.itemView.setOnClickListener(v -> donationsDialog.donate(i)); - } - } - - @Override - public int getItemCount() { - return skuDetailsList.size(); - } - - static class ViewHolder extends RecyclerView.ViewHolder { - @BindView(R.id.title) - TextView title; - @BindView(R.id.text) - TextView text; - @BindView(R.id.price) - TextView price; - @BindView(R.id.image) - IconImageView image; - - public ViewHolder(View view) { - super(view); - ButterKnife.bind(this, view); - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.kt new file mode 100644 index 00000000..5a7cd13d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/SupportDevelopmentActivity.kt @@ -0,0 +1,252 @@ +package code.name.monkey.retromusic.ui.activities + +import android.content.Intent +import android.content.res.ColorStateList +import android.graphics.Paint +import android.os.AsyncTask +import android.os.Bundle +import android.util.Log +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import android.widget.Toast +import androidx.annotation.LayoutRes +import androidx.recyclerview.widget.DefaultItemAnimator +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.ThemeStore +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.BuildConfig +import code.name.monkey.retromusic.Constants.PAYPAL_ME_URL +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity +import code.name.monkey.retromusic.util.RetroUtil +import code.name.monkey.retromusic.views.IconImageView +import com.anjlab.android.iab.v3.BillingProcessor +import com.anjlab.android.iab.v3.SkuDetails +import com.anjlab.android.iab.v3.TransactionDetails +import kotlinx.android.synthetic.main.activity_donation.* +import java.lang.ref.WeakReference +import java.util.* + +class SupportDevelopmentActivity : AbsBaseActivity(), BillingProcessor.IBillingHandler { + + + companion object { + val TAG: String = SupportDevelopmentActivity::class.java.simpleName + const val DONATION_PRODUCT_IDS = R.array.donation_ids + private const val TEZ_REQUEST_CODE = 123 + } + + var billingProcessor: BillingProcessor? = null + private var skuDetailsLoadAsyncTask: AsyncTask<*, *, *>? = null + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + onBackPressed() + return true + } + return super.onOptionsItemSelected(item) + } + + fun donate(i: Int) { + val ids = resources.getStringArray(DONATION_PRODUCT_IDS) + billingProcessor!!.purchase(this, ids[i]) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_donation) + + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + setupToolbar() + + billingProcessor = BillingProcessor(this, BuildConfig.GOOGLE_PLAY_LICENSE_KEY, this) + TintHelper.setTint(progress, ThemeStore.accentColor(this)) + donation.setTextColor(ThemeStore.accentColor(this)) + donate.setOnClickListener { + RetroUtil.openUrl(this, PAYPAL_ME_URL) + } + } + + private fun setupToolbar() { + bannerTitle.setTextColor(ThemeStore.textColorPrimary(this)) + val primaryColor = ThemeStore.primaryColor(this) + appBarLayout.setBackgroundColor(primaryColor) + toolbar.setBackgroundColor(primaryColor) + + toolbar.setNavigationOnClickListener { onBackPressed() } + toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp) + setSupportActionBar(toolbar) + title = null + + donate.backgroundTintList = ColorStateList.valueOf(ThemeStore.accentColor(this)) + ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)) + } + + override fun onBillingInitialized() { + loadSkuDetails() + } + + private fun loadSkuDetails() { + if (skuDetailsLoadAsyncTask != null) { + skuDetailsLoadAsyncTask!!.cancel(false) + } + skuDetailsLoadAsyncTask = SkuDetailsLoadAsyncTask(this).execute() + + } + + override fun onProductPurchased(productId: String, details: TransactionDetails?) { + //loadSkuDetails(); + Toast.makeText(this, R.string.thank_you, Toast.LENGTH_SHORT).show() + } + + override fun onBillingError(errorCode: Int, error: Throwable?) { + Log.e(TAG, "Billing error: code = $errorCode", error) + } + + override fun onPurchaseHistoryRestored() { + //loadSkuDetails(); + Toast.makeText(this, R.string.restored_previous_purchases, Toast.LENGTH_SHORT).show() + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (!billingProcessor!!.handleActivityResult(requestCode, resultCode, data)) { + super.onActivityResult(requestCode, resultCode, data) + } + if (requestCode == TEZ_REQUEST_CODE) { + // Process based on the data in response. + Log.d("result", data!!.getStringExtra("Status")) + } + } + + override fun onDestroy() { + if (billingProcessor != null) { + billingProcessor!!.release() + } + if (skuDetailsLoadAsyncTask != null) { + skuDetailsLoadAsyncTask!!.cancel(true) + } + super.onDestroy() + } +} + +private class SkuDetailsLoadAsyncTask internal constructor(supportDevelopmentActivity: SupportDevelopmentActivity) : AsyncTask>() { + private val weakReference: WeakReference = WeakReference(supportDevelopmentActivity) + + override fun onPreExecute() { + super.onPreExecute() + val supportDevelopmentActivity = weakReference.get() ?: return + + supportDevelopmentActivity.progressContainer.visibility = View.VISIBLE + supportDevelopmentActivity.recyclerView.visibility = View.GONE + } + + override fun doInBackground(vararg params: Void): List? { + val dialog = weakReference.get() + if (dialog != null) { + val ids = dialog.resources.getStringArray(SupportDevelopmentActivity.DONATION_PRODUCT_IDS) + return dialog.billingProcessor!!.getPurchaseListingDetails(ArrayList(Arrays.asList(*ids))) + } + cancel(false) + return null + } + + override fun onPostExecute(skuDetails: List?) { + super.onPostExecute(skuDetails) + val dialog = weakReference.get() ?: return + + if (skuDetails == null || skuDetails.isEmpty()) { + dialog.progressContainer.visibility = View.GONE + return + } + + dialog.progressContainer.visibility = View.GONE + dialog.recyclerView.itemAnimator = DefaultItemAnimator() + dialog.recyclerView.layoutManager = GridLayoutManager(dialog, 2) + dialog.recyclerView.adapter = SkuDetailsAdapter(dialog, skuDetails) + dialog.recyclerView.visibility = View.VISIBLE + } +} + +class SkuDetailsAdapter(private var donationsDialog: SupportDevelopmentActivity, objects: List) : RecyclerView.Adapter() { + private var skuDetailsList: List = ArrayList() + + init { + skuDetailsList = objects + } + + private fun getIcon(position: Int): Int { + return when (position) { + 0 -> R.drawable.ic_cookie_white_24dp + 1 -> R.drawable.ic_take_away_white_24dp + 2 -> R.drawable.ic_take_away_coffe_white_24dp + 3 -> R.drawable.ic_beer_white_24dp + 4 -> R.drawable.ic_fast_food_meal_white_24dp + 5 -> R.drawable.ic_popcorn_white_24dp + 6 -> R.drawable.ic_card_giftcard_white_24dp + else -> R.drawable.ic_card_giftcard_white_24dp + } + } + + override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { + return ViewHolder(LayoutInflater.from(donationsDialog).inflate(LAYOUT_RES_ID, viewGroup, false)) + } + + override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) { + val skuDetails = skuDetailsList[i] + viewHolder.title.text = skuDetails.title.replace("(Retro Music Player)", "").trim { it <= ' ' } + viewHolder.text.text = skuDetails.description + viewHolder.text.visibility = View.GONE + viewHolder.price.text = skuDetails.priceText + viewHolder.image.setImageResource(getIcon(i)) + + val purchased = donationsDialog.billingProcessor!!.isPurchased(skuDetails.productId) + val titleTextColor = if (purchased) ATHUtil.resolveColor(donationsDialog, android.R.attr.textColorHint) else ThemeStore.textColorPrimary(donationsDialog) + val contentTextColor = if (purchased) titleTextColor else ThemeStore.textColorSecondary(donationsDialog) + + + viewHolder.title.setTextColor(titleTextColor) + viewHolder.text.setTextColor(contentTextColor) + viewHolder.price.setTextColor(titleTextColor) + + strikeThrough(viewHolder.title, purchased) + strikeThrough(viewHolder.text, purchased) + strikeThrough(viewHolder.price, purchased) + + viewHolder.itemView.setOnTouchListener { _, _ -> purchased } + viewHolder.itemView.setOnClickListener { donationsDialog.donate(i) } + } + + override fun getItemCount(): Int { + return skuDetailsList.size + } + + class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { + var title: TextView = view.findViewById(R.id.itemTitle) + var text: TextView = view.findViewById(R.id.itemText) + var price: TextView = view.findViewById(R.id.itemPrice) + var image: IconImageView = view.findViewById(R.id.itemImage) + } + + companion object { + @LayoutRes + private val LAYOUT_RES_ID = R.layout.item_donation_option + + private fun strikeThrough(textView: TextView, strikeThrough: Boolean) { + textView.paintFlags = if (strikeThrough) + textView.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + else + textView.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.java deleted file mode 100644 index 489d0bd9..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.java +++ /dev/null @@ -1,296 +0,0 @@ -package code.name.monkey.retromusic.ui.activities; - -import android.content.Context; -import android.content.ContextWrapper; -import android.content.Intent; -import android.graphics.Bitmap; -import android.net.Uri; -import android.os.Bundle; -import android.provider.MediaStore; -import android.provider.MediaStore.Images.Media; -import android.text.TextUtils; -import android.view.MenuItem; -import android.view.View; -import android.widget.ImageView; -import android.widget.TextView; -import android.widget.Toast; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.floatingactionbutton.FloatingActionButton; -import com.google.android.material.textfield.TextInputEditText; -import com.google.android.material.textfield.TextInputLayout; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; - -import androidx.appcompat.widget.Toolbar; -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import code.name.monkey.appthemehelper.ThemeStore; -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.Compressor; -import code.name.monkey.retromusic.util.ImageUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; -import code.name.monkey.retromusic.views.CircularImageView; -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 UserInfoActivity extends AbsBaseActivity { - - private static final int PICK_IMAGE_REQUEST = 9002; - private static final int PICK_BANNER_REQUEST = 9003; - private static final int PROFILE_ICON_SIZE = 400; - @BindView(R.id.title) - TextView title; - - @BindView(R.id.name_container) - TextInputLayout nameLayout; - - @BindView(R.id.name) - TextInputEditText name; - - @BindView(R.id.user_image) - CircularImageView userImage; - - @BindView(R.id.banner_image) - ImageView image; - - @BindView(R.id.next) - FloatingActionButton nextButton; - - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.app_bar) - AppBarLayout appBarLayout; - - private CompositeDisposable disposable; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_user_info); - ButterKnife.bind(this); - - setStatusbarColorAuto(); - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - setLightNavigationBar(true); - - setupToolbar(); - - disposable = new CompositeDisposable(); - - title.setTextColor(ThemeStore.textColorPrimary(this)); - nameLayout.setBoxStrokeColor(ThemeStore.accentColor(this)); - name.setText(PreferenceUtil.getInstance().getUserName()); - - if (!PreferenceUtil.getInstance().getProfileImage().isEmpty()) { - loadImageFromStorage(PreferenceUtil.getInstance().getProfileImage()); - } - if (!PreferenceUtil.getInstance().getBannerImage().isEmpty()) { - loadBannerFromStorage(PreferenceUtil.getInstance().getBannerImage()); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - } - return super.onOptionsItemSelected(item); - } - - private void setupToolbar() { - int primaryColor = ThemeStore.primaryColor(this); - toolbar.setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp); - toolbar.setBackgroundColor(primaryColor); - appBarLayout.setBackgroundColor(primaryColor); - ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)); - setTitle(null); - setSupportActionBar(toolbar); - } - - @OnClick({R.id.next, R.id.banner_select}) - void next(View view) { - switch (view.getId()) { - case R.id.banner_select: - showBannerOptions(); - break; - case R.id.next: - String nameString = name.getText().toString().trim(); - if (TextUtils.isEmpty(nameString)) { - Toast.makeText(this, "Umm name is empty", Toast.LENGTH_SHORT).show(); - return; - } - //noinspection ConstantConditions - PreferenceUtil.getInstance().setUserName(nameString); - setResult(RESULT_OK); - //((UserInfoActivity) getActivity()).setFragment(new ChooseThemeFragment(), true); - finish(); - break; - } - } - - private void showBannerOptions() { - //noinspection ConstantConditions - new MaterialDialog.Builder(this) - .title(R.string.select_banner_photo) - .items(Arrays.asList(getString(R.string.new_banner_photo), - getString(R.string.remove_banner_photo))) - .itemsCallback((dialog, itemView, position, text) -> { - switch (position) { - case 0: - selectBannerImage(); - break; - case 1: - PreferenceUtil.getInstance().setBannerImagePath(""); - break; - } - }).show(); - } - - private void selectBannerImage() { - //noinspection ConstantConditions - if (PreferenceUtil.getInstance().getBannerImage().isEmpty()) { - Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); - pickImageIntent.setType("image/*"); - pickImageIntent.putExtra("crop", "true"); - pickImageIntent.putExtra("outputX", 1290); - pickImageIntent.putExtra("outputY", 720); - pickImageIntent.putExtra("aspectX", 16); - pickImageIntent.putExtra("aspectY", 9); - pickImageIntent.putExtra("scale", true); - //intent.setAction(Intent.ACTION_GET_CONTENT); - startActivityForResult(Intent.createChooser(pickImageIntent, - "Select Picture"), PICK_BANNER_REQUEST); - } else { - PreferenceUtil.getInstance().setBannerImagePath(""); - image.setImageResource(android.R.color.transparent); - } - } - - @OnClick(R.id.user_image) - public void onViewClicked() { - //noinspection ConstantConditions - new MaterialDialog.Builder(this) - .title("Set a profile photo") - .items(Arrays.asList(getString(R.string.new_profile_photo), getString(R.string.remove_profile_photo))) - .itemsCallback((dialog, itemView, position, text) -> { - switch (position) { - case 0: - pickNewPhoto(); - break; - case 1: - PreferenceUtil.getInstance().saveProfileImage(""); - break; - } - }).show(); - } - - private void pickNewPhoto() { - Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); - pickImageIntent.setType("image/*"); - pickImageIntent.putExtra("crop", "true"); - pickImageIntent.putExtra("outputX", 512); - pickImageIntent.putExtra("outputY", 512); - pickImageIntent.putExtra("aspectX", 1); - pickImageIntent.putExtra("aspectY", 1); - pickImageIntent.putExtra("scale", true); - startActivityForResult(Intent.createChooser(pickImageIntent, "Select Picture"), - PICK_IMAGE_REQUEST); - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && - data.getData() != null) { - Uri uri = data.getData(); - try { - Bitmap bitmap = ImageUtil.getResizedBitmap(Media.getBitmap(getContentResolver(), uri), PROFILE_ICON_SIZE); - String profileImagePath = saveToInternalStorage(bitmap, USER_PROFILE); - PreferenceUtil.getInstance().saveProfileImage(profileImagePath); - loadImageFromStorage(profileImagePath); - - } catch (IOException e) { - e.printStackTrace(); - } - } - if (requestCode == PICK_BANNER_REQUEST && resultCode == RESULT_OK && data != null && - data.getData() != null) { - Uri uri = data.getData(); - try { - Bitmap bitmap = Media.getBitmap(getContentResolver(), uri); - String profileImagePath = saveToInternalStorage(bitmap, USER_BANNER); - PreferenceUtil.getInstance().setBannerImagePath(profileImagePath); - loadBannerFromStorage(profileImagePath); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private void loadBannerFromStorage(String profileImagePath) { - disposable.add(new Compressor(this) - .setQuality(100) - .setCompressFormat(Bitmap.CompressFormat.WEBP) - .compressToBitmapAsFlowable(new File(profileImagePath, USER_BANNER)) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(bitmap -> { - image.setImageBitmap(bitmap); - })); - } - - private void loadImageFromStorage(String path) { - disposable.add(new Compressor(this) - .setMaxHeight(300) - .setMaxWidth(300) - .setQuality(75) - .setCompressFormat(Bitmap.CompressFormat.WEBP) - .compressToBitmapAsFlowable(new File(path, USER_PROFILE)) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(bitmap -> { - userImage.setImageBitmap(bitmap); - })); - } - - private String saveToInternalStorage(Bitmap bitmapImage, String userBanner) { - ContextWrapper cw = new ContextWrapper(this); - // path to /data/data/yourapp/app_data/imageDir - File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); - // Create imageDir - File mypath = new File(directory, userBanner); - - FileOutputStream fos = null; - try { - fos = new FileOutputStream(mypath); - // Use the compress method on the BitMap object to write image to the OutputStream - bitmapImage.compress(Bitmap.CompressFormat.WEBP, 100, fos); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (fos != null) { - fos.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - return directory.getAbsolutePath(); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.kt new file mode 100644 index 00000000..182e4c23 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/UserInfoActivity.kt @@ -0,0 +1,233 @@ +package code.name.monkey.retromusic.ui.activities + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.graphics.Bitmap +import android.os.Bundle +import android.provider.MediaStore +import android.provider.MediaStore.Images.Media +import android.text.TextUtils +import android.view.MenuItem +import android.widget.Toast +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.ToolbarContentTintHelper +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.ui.activities.base.AbsBaseActivity +import code.name.monkey.retromusic.util.Compressor +import code.name.monkey.retromusic.util.ImageUtil +import code.name.monkey.retromusic.util.PreferenceUtil +import com.afollestad.materialdialogs.MaterialDialog +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import kotlinx.android.synthetic.main.activity_user_info.* +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.util.* + +class UserInfoActivity : AbsBaseActivity() { + + private var disposable: CompositeDisposable? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_user_info) + + + setStatusbarColorAuto() + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + setLightNavigationBar(true) + + setupToolbar() + + disposable = CompositeDisposable() + + bannerTitle.setTextColor(ThemeStore.textColorPrimary(this)) + nameContainer.boxStrokeColor = ThemeStore.accentColor(this) + name!!.setText(PreferenceUtil.getInstance().userName) + + if (!PreferenceUtil.getInstance().profileImage.isEmpty()) { + loadImageFromStorage(PreferenceUtil.getInstance().profileImage) + } + if (!PreferenceUtil.getInstance().bannerImage.isEmpty()) { + loadBannerFromStorage(PreferenceUtil.getInstance().bannerImage) + } + bannerImage.setOnClickListener { + MaterialDialog.Builder(this) + .title("Set a profile photo") + .items(Arrays.asList(getString(R.string.new_profile_photo), getString(R.string.remove_profile_photo))) + .itemsCallback { _, _, position, _ -> + when (position) { + 0 -> pickNewPhoto() + 1 -> PreferenceUtil.getInstance().saveProfileImage("") + } + }.show() + } + bannerSelect.setOnClickListener { + showBannerOptions() + } + next.setOnClickListener { + val nameString = name!!.text!!.toString().trim { it <= ' ' } + if (TextUtils.isEmpty(nameString)) { + Toast.makeText(this, "Umm name is empty", Toast.LENGTH_SHORT).show() + return@setOnClickListener + } + PreferenceUtil.getInstance().userName = nameString + setResult(Activity.RESULT_OK) + finish() + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + onBackPressed() + } + return super.onOptionsItemSelected(item) + } + + private fun setupToolbar() { + val primaryColor = ThemeStore.primaryColor(this) + toolbar.apply { + setNavigationIcon(R.drawable.ic_keyboard_backspace_black_24dp) + setBackgroundColor(primaryColor) + } + appBarLayout.setBackgroundColor(primaryColor) + ToolbarContentTintHelper.colorBackButton(toolbar, ThemeStore.accentColor(this)) + title = null + setSupportActionBar(toolbar) + } + + private fun showBannerOptions() { + + MaterialDialog.Builder(this) + .title(R.string.select_banner_photo) + .items(Arrays.asList(getString(R.string.new_banner_photo), + getString(R.string.remove_banner_photo))) + .itemsCallback { _, _, position, _ -> + when (position) { + 0 -> selectBannerImage() + 1 -> PreferenceUtil.getInstance().setBannerImagePath("") + } + }.show() + } + + private fun selectBannerImage() { + + if (PreferenceUtil.getInstance().bannerImage.isEmpty()) { + val pickImageIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) + pickImageIntent.type = "image/*" + pickImageIntent.putExtra("crop", "true") + pickImageIntent.putExtra("outputX", 1290) + pickImageIntent.putExtra("outputY", 720) + pickImageIntent.putExtra("aspectX", 16) + pickImageIntent.putExtra("aspectY", 9) + pickImageIntent.putExtra("scale", true) + //intent.setAction(Intent.ACTION_GET_CONTENT); + startActivityForResult(Intent.createChooser(pickImageIntent, + "Select Picture"), PICK_BANNER_REQUEST) + } else { + PreferenceUtil.getInstance().setBannerImagePath("") + bannerImage.setImageResource(android.R.color.transparent) + } + } + + + private fun pickNewPhoto() { + val pickImageIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) + pickImageIntent.type = "image/*" + pickImageIntent.putExtra("crop", "true") + pickImageIntent.putExtra("outputX", 512) + pickImageIntent.putExtra("outputY", 512) + pickImageIntent.putExtra("aspectX", 1) + pickImageIntent.putExtra("aspectY", 1) + pickImageIntent.putExtra("scale", true) + startActivityForResult(Intent.createChooser(pickImageIntent, "Select Picture"), PICK_IMAGE_REQUEST) + } + + public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && + data.data != null) { + val uri = data.data + try { + val bitmap = ImageUtil.getResizedBitmap(Media.getBitmap(contentResolver, uri), PROFILE_ICON_SIZE) + val profileImagePath = saveToInternalStorage(bitmap, USER_PROFILE) + PreferenceUtil.getInstance().saveProfileImage(profileImagePath) + loadImageFromStorage(profileImagePath) + + } catch (e: IOException) { + e.printStackTrace() + } + + } + if (requestCode == PICK_BANNER_REQUEST && resultCode == Activity.RESULT_OK && data != null && + data.data != null) { + val uri = data.data + try { + val bitmap = Media.getBitmap(contentResolver, uri) + val profileImagePath = saveToInternalStorage(bitmap, USER_BANNER) + PreferenceUtil.getInstance().setBannerImagePath(profileImagePath) + loadBannerFromStorage(profileImagePath) + } catch (e: IOException) { + e.printStackTrace() + } + + } + } + + private fun loadBannerFromStorage(profileImagePath: String) { + disposable!!.add(Compressor(this) + .setQuality(100) + .setCompressFormat(Bitmap.CompressFormat.WEBP) + .compressToBitmapAsFlowable(File(profileImagePath, USER_BANNER)) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe { bitmap -> bannerImage.setImageBitmap(bitmap) }) + } + + private fun loadImageFromStorage(path: String) { + disposable!!.add(Compressor(this) + .setMaxHeight(300) + .setMaxWidth(300) + .setQuality(75) + .setCompressFormat(Bitmap.CompressFormat.WEBP) + .compressToBitmapAsFlowable(File(path, USER_PROFILE)) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe { bitmap -> userImage!!.setImageBitmap(bitmap) }) + } + + private fun saveToInternalStorage(bitmapImage: Bitmap, userBanner: String): String { + val cw = ContextWrapper(this) + val directory = cw.getDir("imageDir", Context.MODE_PRIVATE) + val myPath = File(directory, userBanner) + var fos: FileOutputStream? = null + try { + fos = FileOutputStream(myPath) + // Use the compress method on the BitMap object to write image to the OutputStream + bitmapImage.compress(Bitmap.CompressFormat.WEBP, 100, fos) + } catch (e: Exception) { + e.printStackTrace() + } finally { + try { + fos?.close() + } catch (e: IOException) { + e.printStackTrace() + } + } + return directory.absolutePath + } + + companion object { + + private val PICK_IMAGE_REQUEST = 9002 + private val PICK_BANNER_REQUEST = 9003 + private val PROFILE_ICON_SIZE = 400 + } +} 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 index d8a6d492..58f1d66a 100644 --- 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 @@ -3,7 +3,6 @@ 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 @@ -36,7 +35,7 @@ class WhatsNewActivity : AbsBaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_whats_new) - ButterKnife.bind(this) + setStatusbarColorAuto() setNavigationbarColorAuto() 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 index 219152fe..da5b2ff6 100644 --- 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 @@ -11,7 +11,6 @@ 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 @@ -63,7 +62,6 @@ abstract class AbsSlidingMusicPanelActivity protected constructor() : AbsMusicSe 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); diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.java deleted file mode 100755 index f7db9945..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.java +++ /dev/null @@ -1,375 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.tageditor; - -import android.app.SearchManager; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.net.Uri; -import android.os.Bundle; -import android.util.Log; -import android.view.MenuItem; -import android.view.View; -import android.view.animation.OvershootInterpolator; -import android.widget.FrameLayout; -import android.widget.ImageView; - -import com.afollestad.materialdialogs.MaterialDialog; -import com.google.android.material.floatingactionbutton.FloatingActionButton; - -import org.jaudiotagger.audio.AudioFile; -import org.jaudiotagger.audio.AudioFileIO; -import org.jaudiotagger.tag.FieldKey; -import org.jaudiotagger.tag.images.Artwork; - -import java.io.File; -import java.util.List; -import java.util.Map; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import butterknife.BindView; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -import code.name.monkey.appthemehelper.util.TintHelper; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity; -import code.name.monkey.retromusic.util.RetroUtil; - -public abstract class AbsTagEditorActivity extends AbsBaseActivity { - - public static final String EXTRA_ID = "extra_id"; - public static final String EXTRA_PALETTE = "extra_palette"; - private static final String TAG = AbsTagEditorActivity.class.getSimpleName(); - private static final int REQUEST_CODE_SELECT_IMAGE = 1000; - @BindView(R.id.save_fab) - FloatingActionButton save; - - @BindView(R.id.image) - ImageView image; - - @BindView(R.id.image_container) - FrameLayout imageContainer; - - CharSequence[] items; - private int id; - private int paletteColorPrimary; - private boolean isInNoImageMode; - private List songPaths; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(getContentViewLayout()); - ButterKnife.bind(this); - - getIntentExtras(); - - songPaths = getSongPaths(); - if (songPaths.isEmpty()) { - finish(); - return; - } - - setUpViews(); - - - setNavigationbarColorAuto(); - setTaskDescriptionColorAuto(); - } - - private void setUpViews() { - setUpScrollView(); - setUpFab(); - setUpImageView(); - } - - private void setUpScrollView() { - //observableScrollView.setScrollViewCallbacks(observableScrollViewCallbacks); - } - - private void setUpImageView() { - loadCurrentImage(); - items = new CharSequence[]{ - getString(R.string.download_from_last_fm), - getString(R.string.pick_from_local_storage), - getString(R.string.web_search), - getString(R.string.remove_cover) - }; - image.setOnClickListener(v -> getShow()); - } - - protected MaterialDialog getShow() { - return new MaterialDialog.Builder(AbsTagEditorActivity.this) - .title(R.string.update_image) - .items(items) - .itemsCallback((dialog, itemView, position, text) -> { - switch (position) { - case 0: - getImageFromLastFM(); - break; - case 1: - startImagePicker(); - break; - case 2: - searchImageOnWeb(); - break; - case 3: - deleteImage(); - break; - } - }).show(); - } - - private void startImagePicker() { - Intent intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.setType("image/*"); - startActivityForResult( - Intent.createChooser(intent, getString(R.string.pick_from_local_storage)), - REQUEST_CODE_SELECT_IMAGE); - } - - protected abstract void loadCurrentImage(); - - protected abstract void getImageFromLastFM(); - - protected abstract void searchImageOnWeb(); - - protected abstract void deleteImage(); - - private void setUpFab() { - save.setScaleX(0); - save.setScaleY(0); - save.setEnabled(false); - save.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - save(); - } - }); - - TintHelper.setTintAuto(save, ThemeStore.accentColor(this), true); - } - - protected abstract void save(); - - private void getIntentExtras() { - Bundle intentExtras = getIntent().getExtras(); - if (intentExtras != null) { - id = intentExtras.getInt(EXTRA_ID); - } - } - - protected abstract int getContentViewLayout(); - - @NonNull - protected abstract List getSongPaths(); - - protected void searchWebFor(String... keys) { - StringBuilder stringBuilder = new StringBuilder(); - for (String key : keys) { - stringBuilder.append(key); - stringBuilder.append(" "); - } - Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); - intent.putExtra(SearchManager.QUERY, stringBuilder.toString()); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - - startActivity(intent); - } - - @Override - public boolean onOptionsItemSelected(@NonNull MenuItem item) { - int id = item.getItemId(); - switch (id) { - case android.R.id.home: - super.onBackPressed(); - return true; - } - return super.onOptionsItemSelected(item); - } - - protected void setNoImageMode() { - isInNoImageMode = true; - imageContainer.setVisibility(View.GONE); - image.setVisibility(View.GONE); - image.setEnabled(false); - - setColors(getIntent().getIntExtra(EXTRA_PALETTE, ThemeStore.primaryColor(this))); - } - - protected void dataChanged() { - showFab(); - } - - private void showFab() { - save.animate() - .setDuration(500) - .setInterpolator(new OvershootInterpolator()) - .scaleX(1) - .scaleY(1) - .start(); - save.setEnabled(true); - } - - protected void setImageBitmap(@Nullable final Bitmap bitmap, int bgColor) { - if (bitmap == null) { - image.setImageResource(R.drawable.default_album_art); - } else { - image.setImageBitmap(bitmap); - } - setColors(bgColor); - } - - protected void setColors(int color) { - paletteColorPrimary = color; - } - - protected void writeValuesToFiles(@NonNull final Map fieldKeyValueMap, - @Nullable final ArtworkInfo artworkInfo) { - RetroUtil.hideSoftKeyboard(this); - - new WriteTagsAsyncTask(this) - .execute(new WriteTagsAsyncTask.LoadingInfo(getSongPaths(), fieldKeyValueMap, artworkInfo)); - } - - protected int getId() { - return id; - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, - @NonNull Intent imageReturnedIntent) { - super.onActivityResult(requestCode, resultCode, imageReturnedIntent); - switch (requestCode) { - case REQUEST_CODE_SELECT_IMAGE: - if (resultCode == RESULT_OK) { - Uri selectedImage = imageReturnedIntent.getData(); - loadImageFromFile(selectedImage); - } - break; - } - } - - protected abstract void loadImageFromFile(Uri selectedFile); - - @NonNull - private AudioFile getAudioFile(@NonNull String path) { - try { - return AudioFileIO.read(new File(path)); - } catch (Exception e) { - Log.e(TAG, "Could not read audio file " + path, e); - return new AudioFile(); - } - } - - @Nullable - String getAlbumArtist() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault() - .getFirst(FieldKey.ALBUM_ARTIST); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getSongTitle() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.TITLE); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getAlbumTitle() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.ALBUM); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getArtistName() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.ARTIST); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getAlbumArtistName() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault() - .getFirst(FieldKey.ALBUM_ARTIST); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getGenreName() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.GENRE); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getSongYear() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.YEAR); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getTrackNumber() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.TRACK); - } catch (Exception ignored) { - return null; - } - } - - @Nullable - protected String getLyrics() { - try { - return getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault().getFirst(FieldKey.LYRICS); - } catch (Exception ignored) { - return null; - } - } - - - - @Nullable - protected Bitmap getAlbumArt() { - try { - Artwork artworkTag = getAudioFile(songPaths.get(0)).getTagOrCreateAndSetDefault() - .getFirstArtwork(); - if (artworkTag != null) { - byte[] artworkBinaryData = artworkTag.getBinaryData(); - return BitmapFactory.decodeByteArray(artworkBinaryData, 0, artworkBinaryData.length); - } - return null; - } catch (Exception ignored) { - return null; - } - } - - public static class ArtworkInfo { - - public final int albumId; - final Bitmap artwork; - - ArtworkInfo(int albumId, Bitmap artwork) { - this.albumId = albumId; - this.artwork = artwork; - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.kt new file mode 100755 index 00000000..a03c110b --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AbsTagEditorActivity.kt @@ -0,0 +1,332 @@ +package code.name.monkey.retromusic.ui.activities.tageditor + +import android.app.Activity +import android.app.SearchManager +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.net.Uri +import android.os.Bundle +import android.util.Log +import android.view.MenuItem +import android.view.View +import android.view.animation.OvershootInterpolator +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.appthemehelper.util.TintHelper +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.ui.activities.base.AbsBaseActivity +import code.name.monkey.retromusic.util.RetroUtil +import com.afollestad.materialdialogs.MaterialDialog +import kotlinx.android.synthetic.main.activity_album_tag_editor.* +import org.jaudiotagger.audio.AudioFile +import org.jaudiotagger.audio.AudioFileIO +import org.jaudiotagger.tag.FieldKey +import java.io.File + +abstract class AbsTagEditorActivity : AbsBaseActivity() { + + + private lateinit var items: Array + protected var id: Int = 0 + private set + private var paletteColorPrimary: Int = 0 + private var isInNoImageMode: Boolean = false + private var songPaths: List? = null + + protected val show: MaterialDialog + get() = MaterialDialog.Builder(this@AbsTagEditorActivity) + .title(R.string.update_image) + .items(*items) + .itemsCallback { _, _, position, _ -> + when (position) { + 0 -> getImageFromLastFM() + 1 -> startImagePicker() + 2 -> searchImageOnWeb() + 3 -> deleteImage() + } + }.show() + + protected abstract val contentViewLayout: Int + + internal val albumArtist: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault + .getFirst(FieldKey.ALBUM_ARTIST) + } catch (ignored: Exception) { + null + } + + } + + protected val songTitle: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.TITLE) + } catch (ignored: Exception) { + null + } + + } + + protected val albumTitle: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.ALBUM) + } catch (ignored: Exception) { + null + } + + } + + protected val artistName: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.ARTIST) + } catch (ignored: Exception) { + null + } + + } + + protected val albumArtistName: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault + .getFirst(FieldKey.ALBUM_ARTIST) + } catch (ignored: Exception) { + null + } + + } + + protected val genreName: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.GENRE) + } catch (ignored: Exception) { + null + } + + } + + protected val songYear: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.YEAR) + } catch (ignored: Exception) { + null + } + + } + + protected val trackNumber: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.TRACK) + } catch (ignored: Exception) { + null + } + + } + + protected val lyrics: String? + get() { + return try { + getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault.getFirst(FieldKey.LYRICS) + } catch (ignored: Exception) { + null + } + + } + + + protected val albumArt: Bitmap? + get() { + try { + val artworkTag = getAudioFile(songPaths!![0]).tagOrCreateAndSetDefault + .firstArtwork + if (artworkTag != null) { + val artworkBinaryData = artworkTag.binaryData + return BitmapFactory.decodeByteArray(artworkBinaryData, 0, artworkBinaryData.size) + } + return null + } catch (ignored: Exception) { + return null + } + + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(contentViewLayout) + + + getIntentExtras() + + songPaths = getSongPaths() + if (songPaths!!.isEmpty()) { + finish() + return + } + + setUpViews() + + + setNavigationbarColorAuto() + setTaskDescriptionColorAuto() + } + + private fun setUpViews() { + setUpScrollView() + setUpFab() + setUpImageView() + } + + private fun setUpScrollView() { + //observableScrollView.setScrollViewCallbacks(observableScrollViewCallbacks); + } + + private fun setUpImageView() { + loadCurrentImage() + items = arrayOf(getString(R.string.download_from_last_fm), getString(R.string.pick_from_local_storage), getString(R.string.web_search), getString(R.string.remove_cover)) + editorImage.setOnClickListener { show } + } + + private fun startImagePicker() { + val intent = Intent(Intent.ACTION_GET_CONTENT) + intent.type = "image/*" + startActivityForResult( + Intent.createChooser(intent, getString(R.string.pick_from_local_storage)), + REQUEST_CODE_SELECT_IMAGE) + } + + protected abstract fun loadCurrentImage() + + protected abstract fun getImageFromLastFM() + + protected abstract fun searchImageOnWeb() + + protected abstract fun deleteImage() + + private fun setUpFab() { + saveFab.apply { + scaleX = 0f + scaleY = 0f + isEnabled = false + setOnClickListener { save() } + TintHelper.setTintAuto(this, ThemeStore.accentColor(this@AbsTagEditorActivity), true) + } + } + + protected abstract fun save() + + private fun getIntentExtras() { + val intentExtras = intent.extras + if (intentExtras != null) { + id = intentExtras.getInt(EXTRA_ID) + } + } + + protected abstract fun getSongPaths(): List + + protected fun searchWebFor(vararg keys: String) { + val stringBuilder = StringBuilder() + for (key in keys) { + stringBuilder.append(key) + stringBuilder.append(" ") + } + val intent = Intent(Intent.ACTION_WEB_SEARCH) + intent.putExtra(SearchManager.QUERY, stringBuilder.toString()) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + startActivity(intent) + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + val id = item.itemId + when (id) { + android.R.id.home -> { + super.onBackPressed() + return true + } + } + return super.onOptionsItemSelected(item) + } + + protected fun setNoImageMode() { + isInNoImageMode = true + imageContainer!!.visibility = View.GONE + editorImage.visibility = View.GONE + editorImage.isEnabled = false + + setColors(intent.getIntExtra(EXTRA_PALETTE, ThemeStore.primaryColor(this))) + } + + protected fun dataChanged() { + showFab() + } + + private fun showFab() { + saveFab.animate() + .setDuration(500) + .setInterpolator(OvershootInterpolator()) + .scaleX(1f) + .scaleY(1f) + .start() + saveFab.isEnabled = true + } + + protected fun setImageBitmap(bitmap: Bitmap?, bgColor: Int) { + if (bitmap == null) { + editorImage.setImageResource(R.drawable.default_album_art) + } else { + editorImage.setImageBitmap(bitmap) + } + setColors(bgColor) + } + + protected open fun setColors(color: Int) { + paletteColorPrimary = color + } + + protected fun writeValuesToFiles(fieldKeyValueMap: Map, + artworkInfo: ArtworkInfo?) { + RetroUtil.hideSoftKeyboard(this) + + WriteTagsAsyncTask(this) + .execute(WriteTagsAsyncTask.LoadingInfo(getSongPaths(), fieldKeyValueMap, artworkInfo)) + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + when (requestCode) { + REQUEST_CODE_SELECT_IMAGE -> if (resultCode == Activity.RESULT_OK) { + val selectedImage = data!!.data + loadImageFromFile(selectedImage) + } + } + } + + protected abstract fun loadImageFromFile(selectedFile: Uri?) + + private fun getAudioFile(path: String): AudioFile { + try { + return AudioFileIO.read(File(path)) + } catch (e: Exception) { + Log.e(TAG, "Could not read audio file $path", e) + return AudioFile() + } + + } + + class ArtworkInfo constructor(val albumId: Int, val artwork: Bitmap?) + + companion object { + + const val EXTRA_ID = "extra_id" + const val EXTRA_PALETTE = "extra_palette" + private val TAG = AbsTagEditorActivity::class.java.simpleName + private const val REQUEST_CODE_SELECT_IMAGE = 1000 + } +} 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 deleted file mode 100755 index 326db21e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.java +++ /dev/null @@ -1,307 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.tageditor; - -import android.content.res.ColorStateList; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Bundle; -import android.text.Editable; -import android.text.TextUtils; -import android.text.TextWatcher; -import android.view.View; -import android.widget.TextView; -import android.widget.Toast; - -import com.bumptech.glide.Glide; -import com.bumptech.glide.load.engine.DiskCacheStrategy; -import com.bumptech.glide.request.animation.GlideAnimation; -import com.bumptech.glide.request.target.SimpleTarget; -import com.google.android.material.appbar.AppBarLayout; -import com.google.android.material.textfield.TextInputEditText; -import com.google.android.material.textfield.TextInputLayout; - -import org.jaudiotagger.tag.FieldKey; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.Toolbar; -import androidx.core.content.ContextCompat; -import butterknife.BindView; -import butterknife.BindViews; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -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.glide.palette.BitmapPaletteTranscoder; -import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper; -import code.name.monkey.retromusic.loaders.AlbumLoader; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.rest.LastFMRestClient; -import code.name.monkey.retromusic.rest.model.LastFmAlbum; -import code.name.monkey.retromusic.util.ImageUtil; -import code.name.monkey.retromusic.util.LastFMUtil; -import code.name.monkey.retromusic.util.RetroColorUtil; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - - -public class AlbumTagEditorActivity extends AbsTagEditorActivity implements TextWatcher { - - public static final String TAG = AlbumTagEditorActivity.class.getSimpleName(); - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.app_bar) - @Nullable - AppBarLayout appBarLayout; - @BindViews({R.id.album_title_container, R.id.album_artist_container, R.id.genre_container, R.id.year_container}) - List textInputLayouts; - - @BindView(R.id.album_title) - TextInputEditText albumTitle; - - @BindView(R.id.album_artist) - TextInputEditText albumArtist; - - @BindView(R.id.genre) - TextInputEditText genre; - - @BindView(R.id.year) - TextInputEditText year; - - @BindView(R.id.gradient_background) - View background; - - @BindView(R.id.content) - View content; - - ButterKnife.Setter textColor = (view, value, index) -> { - view.setBoxStrokeColor(value); - }; - private Bitmap albumArtBitmap; - private boolean deleteAlbumArt; - private LastFMRestClient lastFMRestClient; - private CompositeDisposable disposable = new CompositeDisposable(); - - private void setupToolbar() { - title.setTextColor(Color.WHITE); - toolbar.setNavigationOnClickListener(v -> onBackPressed()); - ToolbarContentTintHelper.setToolbarContentColorBasedOnToolbarColor(this, toolbar, Color.TRANSPARENT); - setTitle(null); - setSupportActionBar(toolbar); - TintHelper.setTintAuto(content, ThemeStore.primaryColor(this), true); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - setDrawUnderStatusBar(); - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - ButterKnife.apply(textInputLayouts, textColor, ThemeStore.accentColor((this))); - lastFMRestClient = new LastFMRestClient(this); - - setUpViews(); - setupToolbar(); - - } - - @Override - protected int getContentViewLayout() { - return R.layout.activity_album_tag_editor; - } - - private void setUpViews() { - fillViewsWithFileTags(); - albumTitle.addTextChangedListener(this); - albumArtist.addTextChangedListener(this); - genre.addTextChangedListener(this); - year.addTextChangedListener(this); - } - - private void fillViewsWithFileTags() { - albumTitle.setText(getAlbumTitle()); - albumArtist.setText(getAlbumArtistName()); - genre.setText(getGenreName()); - year.setText(getSongYear()); - } - - @Override - protected void loadCurrentImage() { - Bitmap bitmap = getAlbumArt(); - setImageBitmap(bitmap, RetroColorUtil.getColor(RetroColorUtil.generatePalette(bitmap), - ATHUtil.resolveColor(this, R.attr.defaultFooterColor))); - deleteAlbumArt = false; - } - - @Override - protected void getImageFromLastFM() { - String albumTitleStr = albumTitle.getText().toString(); - String albumArtistNameStr = albumArtist.getText().toString(); - if (albumArtistNameStr.trim().equals("") || albumTitleStr.trim().equals("")) { - Toast.makeText(this, getResources().getString(R.string.album_or_artist_empty), - Toast.LENGTH_SHORT).show(); - return; - } - - disposable.add(lastFMRestClient.getApiService() - .getAlbumInfo(albumTitleStr, albumArtistNameStr, null) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeOn(Schedulers.computation()) - .subscribe(this::extractDetails)); - } - - @Override - protected void onPause() { - super.onPause(); - disposable.clear(); - } - - private void extractDetails(@NonNull LastFmAlbum lastFmAlbum) { - if (lastFmAlbum.getAlbum() != null) { - - String url = LastFMUtil.getLargestAlbumImageUrl(lastFmAlbum.getAlbum().getImage()); - - if (!TextUtils.isEmpty(url) && url.trim().length() > 0) { - Glide.with(this) - .load(url) - .asBitmap() - .transcode(new BitmapPaletteTranscoder(this), BitmapPaletteWrapper.class) - .diskCacheStrategy(DiskCacheStrategy.SOURCE) - .error(R.drawable.default_album_art) - .into(new SimpleTarget() { - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - e.printStackTrace(); - Toast.makeText(AlbumTagEditorActivity.this, e.toString(), Toast.LENGTH_LONG).show(); - } - - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - albumArtBitmap = ImageUtil.resizeBitmap(resource.getBitmap(), 2048); - setImageBitmap(albumArtBitmap, RetroColorUtil.getColor(resource.getPalette(), - ContextCompat.getColor(AlbumTagEditorActivity.this, R.color.md_grey_500))); - deleteAlbumArt = false; - dataChanged(); - setResult(RESULT_OK); - } - }); - return; - } - if (lastFmAlbum.getAlbum().getTags().getTag().size() > 0) { - genre.setText(lastFmAlbum.getAlbum().getTags().getTag().get(0).getName()); - } - - } - toastLoadingFailed(); - } - - private void toastLoadingFailed() { - Toast.makeText(AlbumTagEditorActivity.this, - R.string.could_not_download_album_cover, Toast.LENGTH_SHORT).show(); - } - - @Override - protected void searchImageOnWeb() { - searchWebFor(albumTitle.getText().toString(), albumArtist.getText().toString()); - } - - @Override - protected void deleteImage() { - setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.default_album_art), - ATHUtil.resolveColor(this, R.attr.defaultFooterColor)); - deleteAlbumArt = true; - dataChanged(); - } - - @Override - protected void save() { - Map fieldKeyValueMap = new EnumMap<>(FieldKey.class); - fieldKeyValueMap.put(FieldKey.ALBUM, albumTitle.getText().toString()); - //android seems not to recognize album_artist field so we additionally write the normal artist field - fieldKeyValueMap.put(FieldKey.ARTIST, albumArtist.getText().toString()); - fieldKeyValueMap.put(FieldKey.ALBUM_ARTIST, albumArtist.getText().toString()); - fieldKeyValueMap.put(FieldKey.GENRE, genre.getText().toString()); - fieldKeyValueMap.put(FieldKey.YEAR, year.getText().toString()); - - writeValuesToFiles(fieldKeyValueMap, deleteAlbumArt ? new ArtworkInfo(getId(), null) - : albumArtBitmap == null ? null : new ArtworkInfo(getId(), albumArtBitmap)); - } - - @NonNull - @Override - protected List getSongPaths() { - ArrayList songs = AlbumLoader.Companion.getAlbum(this, getId()).blockingFirst().getSongs(); - ArrayList paths = new ArrayList<>(songs.size()); - for (Song song : songs) { - paths.add(song.getData()); - } - return paths; - } - - @Override - protected void loadImageFromFile(@NonNull final Uri selectedFileUri) { - Glide.with(AlbumTagEditorActivity.this) - .load(selectedFileUri) - .asBitmap() - .transcode(new BitmapPaletteTranscoder(AlbumTagEditorActivity.this), - BitmapPaletteWrapper.class) - .diskCacheStrategy(DiskCacheStrategy.NONE) - .skipMemoryCache(true) - .into(new SimpleTarget() { - @Override - public void onLoadFailed(Exception e, Drawable errorDrawable) { - super.onLoadFailed(e, errorDrawable); - e.printStackTrace(); - Toast.makeText(AlbumTagEditorActivity.this, e.toString(), Toast.LENGTH_LONG).show(); - } - - @Override - public void onResourceReady(BitmapPaletteWrapper resource, - GlideAnimation glideAnimation) { - RetroColorUtil.getColor(resource.getPalette(), Color.TRANSPARENT); - albumArtBitmap = ImageUtil.resizeBitmap(resource.getBitmap(), 2048); - setImageBitmap(albumArtBitmap, RetroColorUtil.getColor(resource.getPalette(), - ATHUtil.resolveColor(AlbumTagEditorActivity.this, R.attr.defaultFooterColor))); - deleteAlbumArt = false; - dataChanged(); - setResult(RESULT_OK); - } - }); - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - dataChanged(); - } - - @Override - protected void setColors(int color) { - super.setColors(color); - save.setBackgroundTintList(ColorStateList.valueOf(color)); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.kt new file mode 100755 index 00000000..075c0948 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/AlbumTagEditorActivity.kt @@ -0,0 +1,232 @@ +package code.name.monkey.retromusic.ui.activities.tageditor + +import android.app.Activity +import android.content.res.ColorStateList +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Color +import android.graphics.drawable.Drawable +import android.net.Uri +import android.os.Bundle +import android.text.Editable +import android.text.TextUtils +import android.text.TextWatcher +import android.widget.Toast +import androidx.core.content.ContextCompat +import code.name.monkey.appthemehelper.ThemeStore +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.glide.palette.BitmapPaletteTranscoder +import code.name.monkey.retromusic.glide.palette.BitmapPaletteWrapper +import code.name.monkey.retromusic.loaders.AlbumLoader +import code.name.monkey.retromusic.rest.LastFMRestClient +import code.name.monkey.retromusic.rest.model.LastFmAlbum +import code.name.monkey.retromusic.util.ImageUtil +import code.name.monkey.retromusic.util.LastFMUtil +import code.name.monkey.retromusic.util.RetroColorUtil +import com.bumptech.glide.Glide +import com.bumptech.glide.load.engine.DiskCacheStrategy +import com.bumptech.glide.request.animation.GlideAnimation +import com.bumptech.glide.request.target.SimpleTarget +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import kotlinx.android.synthetic.main.activity_album_tag_editor.* +import org.jaudiotagger.tag.FieldKey +import java.util.* + + +class AlbumTagEditorActivity : AbsTagEditorActivity(), TextWatcher { + override val contentViewLayout: Int + get() = R.layout.activity_album_tag_editor + + override fun loadImageFromFile(selectedFile: Uri?) { + Glide.with(this@AlbumTagEditorActivity) + .load(selectedFile) + .asBitmap() + .transcode(BitmapPaletteTranscoder(this@AlbumTagEditorActivity), BitmapPaletteWrapper::class.java) + .diskCacheStrategy(DiskCacheStrategy.NONE) + .skipMemoryCache(true) + .into(object : SimpleTarget() { + override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) { + super.onLoadFailed(e, errorDrawable) + e!!.printStackTrace() + Toast.makeText(this@AlbumTagEditorActivity, e.toString(), Toast.LENGTH_LONG).show() + } + + override fun onResourceReady(resource: BitmapPaletteWrapper, glideAnimation: GlideAnimation) { + RetroColorUtil.getColor(resource.palette, Color.TRANSPARENT) + albumArtBitmap = ImageUtil.resizeBitmap(resource.bitmap, 2048) + setImageBitmap(albumArtBitmap, RetroColorUtil.getColor(resource.palette, ATHUtil.resolveColor(this@AlbumTagEditorActivity, R.attr.defaultFooterColor))) + deleteAlbumArt = false + dataChanged() + setResult(Activity.RESULT_OK) + } + }) + } + + private var albumArtBitmap: Bitmap? = null + private var deleteAlbumArt: Boolean = false + private var lastFMRestClient: LastFMRestClient? = null + private val disposable = CompositeDisposable() + + private fun setupToolbar() { + bannerTitle.setTextColor(Color.WHITE) + toolbar.setNavigationOnClickListener { onBackPressed() } + ToolbarContentTintHelper.setToolbarContentColorBasedOnToolbarColor(this, toolbar, Color.TRANSPARENT) + title = null + setSupportActionBar(toolbar) + TintHelper.setTintAuto(content, ThemeStore.primaryColor(this), true) + } + + override fun onCreate(savedInstanceState: Bundle?) { + setDrawUnderStatusBar() + super.onCreate(savedInstanceState) + lastFMRestClient = LastFMRestClient(this) + + setUpViews() + setupToolbar() + } + + + private fun setUpViews() { + fillViewsWithFileTags() + albumText.addTextChangedListener(this) + albumArtistText.addTextChangedListener(this) + genreTitle.addTextChangedListener(this) + yearTitle.addTextChangedListener(this) + } + + private fun fillViewsWithFileTags() { + albumText.setText(albumTitle) + albumArtistText.setText(albumArtistName) + genreTitle.setText(genreName) + yearTitle.setText(songYear) + } + + override fun loadCurrentImage() { + val bitmap = albumArt + setImageBitmap(bitmap, RetroColorUtil.getColor(RetroColorUtil.generatePalette(bitmap), ATHUtil.resolveColor(this, R.attr.defaultFooterColor))) + deleteAlbumArt = false + } + + override fun getImageFromLastFM() { + val albumTitleStr = albumText.text.toString() + val albumArtistNameStr = albumArtistText.text.toString() + if (albumArtistNameStr.trim { it <= ' ' } == "" || albumTitleStr.trim { it <= ' ' } == "") { + Toast.makeText(this, resources.getString(R.string.album_or_artist_empty), Toast.LENGTH_SHORT).show() + return + } + + disposable.add(lastFMRestClient!!.apiService + .getAlbumInfo(albumTitleStr, albumArtistNameStr, null) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeOn(Schedulers.computation()) + .subscribe { this.extractDetails(it) }) + } + + override fun onPause() { + super.onPause() + disposable.clear() + } + + private fun extractDetails(lastFmAlbum: LastFmAlbum) { + if (lastFmAlbum.album != null) { + + val url = LastFMUtil.getLargestAlbumImageUrl(lastFmAlbum.album.image) + + if (!TextUtils.isEmpty(url) && url.trim { it <= ' ' }.isNotEmpty()) { + Glide.with(this) + .load(url) + .asBitmap() + .transcode(BitmapPaletteTranscoder(this), BitmapPaletteWrapper::class.java) + .diskCacheStrategy(DiskCacheStrategy.SOURCE) + .error(R.drawable.default_album_art) + .into(object : SimpleTarget() { + override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) { + super.onLoadFailed(e, errorDrawable) + e!!.printStackTrace() + Toast.makeText(this@AlbumTagEditorActivity, e.toString(), Toast.LENGTH_LONG).show() + } + + override fun onResourceReady(resource: BitmapPaletteWrapper, + glideAnimation: GlideAnimation) { + albumArtBitmap = ImageUtil.resizeBitmap(resource.bitmap, 2048) + setImageBitmap(albumArtBitmap, RetroColorUtil.getColor(resource.palette, + ContextCompat.getColor(this@AlbumTagEditorActivity, R.color.md_grey_500))) + deleteAlbumArt = false + dataChanged() + setResult(Activity.RESULT_OK) + } + }) + return + } + if (lastFmAlbum.album.tags.tag.size > 0) { + genreTitle.setText(lastFmAlbum.album.tags.tag[0].name) + } + + } + toastLoadingFailed() + } + + private fun toastLoadingFailed() { + Toast.makeText(this@AlbumTagEditorActivity, R.string.could_not_download_album_cover, Toast.LENGTH_SHORT).show() + } + + override fun searchImageOnWeb() { + searchWebFor(albumText.text.toString(), albumArtistText.text.toString()) + } + + override fun deleteImage() { + setImageBitmap(BitmapFactory.decodeResource(resources, R.drawable.default_album_art), ATHUtil.resolveColor(this, R.attr.defaultFooterColor)) + deleteAlbumArt = true + dataChanged() + } + + override fun save() { + val fieldKeyValueMap = EnumMap(FieldKey::class.java) + fieldKeyValueMap[FieldKey.ALBUM] = albumText.text.toString() + //android seems not to recognize album_artist field so we additionally write the normal artist field + fieldKeyValueMap[FieldKey.ARTIST] = albumArtistText.text.toString() + fieldKeyValueMap[FieldKey.ALBUM_ARTIST] = albumArtistText.text.toString() + fieldKeyValueMap[FieldKey.GENRE] = genreTitle.text.toString() + fieldKeyValueMap[FieldKey.YEAR] = yearTitle.text.toString() + + writeValuesToFiles(fieldKeyValueMap, if (deleteAlbumArt) AbsTagEditorActivity.ArtworkInfo(id, null) + else if (albumArtBitmap == null) null else AbsTagEditorActivity.ArtworkInfo(id, albumArtBitmap!!)) + } + + override fun getSongPaths(): List { + val songs = AlbumLoader.getAlbum(this, id).blockingFirst().songs + val paths = ArrayList(songs!!.size) + for (song in songs) { + paths.add(song.data!!) + } + return paths + } + + + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + + } + + override fun afterTextChanged(s: Editable) { + dataChanged() + } + + override fun setColors(color: Int) { + super.setColors(color) + saveFab.backgroundTintList = ColorStateList.valueOf(color) + } + + companion object { + + val TAG: String = AlbumTagEditorActivity::class.java.simpleName + } +} 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 deleted file mode 100755 index 4672b62e..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.java +++ /dev/null @@ -1,179 +0,0 @@ -package code.name.monkey.retromusic.ui.activities.tageditor; - -import android.net.Uri; -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.widget.EditText; -import android.widget.TextView; - -import com.google.android.material.appbar.AppBarLayout; - -import org.jaudiotagger.tag.FieldKey; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -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.retromusic.R; -import code.name.monkey.retromusic.loaders.SongLoader; - - -public class SongTagEditorActivity extends AbsTagEditorActivity implements TextWatcher { - - public static final String TAG = SongTagEditorActivity.class.getSimpleName(); - @BindView(R.id.toolbar) - Toolbar toolbar; - - @BindView(R.id.app_bar) - AppBarLayout appBarLayout; - - @BindView(R.id.title) - TextView title; - - @BindView(R.id.title1) - EditText songTitle; - - @BindView(R.id.title2) - EditText albumTitle; - - @BindView(R.id.artist) - EditText artist; - - @BindView(R.id.genre) - EditText genre; - - @BindView(R.id.year) - EditText year; - - @BindView(R.id.image_text) - EditText trackNumber; - - @BindView(R.id.lyrics) - EditText lyrics; - - @BindView(R.id.album_artist) - EditText albumArtist; - - private void setupToolbar() { - appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)); - toolbar.setBackgroundColor(ThemeStore.primaryColor(this)); - toolbar.setNavigationOnClickListener(v -> onBackPressed()); - setTitle(null); - title.setTextColor(ThemeStore.textColorPrimary(this)); - setSupportActionBar(toolbar); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - ButterKnife.bind(this); - - setNoImageMode(); - setUpViews(); - setupToolbar(); - setStatusbarColorAuto(); - } - - private void setUpViews() { - fillViewsWithFileTags(); - albumArtist.addTextChangedListener(this); - songTitle.addTextChangedListener(this); - albumTitle.addTextChangedListener(this); - artist.addTextChangedListener(this); - genre.addTextChangedListener(this); - year.addTextChangedListener(this); - trackNumber.addTextChangedListener(this); - lyrics.addTextChangedListener(this); - } - - private void fillViewsWithFileTags() { - songTitle.setText(getSongTitle()); - albumArtist.setText(getAlbumArtist()); - albumTitle.setText(getAlbumTitle()); - artist.setText(getArtistName()); - genre.setText(getGenreName()); - year.setText(getSongYear()); - trackNumber.setText(getTrackNumber()); - lyrics.setText(getLyrics()); - } - - @Override - protected void loadCurrentImage() { - - } - - @Override - protected void getImageFromLastFM() { - - } - - @Override - protected void searchImageOnWeb() { - - } - - @Override - protected void deleteImage() { - - } - - @Override - protected void save() { - Map fieldKeyValueMap = new EnumMap<>(FieldKey.class); - fieldKeyValueMap.put(FieldKey.TITLE, songTitle.getText().toString()); - fieldKeyValueMap.put(FieldKey.ALBUM, albumTitle.getText().toString()); - fieldKeyValueMap.put(FieldKey.ARTIST, artist.getText().toString()); - fieldKeyValueMap.put(FieldKey.GENRE, genre.getText().toString()); - fieldKeyValueMap.put(FieldKey.YEAR, year.getText().toString()); - fieldKeyValueMap.put(FieldKey.TRACK, trackNumber.getText().toString()); - fieldKeyValueMap.put(FieldKey.LYRICS, lyrics.getText().toString()); - fieldKeyValueMap.put(FieldKey.ALBUM_ARTIST, albumArtist.getText().toString()); - writeValuesToFiles(fieldKeyValueMap, null); - } - - @Override - protected int getContentViewLayout() { - return R.layout.activity_song_tag_editor; - } - - @NonNull - @Override - protected List getSongPaths() { - ArrayList paths = new ArrayList<>(1); - paths.add(SongLoader.INSTANCE.getSong(this, getId()).blockingFirst().getData()); - return paths; - } - - @Override - protected void loadImageFromFile(Uri imageFilePath) { - - } - - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - - } - - @Override - public void afterTextChanged(Editable s) { - dataChanged(); - } - - @Override - protected void setColors(int color) { - super.setColors(color); - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.kt b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.kt new file mode 100755 index 00000000..9bc5525e --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/SongTagEditorActivity.kt @@ -0,0 +1,117 @@ +package code.name.monkey.retromusic.ui.activities.tageditor + +import android.net.Uri +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import code.name.monkey.appthemehelper.ThemeStore +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.loaders.SongLoader +import kotlinx.android.synthetic.main.activity_song_tag_editor.* +import org.jaudiotagger.tag.FieldKey +import java.util.* + + +class SongTagEditorActivity : AbsTagEditorActivity(), TextWatcher { + + override val contentViewLayout: Int + get() = R.layout.activity_song_tag_editor + + private fun setupToolbar() { + appBarLayout.setBackgroundColor(ThemeStore.primaryColor(this)) + toolbar.setBackgroundColor(ThemeStore.primaryColor(this)) + toolbar.setNavigationOnClickListener { onBackPressed() } + title = null + bannerTitle!!.setTextColor(ThemeStore.textColorPrimary(this)) + setSupportActionBar(toolbar) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + + setNoImageMode() + setUpViews() + setupToolbar() + setStatusbarColorAuto() + } + + private fun setUpViews() { + fillViewsWithFileTags() + albumText.addTextChangedListener(this) + songText.addTextChangedListener(this) + albumText.addTextChangedListener(this) + artistText.addTextChangedListener(this) + genreText.addTextChangedListener(this) + yearText.addTextChangedListener(this) + trackNumberText.addTextChangedListener(this) + lyricsText.addTextChangedListener(this) + } + + private fun fillViewsWithFileTags() { + songText.setText(songTitle) + albumArtistText.setText(albumArtist) + albumText.setText(albumTitle) + artistText.setText(artistName) + genreText.setText(genreName) + yearText.setText(songYear) + trackNumberText.setText(trackNumber) + lyricsText.setText(lyrics) + } + + override fun loadCurrentImage() { + + } + + override fun getImageFromLastFM() { + + } + + override fun searchImageOnWeb() { + + } + + override fun deleteImage() { + + } + + override fun save() { + val fieldKeyValueMap = EnumMap(FieldKey::class.java) + fieldKeyValueMap[FieldKey.TITLE] = songText.text.toString() + fieldKeyValueMap[FieldKey.ALBUM] = albumText.text.toString() + fieldKeyValueMap[FieldKey.ARTIST] = artistText.text.toString() + fieldKeyValueMap[FieldKey.GENRE] = genreText.text.toString() + fieldKeyValueMap[FieldKey.YEAR] = yearText.text.toString() + fieldKeyValueMap[FieldKey.TRACK] = trackNumberText.text.toString() + fieldKeyValueMap[FieldKey.LYRICS] = lyricsText.text.toString() + fieldKeyValueMap[FieldKey.ALBUM_ARTIST] = albumArtistText.text.toString() + writeValuesToFiles(fieldKeyValueMap, null) + } + + override fun getSongPaths(): List { + val paths = ArrayList(1) + paths.add(SongLoader.getSong(this, id).blockingFirst().data!!) + return paths + } + + override fun loadImageFromFile(selectedFile: Uri?) { + + } + + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { + + } + + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + + } + + override fun afterTextChanged(s: Editable) { + dataChanged() + } + + companion object { + val TAG: String = SongTagEditorActivity::class.java.simpleName + } + +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/WriteTagsAsyncTask.java b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/WriteTagsAsyncTask.java index 8d181da7..d8ad8d64 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/WriteTagsAsyncTask.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/activities/tageditor/WriteTagsAsyncTask.java @@ -50,10 +50,10 @@ public class WriteTagsAsyncTask extends Artwork artwork = null; File albumArtFile = null; - if (info.artworkInfo != null && info.artworkInfo.artwork != null) { + if (info.artworkInfo != null && info.artworkInfo.getArtwork() != null) { try { albumArtFile = MusicUtil.createAlbumArtFile().getCanonicalFile(); - info.artworkInfo.artwork + info.artworkInfo.getArtwork() .compress(Bitmap.CompressFormat.PNG, 0, new FileOutputStream(albumArtFile)); artwork = ArtworkFactory.createArtworkFromFile(albumArtFile); } catch (IOException e) { @@ -81,7 +81,7 @@ public class WriteTagsAsyncTask extends } if (info.artworkInfo != null) { - if (info.artworkInfo.artwork == null) { + if (info.artworkInfo.getArtwork() == null) { tag.deleteArtworkField(); deletedArtwork = true; } else if (artwork != null) { @@ -100,9 +100,9 @@ public class WriteTagsAsyncTask extends Context context = getContext(); if (context != null) { if (wroteArtwork) { - MusicUtil.insertAlbumArt(context, info.artworkInfo.albumId, albumArtFile.getPath()); + MusicUtil.insertAlbumArt(context, info.artworkInfo.getAlbumId(), albumArtFile.getPath()); } else if (deletedArtwork) { - MusicUtil.deleteAlbumArt(context, info.artworkInfo.albumId); + MusicUtil.deleteAlbumArt(context, info.artworkInfo.getAlbumId()); } } 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 deleted file mode 100644 index 166f7f65..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.java +++ /dev/null @@ -1,102 +0,0 @@ -package code.name.monkey.retromusic.ui.adapter; - -import android.app.Activity; -import android.content.Context; -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 java.util.ArrayList; -import java.util.List; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.RecyclerView; -import butterknife.BindView; -import butterknife.BindViews; -import butterknife.ButterKnife; -import code.name.monkey.appthemehelper.ThemeStore; -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.helper.MusicPlayerRemote; -import code.name.monkey.retromusic.model.Song; -import code.name.monkey.retromusic.ui.adapter.CollageSongAdapter.CollageSongViewHolder; -import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder; - -/** - * @author Hemanth S (h4h13). - */ -public class CollageSongAdapter extends RecyclerView.Adapter { - - private Activity activity; - private ArrayList dataSet; - - public CollageSongAdapter(Activity activity, ArrayList dataSet) { - this.activity = activity; - this.dataSet = dataSet; - } - - @Override - public void onBindViewHolder(@NonNull CollageSongViewHolder holder, int position) { - holder.bindSongs(); - if (dataSet.size() > 8) { - for (int i = 0; i < dataSet.subList(0, 8).size(); i++) { - if (holder.imageViews != null) { - SongGlideRequest.Builder.from(Glide.with(activity), dataSet.get(i)) - .checkIgnoreMediaStore(activity) - .build() - .into(holder.imageViews.get(i)); - } - } - } - } - - @Override - public int getItemCount() { - return 1; - } - - @NonNull - @Override - public CollageSongViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - return new CollageSongViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_collage, parent, false)); - } - - class CollageSongViewHolder extends MediaEntryViewHolder { - - @BindViews({R.id.image_2, R.id.image_3, R.id.image_4, R.id.image_5, R.id.image_6, R.id.image_7, R.id.image_8, R.id.image_9}) - @Nullable - List imageViews; - - @BindView(R.id.image_1) - TextView view; - - CollageSongViewHolder(View itemView) { - super(itemView); - //ButterKnife.bind(this, itemView); - //Context context = itemView.getContext(); - //int color = ThemeStore.accentColor(context); - //view.setOnClickListener(v -> MusicPlayerRemote.INSTANCE.openQueue(dataSet, 0, true)); - //view.setBackgroundColor(color); - //view.setTextColor(MaterialValueHelper.getPrimaryTextColor(context, ColorUtil.isColorLight(color))); - } - - void bindSongs() { - if (imageViews != null) { - for (int i = 0; i < imageViews.size(); i++) { - final int startPosition = i; - ImageView imageView = imageViews.get(i); - imageView.setOnClickListener(view -> { - MusicPlayerRemote.INSTANCE.playNext(dataSet.get(startPosition)); - }); - } - } - } - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.kt b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.kt new file mode 100644 index 00000000..81a0c16d --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/adapter/CollageSongAdapter.kt @@ -0,0 +1,68 @@ +package code.name.monkey.retromusic.ui.adapter + +import android.app.Activity +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import code.name.monkey.appthemehelper.ThemeStore +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.helper.MusicPlayerRemote +import code.name.monkey.retromusic.model.Song +import code.name.monkey.retromusic.ui.adapter.CollageSongAdapter.CollageSongViewHolder +import code.name.monkey.retromusic.ui.adapter.base.MediaEntryViewHolder +import com.bumptech.glide.Glide +import java.util.* + +/** + * @author Hemanth S (h4h13). + */ +class CollageSongAdapter(private val activity: Activity, private val dataSet: ArrayList) : RecyclerView.Adapter() { + + override fun onBindViewHolder(holder: CollageSongViewHolder, position: Int) { + holder.bindSongs() + if (dataSet.size > 8) { + for (i in 0 until dataSet.subList(0, 8).size) { + SongGlideRequest.Builder.from(Glide.with(activity), dataSet[i]) + .checkIgnoreMediaStore(activity) + .build() + .into(holder.itemView.findViewById(holder.ids[i]) as ImageView) + } + } + } + + override fun getItemCount(): Int { + return 1 + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CollageSongViewHolder { + return CollageSongViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_collage, parent, false)) + } + + inner class CollageSongViewHolder(itemView: View) : MediaEntryViewHolder(itemView) { + + val ids = arrayListOf(R.id.image_2, R.id.image_3, R.id.image_4, R.id.image_5, R.id.image_6, R.id.image_7, R.id.image_8, R.id.image_9) + private var textView: TextView = itemView.findViewById(R.id.image_1) + + fun bindSongs() { + for (i in ids) { + val imageView = itemView.findViewById(i) + imageView.setOnClickListener { + textView.setOnClickListener { MusicPlayerRemote.openQueue(dataSet, 0, true) } + } + } + + val context = itemView.context + val color = ThemeStore.accentColor(context); + + textView.setOnClickListener { MusicPlayerRemote.openQueue(dataSet, 0, true) } + textView.setBackgroundColor(color); + textView.setTextColor(MaterialValueHelper.getPrimaryTextColor(context, ColorUtil.isColorLight(color))) + } + } +} 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 index fc902b49..0704c023 100644 --- 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 @@ -118,9 +118,9 @@ class AlbumCoverPagerAdapter(fm: FragmentManager, private val dataSet: ArrayList } private fun loadAlbumCover() { - SongGlideRequest.Builder.from(Glide.with(context), song) - .checkIgnoreMediaStore(activity) - .generatePalette(activity).build() + SongGlideRequest.Builder.from(Glide.with(context), song!!) + .checkIgnoreMediaStore(activity!!) + .generatePalette(activity!!).build() .into(object : RetroMusicColoredTarget(albumCover) { override fun onColorReady(color: Int) { setColor(color) 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 index 67a3f52e..95ab4e3b 100755 --- 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 @@ -10,7 +10,6 @@ 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 @@ -207,7 +206,6 @@ class PlaylistAdapter(protected val activity: AppCompatActivity, dataSet: ArrayL 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) diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.java deleted file mode 100644 index 1c63ac8f..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.java +++ /dev/null @@ -1,28 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments; - -import androidx.annotation.DrawableRes; -import androidx.annotation.StringRes; -import code.name.monkey.retromusic.R; - - -public enum AlbumCoverStyle { - NORMAL(R.string.normal, R.drawable.album_cover_normal, 0), - FLAT(R.string.flat, R.drawable.album_cover_square, 1), - CIRCLE(R.string.circular, R.drawable.album_cover_circle, 2), - MATERIAL(R.string.material, R.drawable.album_cover_normal, 3), - CARD(R.string.card, R.drawable.album_cover_card, 4), - FULL(R.string.full, R.drawable.album_cover_full, 5), - FULL_CARD(R.string.full_card, R.drawable.album_cover_full_card, 6); - - @StringRes - public final int titleRes; - @DrawableRes - public final int drawableResId; - public final int id; - - AlbumCoverStyle(@StringRes int titleRes, @DrawableRes int drawableResId, int id) { - this.titleRes = titleRes; - this.drawableResId = drawableResId; - this.id = id; - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.kt new file mode 100644 index 00000000..f901e7f7 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/AlbumCoverStyle.kt @@ -0,0 +1,19 @@ +package code.name.monkey.retromusic.ui.fragments + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import code.name.monkey.retromusic.R + + +enum class AlbumCoverStyle(@param:StringRes @field:StringRes + val titleRes: Int, + @param:DrawableRes @field:DrawableRes + val drawableResId: Int, val id: Int) { + NORMAL(R.string.normal, R.drawable.album_cover_normal, 0), + FLAT(R.string.flat, R.drawable.album_cover_square, 1), + CIRCLE(R.string.circular, R.drawable.album_cover_circle, 2), + MATERIAL(R.string.material, R.drawable.album_cover_normal, 3), + CARD(R.string.card, R.drawable.album_cover_card, 4), + FULL(R.string.full, R.drawable.album_cover_full, 5), + FULL_CARD(R.string.full_card, R.drawable.album_cover_full_card, 6) +} 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.kt similarity index 53% rename from app/src/main/java/code/name/monkey/retromusic/ui/fragments/NowPlayingScreen.java rename to app/src/main/java/code/name/monkey/retromusic/ui/fragments/NowPlayingScreen.kt index 077d3f13..49497b4f 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.kt @@ -1,11 +1,14 @@ -package code.name.monkey.retromusic.ui.fragments; +package code.name.monkey.retromusic.ui.fragments -import androidx.annotation.DrawableRes; -import androidx.annotation.StringRes; -import code.name.monkey.retromusic.R; +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import code.name.monkey.retromusic.R -public enum NowPlayingScreen { +enum class NowPlayingScreen constructor(@param:StringRes @field:StringRes + val titleRes: Int, + @param:DrawableRes @field:DrawableRes val drawableResId: Int, + val id: Int) { NORMAL(R.string.normal, R.drawable.np_normal, 0), FLAT(R.string.flat, R.drawable.np_flat, 1), FULL(R.string.full, R.drawable.np_full, 2), @@ -18,17 +21,5 @@ public enum NowPlayingScreen { BLUR_CARD(R.string.blur_card, R.drawable.np_blur_card, 9), ADAPTIVE(R.string.adaptive, R.drawable.np_adaptive, 10), MATERIAL(R.string.material, R.drawable.np_material, 11), - FIT(R.string.fit, R.drawable.np_adaptive, 12); - - @StringRes - public final int titleRes; - @DrawableRes - public final int drawableResId; - public final int id; - - NowPlayingScreen(@StringRes int titleRes, @DrawableRes int drawableResId, int id) { - this.titleRes = titleRes; - this.drawableResId = drawableResId; - this.id = id; - } + FIT(R.string.fit, R.drawable.np_adaptive, 12) } 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 index d8695449..a202d1e9 100644 --- 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 @@ -130,8 +130,8 @@ open class AlbumsFragment : AbsLibraryPagerRecyclerViewCustomGridSizeFragment) { - adapter!!.swapDataSet(albums) + override fun showData(list: ArrayList) { + adapter!!.swapDataSet(list) } companion object { 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 index cb67e5ba..bddb8bce 100644 --- 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 @@ -122,8 +122,8 @@ class ArtistsFragment : AbsLibraryPagerRecyclerViewCustomGridSizeFragment) { - adapter!!.swapDataSet(artists) + override fun showData(list: ArrayList) { + adapter!!.swapDataSet(list) } companion object { 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 index 519cdc3f..2d8725ca 100644 --- 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 @@ -60,8 +60,8 @@ class GenreFragment : AbsLibraryPagerRecyclerViewFragment) { - adapter!!.swapDataSet(songs) + override fun showData(list: ArrayList) { + adapter!!.swapDataSet(list) } override fun showEmptyView() { 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 index 9ea0ad93..267ebb5d 100644 --- 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 @@ -56,11 +56,22 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme val totalAppBarScrollingRange: Int get() = appbar.totalScrollRange - private val currentFragment: Fragment? - get() = if (fragmentManager == null) { + private fun getCurrentFragment(): Fragment? { + return if (fragmentManager == null) { SongsFragment.newInstance() - } else fragmentManager!!.findFragmentByTag(LibraryFragment.TAG) + } else fragmentManager!!.findFragmentById(R.id.fragment_container) + } + private fun selectedFragment(fragment: Fragment) { + val fragmentManager = childFragmentManager + val fragmentTransaction = fragmentManager.beginTransaction() + + fragmentTransaction + .replace(R.id.fragment_container, fragment, TAG) + .commit() + + fragmentManager.executePendingTransactions() + } fun setTitle(@StringRes name: Int) { title.text = getString(name) @@ -120,14 +131,6 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme 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) { @@ -143,12 +146,17 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme return cab as MaterialCab } + private fun isPlaylistFragment(): Boolean { + return true + } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) inflater!!.inflate(R.menu.menu_main, menu) - - val currentFragment = currentFragment + if (isPlaylistFragment()) { + menu!!.add(0, R.id.action_new_playlist, 0, R.string.new_playlist_title) + } + val currentFragment = getCurrentFragment() if (currentFragment is AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *> && currentFragment.isAdded) { val fragment = currentFragment as AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>? @@ -161,11 +169,9 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme 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) + menu!!.removeItem(R.id.action_grid_size) } - activity ?: return - ToolbarContentTintHelper.handleOnCreateOptionsMenu(getActivity(), toolbar, menu, ATHToolbarActivity.getToolbarBackgroundColor(toolbar)) + ToolbarContentTintHelper.handleOnCreateOptionsMenu(activity!!, toolbar, menu, ATHToolbarActivity.getToolbarBackgroundColor(toolbar)) } override fun onPrepareOptionsMenu(menu: Menu?) { @@ -181,22 +187,26 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme 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 + when (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 + } + 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 + } + 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) @@ -205,20 +215,18 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme private fun handleSortOrderMenuItem( fragment: AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>, item: MenuItem): Boolean { var sortOrder: String? = null - if (fragment is AlbumsFragment) { - when (item.itemId) { + when (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) { + 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) { + 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 @@ -240,7 +248,7 @@ class LibraryFragment : AbsMainActivityFragment(), CabHolder, MainActivityFragme override fun onOptionsItemSelected(item: MenuItem): Boolean { //if (pager == null) return false; - val currentFragment = currentFragment + val currentFragment = getCurrentFragment() if (currentFragment is AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>) { val fragment = currentFragment as AbsLibraryPagerRecyclerViewCustomGridSizeFragment<*, *>? if (handleGridSizeMenuItem(fragment!!, item)) { 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 index 76181522..b45957a4 100644 --- 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 @@ -4,7 +4,6 @@ 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 @@ -76,8 +75,8 @@ class PlaylistsFragment : AbsLibraryPagerRecyclerViewFragment) { - adapter!!.swapDataSet(playlists) + override fun showData(list: ArrayList) { + adapter!!.swapDataSet(list) } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { 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 index 63bfc9d6..ff433459 100644 --- 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 @@ -105,8 +105,8 @@ class SongsFragment : AbsLibraryPagerRecyclerViewCustomGridSizeFragment) { - adapter!!.swapDataSet(songs) + override fun showData(list: ArrayList) { + adapter!!.swapDataSet(list) } override fun showEmptyView() { 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 5ab19f72..1dbd69da 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 @@ -32,6 +32,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; +import java.util.Objects; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -40,8 +41,6 @@ import androidx.loader.app.LoaderManager; import androidx.loader.content.Loader; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -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; @@ -106,6 +105,7 @@ public class FoldersFragment extends AbsMainActivityFragment implements }; private SongFileAdapter adapter; private MaterialCab cab; + public FoldersFragment() { } @@ -515,8 +515,8 @@ public class FoldersFragment extends AbsMainActivityFragment implements private WeakReference fragmentWeakReference; - public AsyncFileLoader(FoldersFragment foldersFragment) { - super(foldersFragment.getActivity()); + AsyncFileLoader(FoldersFragment foldersFragment) { + super(Objects.requireNonNull(foldersFragment.getActivity())); fragmentWeakReference = new WeakReference<>(foldersFragment); } 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 index 273ab2a9..7615a697 100644 --- 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 @@ -265,10 +265,10 @@ class BannerHomeFragment : AbsMainActivityFragment(), MainActivityFragmentCallba } - override fun geners(genres: ArrayList) { + override fun geners(songs: ArrayList) { genreContainer.visibility = View.VISIBLE genresRecyclerView.apply { - val genreAdapter = GenreAdapter(activity!!, genres, R.layout.item_list) + val genreAdapter = GenreAdapter(activity!!, songs, R.layout.item_list) layoutManager = LinearLayoutManager(context) adapter = genreAdapter } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.kt index e462252d..ee42ef4c 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.kt +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/player/color/ColorFragment.kt @@ -133,7 +133,7 @@ class ColorFragment : AbsPlayerFragment() { val activity = activity SongGlideRequest.Builder.from(Glide.with(activity), MusicPlayerRemote.currentSong) - .checkIgnoreMediaStore(activity) + .checkIgnoreMediaStore(activity!!) .generatePalette(activity).build().dontAnimate() .into(object : RetroMusicColoredTarget(playerImage) { override fun onColorReady(color: Int) { diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AbsSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AbsSettingsFragment.java index f2945694..f8130bd4 100644 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AbsSettingsFragment.java +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AbsSettingsFragment.java @@ -67,11 +67,11 @@ public abstract class AbsSettingsFragment extends ATEPreferenceFragmentCompat { @Override public DialogFragment onCreatePreferenceDialog(Preference preference) { if (preference instanceof NowPlayingScreenPreference) { - return NowPlayingScreenPreferenceDialog.newInstance(); + return NowPlayingScreenPreferenceDialog.Companion.newInstance(); } else if (preference instanceof BlacklistPreference) { return BlacklistPreferenceDialog.newInstance(); } else if (preference instanceof AlbumCoverStylePreference) { - return AlbumCoverStylePreferenceDialog.newInstance(); + return AlbumCoverStylePreferenceDialog.Companion.newInstance(); } return super.onCreatePreferenceDialog(preference); } diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.java deleted file mode 100644 index 28485335..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.java +++ /dev/null @@ -1,49 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.content.Intent; -import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; -import android.media.audiofx.AudioEffect; -import android.os.Bundle; -import androidx.preference.Preference; - -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.util.NavigationUtil; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ - -public class AudioSettings extends AbsSettingsFragment { - @Override - public void invalidateSettings() { - Preference findPreference = findPreference("equalizer"); - if (!hasEqualizer() && !PreferenceUtil.getInstance().getSelectedEqualizer().equals("retro")) { - findPreference.setEnabled(false); - findPreference.setSummary(getResources().getString(R.string.no_equalizer)); - } else { - findPreference.setEnabled(true); - } - findPreference.setOnPreferenceClickListener(preference -> { - //noinspection ConstantConditions - NavigationUtil.openEqualizer(getActivity()); - return true; - }); - - - } - - private boolean hasEqualizer() { - final Intent effects = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL); - //noinspection ConstantConditions - PackageManager pm = getActivity().getPackageManager(); - ResolveInfo ri = pm.resolveActivity(effects, 0); - return ri != null; - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_audio); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.kt new file mode 100644 index 00000000..5c8e52cf --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/AudioSettings.kt @@ -0,0 +1,46 @@ +package code.name.monkey.retromusic.ui.fragments.settings + +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.media.audiofx.AudioEffect +import android.os.Bundle +import androidx.preference.Preference + +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.util.NavigationUtil +import code.name.monkey.retromusic.util.PreferenceUtil + +/** + * @author Hemanth S (h4h13). + */ + +class AudioSettings : AbsSettingsFragment() { + override fun invalidateSettings() { + val findPreference = findPreference("equalizer") + if (!hasEqualizer() && PreferenceUtil.getInstance().selectedEqualizer != "retro") { + findPreference.isEnabled = false + findPreference.summary = resources.getString(R.string.no_equalizer) + } else { + findPreference.isEnabled = true + } + findPreference.setOnPreferenceClickListener { + NavigationUtil.openEqualizer(activity!!) + true + } + + + } + + private fun hasEqualizer(): Boolean { + val effects = Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL) + + val pm = activity!!.packageManager + val ri = pm.resolveActivity(effects, 0) + return ri != null + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_audio) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.java deleted file mode 100644 index 80e7c29b..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.java +++ /dev/null @@ -1,28 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.os.Bundle; -import androidx.preference.Preference; - -import code.name.monkey.retromusic.R; - -/** - * @author Hemanth S (h4h13). - */ - -public class ImageSettingFragment extends AbsSettingsFragment { - @Override - public void invalidateSettings() { - final Preference autoDownloadImagesPolicy = findPreference("auto_download_images_policy"); - setSummary(autoDownloadImagesPolicy); - autoDownloadImagesPolicy.setOnPreferenceChangeListener((preference, o) -> { - setSummary(autoDownloadImagesPolicy, o); - return true; - }); - - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_images); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.kt new file mode 100644 index 00000000..5ae82db6 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ImageSettingFragment.kt @@ -0,0 +1,26 @@ +package code.name.monkey.retromusic.ui.fragments.settings + +import android.os.Bundle +import androidx.preference.Preference + +import code.name.monkey.retromusic.R + +/** + * @author Hemanth S (h4h13). + */ + +class ImageSettingFragment : AbsSettingsFragment() { + override fun invalidateSettings() { + val autoDownloadImagesPolicy = findPreference("auto_download_images_policy") + setSummary(autoDownloadImagesPolicy) + autoDownloadImagesPolicy.setOnPreferenceChangeListener { _, o -> + setSummary(autoDownloadImagesPolicy, o) + true + } + + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_images) + } +} 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 deleted file mode 100644 index 6eec07ab..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.java +++ /dev/null @@ -1,43 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.os.Build; -import android.os.Bundle; -import androidx.preference.TwoStatePreference; - -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.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ - -public class NotificationSettingsFragment extends AbsSettingsFragment { - @Override - public void invalidateSettings() { - final TwoStatePreference classicNotification = (TwoStatePreference) findPreference("classic_notification"); - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { - classicNotification.setVisible(false); - } else { - classicNotification.setChecked(PreferenceUtil.getInstance().classicNotification()); - classicNotification.setOnPreferenceChangeListener((preference, newValue) -> { - // Save preference - PreferenceUtil.getInstance().setClassicNotification((Boolean) newValue); - - final MusicService service = MusicPlayerRemote.INSTANCE.getMusicService(); - if (service != null) { - service.initNotification(); - service.updateNotification(); - } - - return true; - }); - } - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_notification); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.kt new file mode 100644 index 00000000..9c5dc1d0 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NotificationSettingsFragment.kt @@ -0,0 +1,41 @@ +package code.name.monkey.retromusic.ui.fragments.settings + +import android.os.Build +import android.os.Bundle +import androidx.preference.TwoStatePreference + +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.util.PreferenceUtil + +/** + * @author Hemanth S (h4h13). + */ + +class NotificationSettingsFragment : AbsSettingsFragment() { + override fun invalidateSettings() { + val classicNotification = findPreference("classic_notification") as TwoStatePreference + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { + classicNotification.isVisible = false + } else { + classicNotification.isChecked = PreferenceUtil.getInstance().classicNotification() + classicNotification.setOnPreferenceChangeListener { _, newValue -> + // Save preference + PreferenceUtil.getInstance().setClassicNotification(newValue as Boolean) + + val service = MusicPlayerRemote.musicService + if (service != null) { + service.initNotification() + service.updateNotification() + } + + true + } + } + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_notification) + } +} 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 deleted file mode 100644 index 74da5bfe..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.java +++ /dev/null @@ -1,80 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.preference.TwoStatePreference; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.App; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ - -public class NowPlayingSettingsFragment extends AbsSettingsFragment implements - SharedPreferences.OnSharedPreferenceChangeListener { - - @SuppressWarnings("ConstantConditions") - @Override - public void invalidateSettings() { - updateNowPlayingScreenSummary(); - updateAlbumCoverStyleSummary(); - - final TwoStatePreference carouselEffect = (TwoStatePreference) findPreference("carousel_effect"); - carouselEffect.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue && !App.Companion.isProVersion()) { - showProToastAndNavigate(getActivity().getString(R.string.pref_title_toggle_carousel_effect)); - return false; - } - return true; - }); - - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_now_playing_screen); - } - - private void updateNowPlayingScreenSummary() { - //noinspection ConstantConditions - findPreference("now_playing_screen_id").setSummary(PreferenceUtil.getInstance().getNowPlayingScreen().titleRes); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - //noinspection ConstantConditions - PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - //noinspection ConstantConditions - PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - switch (key) { - case PreferenceUtil.NOW_PLAYING_SCREEN_ID: - updateNowPlayingScreenSummary(); - break; - case PreferenceUtil.ALBUM_COVER_STYLE: - updateAlbumCoverStyleSummary(); - break; - case PreferenceUtil.CIRCULAR_ALBUM_ART: - case PreferenceUtil.CAROUSEL_EFFECT: - invalidateSettings(); - break; - } - } - - private void updateAlbumCoverStyleSummary() { - findPreference("album_cover_style_id").setSummary(PreferenceUtil.getInstance().getAlbumCoverStyle().titleRes); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.kt new file mode 100644 index 00000000..757166664 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/NowPlayingSettingsFragment.kt @@ -0,0 +1,64 @@ +package code.name.monkey.retromusic.ui.fragments.settings + +import android.content.SharedPreferences +import android.os.Bundle +import android.view.View +import androidx.preference.TwoStatePreference +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.App +import code.name.monkey.retromusic.util.PreferenceUtil + +/** + * @author Hemanth S (h4h13). + */ + +class NowPlayingSettingsFragment : AbsSettingsFragment(), SharedPreferences.OnSharedPreferenceChangeListener { + + override fun invalidateSettings() { + updateNowPlayingScreenSummary() + updateAlbumCoverStyleSummary() + + val carouselEffect = findPreference("carousel_effect") as TwoStatePreference + carouselEffect.setOnPreferenceChangeListener { _, newValue -> + if (newValue as Boolean && !App.isProVersion) { + showProToastAndNavigate(activity!!.getString(R.string.pref_title_toggle_carousel_effect)) + return@setOnPreferenceChangeListener false + } + true + } + + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_now_playing_screen) + } + + private fun updateNowPlayingScreenSummary() { + + findPreference("now_playing_screen_id").setSummary(PreferenceUtil.getInstance().nowPlayingScreen.titleRes) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this) + } + + override fun onDestroyView() { + super.onDestroyView() + + PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this) + } + + override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { + when (key) { + PreferenceUtil.NOW_PLAYING_SCREEN_ID -> updateNowPlayingScreenSummary() + PreferenceUtil.ALBUM_COVER_STYLE -> updateAlbumCoverStyleSummary() + PreferenceUtil.CIRCULAR_ALBUM_ART, PreferenceUtil.CAROUSEL_EFFECT -> invalidateSettings() + } + } + + private fun updateAlbumCoverStyleSummary() { + findPreference("album_cover_style_id").setSummary(PreferenceUtil.getInstance().albumCoverStyle.titleRes) + } +} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.java b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.java deleted file mode 100644 index 4099daa1..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.java +++ /dev/null @@ -1,23 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.os.Bundle; - -import code.name.monkey.retromusic.R; - -/** - * @author Hemanth S (h4h13). - */ - -public class OtherSettingsFragment extends AbsSettingsFragment { - @Override - public void invalidateSettings() { - - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_blacklist); - addPreferencesFromResource(R.xml.pref_playlists); - addPreferencesFromResource(R.xml.pref_advanced); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.kt new file mode 100644 index 00000000..7abf875a --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/OtherSettingsFragment.kt @@ -0,0 +1,21 @@ +package code.name.monkey.retromusic.ui.fragments.settings + +import android.os.Bundle + +import code.name.monkey.retromusic.R + +/** + * @author Hemanth S (h4h13). + */ + +class OtherSettingsFragment : AbsSettingsFragment() { + override fun invalidateSettings() { + + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_blacklist) + addPreferencesFromResource(R.xml.pref_playlists) + addPreferencesFromResource(R.xml.pref_advanced) + } +} 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 deleted file mode 100644 index 879c0a1a..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.java +++ /dev/null @@ -1,65 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.preference.TwoStatePreference; -import code.name.monkey.retromusic.R; -import code.name.monkey.retromusic.App; -import code.name.monkey.retromusic.util.PreferenceUtil; - -public class PersonaizeSettingsFragment extends AbsSettingsFragment implements SharedPreferences.OnSharedPreferenceChangeListener { - @SuppressWarnings("ConstantConditions") - @Override - public void invalidateSettings() { - final TwoStatePreference cornerWindow = (TwoStatePreference) findPreference("corner_window"); - cornerWindow.setOnPreferenceChangeListener((preference, newValue) -> { - if ((Boolean) newValue && !App.Companion.isProVersion()) { - showProToastAndNavigate(getActivity().getString(R.string.pref_title_round_corners)); - return false; - } - getActivity().recreate(); - return true; - }); - - - final TwoStatePreference toggleFullScreen = (TwoStatePreference) findPreference("toggle_full_screen"); - toggleFullScreen.setOnPreferenceChangeListener((preference, newValue) -> { - getActivity().recreate(); - return true; - }); - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_ui); - addPreferencesFromResource(R.xml.pref_window); - addPreferencesFromResource(R.xml.pref_lockscreen); - } - - @Override - public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - //noinspection ConstantConditions - PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this); - } - - @Override - public void onDestroyView() { - super.onDestroyView(); - //noinspection ConstantConditions - PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - switch (key) { - case PreferenceUtil.CAROUSEL_EFFECT: - invalidateSettings(); - break; - } - } - -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.kt new file mode 100644 index 00000000..f459d9d3 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/PersonaizeSettingsFragment.kt @@ -0,0 +1,55 @@ +package code.name.monkey.retromusic.ui.fragments.settings + +import android.content.SharedPreferences +import android.os.Bundle +import android.view.View +import androidx.preference.TwoStatePreference +import code.name.monkey.retromusic.App +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.util.PreferenceUtil + +class PersonaizeSettingsFragment : AbsSettingsFragment(), SharedPreferences.OnSharedPreferenceChangeListener { + override fun invalidateSettings() { + val cornerWindow = findPreference("corner_window") as TwoStatePreference + cornerWindow.setOnPreferenceChangeListener { _, newValue -> + if (newValue as Boolean && !App.isProVersion) { + showProToastAndNavigate(activity!!.getString(R.string.pref_title_round_corners)) + return@setOnPreferenceChangeListener false + } + activity!!.recreate() + true + } + + + val toggleFullScreen = findPreference("toggle_full_screen") as TwoStatePreference + toggleFullScreen.setOnPreferenceChangeListener { _, newValue -> + activity!!.recreate() + true + } + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_ui) + addPreferencesFromResource(R.xml.pref_window) + addPreferencesFromResource(R.xml.pref_lockscreen) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + PreferenceUtil.getInstance().registerOnSharedPreferenceChangedListener(this) + } + + override fun onDestroyView() { + super.onDestroyView() + + PreferenceUtil.getInstance().unregisterOnSharedPreferenceChangedListener(this) + } + + override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { + when (key) { + PreferenceUtil.CAROUSEL_EFFECT -> invalidateSettings() + } + } + +} 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 deleted file mode 100644 index 60e4f8af..00000000 --- a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.java +++ /dev/null @@ -1,122 +0,0 @@ -package code.name.monkey.retromusic.ui.fragments.settings; - -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; - -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.App; -import code.name.monkey.retromusic.ui.activities.SettingsActivity; -import code.name.monkey.retromusic.util.PreferenceUtil; - -/** - * @author Hemanth S (h4h13). - */ - -public class ThemeSettingsFragment extends AbsSettingsFragment { - - @Override - public void invalidateSettings() { - - final ATEColorPreference primaryColorPref = (ATEColorPreference) findPreference( - "primary_color"); - //noinspection ConstantConditions - primaryColorPref.setVisible(PreferenceUtil.getInstance().getGeneralTheme() == R.style.Theme_RetroMusic_Color); - final int primaryColor = ThemeStore.primaryColor(getActivity()); - primaryColorPref.setColor(primaryColor, ColorUtil.darkenColor(primaryColor)); - primaryColorPref.setOnPreferenceClickListener(preference -> { - new ColorChooserDialog.Builder(getActivity(), R.string.primary_color) - .accentMode(false) - .allowUserColorInput(true) - .allowUserColorInputAlpha(false) - .preselect(primaryColor) - .show(getActivity()); - return true; - }); - - final Preference generalTheme = findPreference("general_theme"); - setSummary(generalTheme); - generalTheme.setOnPreferenceChangeListener((preference, newValue) -> { - String theme = (String) newValue; - - if (theme.equals("color") && !App.Companion.isProVersion()) { - primaryColorPref.setVisible(false); - showProToastAndNavigate("Color theme"); - return false; - } else { - primaryColorPref.setVisible(true); - } - - setSummary(generalTheme, newValue); - - - switch (theme) { - case "light": - ThemeStore.editTheme(getContext()).primaryColor(Color.WHITE).commit(); - break; - case "black": - ThemeStore.editTheme(getContext()).primaryColor(Color.BLACK).commit(); - break; - case "dark": - ThemeStore.editTheme(getContext()).primaryColor(ContextCompat.getColor(getContext(), R.color.md_grey_900)).commit(); - break; - case "color": - ThemeStore.editTheme(getContext()).primaryColor(ContextCompat.getColor(getContext(), R.color.md_blue_grey_800)).commit(); - break; - } - - ThemeStore.editTheme(getActivity()) - .activityTheme(PreferenceUtil.getThemeResFromPrefValue(theme)) - .commit(); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { - getActivity().setTheme(PreferenceUtil.getThemeResFromPrefValue(theme)); - } - getActivity().recreate(); - //invalidateSettings(); - return true; - }); - - ATEColorPreference accentColorPref = (ATEColorPreference) findPreference("accent_color"); - final int accentColor = ThemeStore.accentColor(getActivity()); - accentColorPref.setColor(accentColor, ColorUtil.darkenColor(accentColor)); - - accentColorPref.setOnPreferenceClickListener(preference -> { - new ColorChooserDialog.Builder(((SettingsActivity) getActivity()), R.string.accent_color) - .accentMode(true) - .allowUserColorInput(true) - .allowUserColorInputAlpha(false) - .preselect(accentColor) - .show(getActivity()); - return true; - }); - - TwoStatePreference colorAppShortcuts = (TwoStatePreference) findPreference( - "should_color_app_shortcuts"); - if (!VersionUtils.hasNougatMR()) { - colorAppShortcuts.setVisible(false); - } else { - colorAppShortcuts.setChecked(PreferenceUtil.getInstance().coloredAppShortcuts()); - colorAppShortcuts.setOnPreferenceChangeListener((preference, newValue) -> { - // Save preference - PreferenceUtil.getInstance().setColoredAppShortcuts((Boolean) newValue); - return true; - }); - } - - } - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.pref_general); - } -} diff --git a/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.kt b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.kt new file mode 100644 index 00000000..7814a236 --- /dev/null +++ b/app/src/main/java/code/name/monkey/retromusic/ui/fragments/settings/ThemeSettingsFragment.kt @@ -0,0 +1,108 @@ +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.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.App +import code.name.monkey.retromusic.R +import code.name.monkey.retromusic.util.PreferenceUtil +import com.afollestad.materialdialogs.color.ColorChooserDialog + +/** + * @author Hemanth S (h4h13). + */ + +class ThemeSettingsFragment : AbsSettingsFragment() { + + override fun invalidateSettings() { + + val primaryColorPref = findPreference( + "primary_color") as ATEColorPreference + + primaryColorPref.isVisible = PreferenceUtil.getInstance().generalTheme == R.style.Theme_RetroMusic_Color + val primaryColor = ThemeStore.primaryColor(activity!!) + primaryColorPref.setColor(primaryColor, ColorUtil.darkenColor(primaryColor)) + primaryColorPref.setOnPreferenceClickListener { + ColorChooserDialog.Builder(activity!!, R.string.primary_color) + .accentMode(false) + .allowUserColorInput(true) + .allowUserColorInputAlpha(false) + .preselect(primaryColor) + .show(activity!!) + true + } + + val generalTheme = findPreference("general_theme") + setSummary(generalTheme) + generalTheme.setOnPreferenceChangeListener { _, newValue -> + val theme = newValue as String + + if (theme == "color" && !App.isProVersion) { + primaryColorPref.isVisible = false + showProToastAndNavigate("Color theme") + return@setOnPreferenceChangeListener false + } else { + primaryColorPref.isVisible = true + } + + setSummary(generalTheme, newValue) + + + when (theme) { + "light" -> ThemeStore.editTheme(context!!).primaryColor(Color.WHITE).commit() + "black" -> ThemeStore.editTheme(context!!).primaryColor(Color.BLACK).commit() + "dark" -> ThemeStore.editTheme(context!!).primaryColor(ContextCompat.getColor(context!!, R.color.md_grey_900)).commit() + "color" -> ThemeStore.editTheme(context!!).primaryColor(ContextCompat.getColor(context!!, R.color.md_blue_grey_800)).commit() + } + + ThemeStore.editTheme(activity!!) + .activityTheme(PreferenceUtil.getThemeResFromPrefValue(theme)) + .commit() + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { + activity!!.setTheme(PreferenceUtil.getThemeResFromPrefValue(theme)) + } + activity!!.recreate() + //invalidateSettings(); + true + } + + val accentColorPref = findPreference("accent_color") as ATEColorPreference + val accentColor = ThemeStore.accentColor(activity!!) + accentColorPref.setColor(accentColor, ColorUtil.darkenColor(accentColor)) + + accentColorPref.setOnPreferenceClickListener { + ColorChooserDialog.Builder(context!!, R.string.accent_color) + .accentMode(true) + .allowUserColorInput(true) + .allowUserColorInputAlpha(false) + .preselect(accentColor) + .show(activity!!) + true + } + + val colorAppShortcuts = findPreference( + "should_color_app_shortcuts") as TwoStatePreference + if (!VersionUtils.hasNougatMR()) { + colorAppShortcuts.isVisible = false + } else { + colorAppShortcuts.isChecked = PreferenceUtil.getInstance().coloredAppShortcuts() + colorAppShortcuts.setOnPreferenceChangeListener { _, newValue -> + // Save preference + PreferenceUtil.getInstance().setColoredAppShortcuts(newValue as Boolean) + true + } + } + + } + + override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) { + addPreferencesFromResource(R.xml.pref_general) + } +} 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 4b8e93d7..12c639e1 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 @@ -289,7 +289,7 @@ public final class PreferenceUtil { } public int getLastLyricsType() { - return mPreferences.getInt(LAST_KNOWN_LYRICS_TYPE, R.id.normal_lyrics); + return mPreferences.getInt(LAST_KNOWN_LYRICS_TYPE, R.id.normalLyrics); } public void setLastLyricsType(int group) { @@ -323,7 +323,7 @@ public final class PreferenceUtil { public final NowPlayingScreen getNowPlayingScreen() { int id = mPreferences.getInt(NOW_PLAYING_SCREEN_ID, 0); for (NowPlayingScreen nowPlayingScreen : NowPlayingScreen.values()) { - if (nowPlayingScreen.id == id) { + if (nowPlayingScreen.getId() == id) { return nowPlayingScreen; } } @@ -333,14 +333,14 @@ public final class PreferenceUtil { @SuppressLint("CommitPrefEdits") public void setNowPlayingScreen(NowPlayingScreen nowPlayingScreen) { final SharedPreferences.Editor editor = mPreferences.edit(); - editor.putInt(NOW_PLAYING_SCREEN_ID, nowPlayingScreen.id); + editor.putInt(NOW_PLAYING_SCREEN_ID, nowPlayingScreen.getId()); editor.apply(); } public final AlbumCoverStyle getAlbumCoverStyle() { int id = mPreferences.getInt(ALBUM_COVER_STYLE, 0); for (AlbumCoverStyle albumCoverStyle : AlbumCoverStyle.values()) { - if (albumCoverStyle.id == id) { + if (albumCoverStyle.getId() == id) { return albumCoverStyle; } } @@ -349,7 +349,7 @@ public final class PreferenceUtil { public void setAlbumCoverStyle(AlbumCoverStyle albumCoverStyle) { final SharedPreferences.Editor editor = mPreferences.edit(); - editor.putInt(ALBUM_COVER_STYLE, albumCoverStyle.id); + editor.putInt(ALBUM_COVER_STYLE, albumCoverStyle.getId()); editor.apply(); }