diff options
| author | Adrian Ulrich <adrian@blinkenlights.ch> | 2024-06-23 11:32:06 +0200 |
|---|---|---|
| committer | Adrian Ulrich <adrian@blinkenlights.ch> | 2024-06-23 11:32:06 +0200 |
| commit | 38e1761320cd22faa4533d69b0bb3fa9f4f0b20d (patch) | |
| tree | 0e02630991570a66c8aa43808abf0aaca96ed2d9 /app/src/main/java/ch/blinkenlights/android | |
| download | vanilla-dpad-master.tar.gz vanilla-dpad-master.zip | |
Diffstat (limited to 'app/src/main/java/ch/blinkenlights/android')
91 files changed, 25258 insertions, 0 deletions
diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/LibraryObserver.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/LibraryObserver.java new file mode 100644 index 0000000..fc2b1d6 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/LibraryObserver.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +/** + * Receives callbacks if the media library changes + */ +public class LibraryObserver { + /** + * Type of the event, to be used as a hint + * by the receiver + */ + public enum Type { + SONG, // Change affected song items. + PLAYLIST, // Change affected playlists. + SCAN_PROGRESS, // Information about an ongoing scan. + } + /** + * Special hint values + */ + public class Value { + public static final int UNKNOWN = -1; // The exact id of the changed object is not know, may have affected all items. + public static final int OUTDATED = -2; // Everything you know is wrong: Cached data must not be used nor trusted. + } + + /** + * Return new LibraryObserver object. + */ + public LibraryObserver() { + } + + /** + * Called if there was a change, expected + * to be overriden by the registered observer. + * + * @param type one of LibraryObserver.Type + * @param id hint of which id changed for type, -1 if unspecified. + * @param ongoing whether or not to expect more events soon. + */ + public void onChange(Type type, long id, boolean ongoing) { + // NOOP, should be overriden. + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaLibrary.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaLibrary.java new file mode 100644 index 0000000..2235e08 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaLibrary.java @@ -0,0 +1,857 @@ +/* + * Copyright (C) 2016-2021 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +import android.content.Context; +import android.content.ContentValues; +import android.database.Cursor; +import android.provider.MediaStore; +import android.os.Build; +import android.os.Environment; +import android.util.Log; + +import java.util.ArrayList; +import java.util.HashSet; + +import java.io.ObjectOutputStream; +import java.io.ObjectInputStream; +import java.io.Serializable; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +public class MediaLibrary { + + public static final String TABLE_SONGS = "songs"; + public static final String TABLE_ALBUMS = "albums"; + public static final String TABLE_CONTRIBUTORS = "contributors"; + public static final String TABLE_CONTRIBUTORS_SONGS = "contributors_songs"; + public static final String TABLE_GENRES = "genres"; + public static final String TABLE_GENRES_SONGS = "genres_songs"; + public static final String TABLE_PLAYLISTS = "playlists"; + public static final String TABLE_PLAYLISTS_SONGS = "playlists_songs"; + public static final String VIEW_ARTISTS = "_artists"; + public static final String VIEW_ALBUMARTISTS = "_albumartists"; + public static final String VIEW_COMPOSERS = "_composers"; + public static final String VIEW_ALBUMS_ARTISTS = "_albums_artists"; + public static final String VIEW_SONGS_ALBUMS_ARTISTS = "_songs_albums_artists"; + public static final String VIEW_SONGS_ALBUMS_ARTISTS_HUGE = "_songs_albums_artists_huge"; + public static final String VIEW_PLAYLISTS = "_playlists"; + public static final String VIEW_PLAYLISTS_SONGS = "_playlists_songs"; + + public static final int ROLE_ARTIST = 0; + public static final int ROLE_COMPOSER = 1; + public static final int ROLE_ALBUMARTIST = 2; + + public static final int SONG_FLAG_OUTDATED = (1 << 0); // entry in library should get rescanned. + public static final int SONG_FLAG_NO_ALBUM = (1 << 1); // file had no real album tag. + public static final int SONG_FLAG_NO_ARTIST = (1 << 2); // file had no real artist tag. + + public static final String PREFERENCES_FILE = "_prefs-v1.obj"; + + /** + * Options used by the MediaScanner class + */ + public static class Preferences implements Serializable { + public boolean forceBastp; + public boolean groupAlbumsByFolder; + public ArrayList<String> mediaFolders; + public ArrayList<String> blacklistedFolders; + int _nativeLibraryCount; + int _nativeLastMtime; + } + + /** + * The progress of a currently scan, if any + * is running + */ + public static class ScanProgress { + public boolean isRunning; + public String lastFile; + public int seen; + public int changed; + public int total; + } + + /** + * Cached preferences, may be null + */ + private static Preferences sPreferences; + /** + * Our static backend instance + */ + private volatile static MediaLibraryBackend sBackend; + /** + * An instance to the created scanner thread during our own creation + */ + private static MediaScanner sScanner; + /** + * The observer to call-back during database changes + */ + private static final ArrayList<LibraryObserver> sLibraryObservers = new ArrayList<LibraryObserver>(2); + /** + * The lock we are using during object creation + */ + private static final Object[] sWait = new Object[0]; + + private static MediaLibraryBackend getBackend(Context context) { + if (sBackend == null) { + // -> unlikely + synchronized(sWait) { + if (sBackend == null) { + sBackend = new MediaLibraryBackend(context.getApplicationContext()); + sScanner = new MediaScanner(context.getApplicationContext(), sBackend); + sScanner.startQuickScan(50); + } + } + } + return sBackend; + } + + /** + * Returns the scanner preferences + * + * @param context the context to use + * @return MediaLibrary.Preferences + */ + public static MediaLibrary.Preferences getPreferences(Context context) { + MediaLibrary.Preferences prefs = sPreferences; + if (prefs == null) { + try (ObjectInputStream ois = new ObjectInputStream(context.openFileInput(PREFERENCES_FILE))) { + prefs = (MediaLibrary.Preferences)ois.readObject(); + } catch (Exception e) { + Log.w("VanillaMusic", "Returning default media-library preferences due to error: "+ e); + } + + if (prefs == null) { + prefs = new MediaLibrary.Preferences(); + prefs.forceBastp = true; // Auto enable for new installations + } + + if (prefs.mediaFolders == null || prefs.mediaFolders.size() == 0) + prefs.mediaFolders = discoverDefaultMediaPaths(context); + + if (prefs.blacklistedFolders == null) // we allow this to be empty, but it must not be null. + prefs.blacklistedFolders = discoverDefaultBlacklistedPaths(context); + + sPreferences = prefs; // cached for frequent access + } + return prefs; + } + + /** + * Returns the guessed media paths for this device + * + * @return array with guessed directories + */ + private static ArrayList<String> discoverDefaultMediaPaths(Context context) { + HashSet<String> defaultPaths = new HashSet<>(); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // Running on a platform which enforces scoped access. + // Add the external storage dir by default but also try to guess good external paths. + defaultPaths.add(Environment.getExternalStorageDirectory().getAbsolutePath()); + + for (File file : context.getExternalMediaDirs()) { + // Returns 'null' on some Samsung devices?!. + if (file == null) + continue; + + defaultPaths.add(file.getAbsolutePath()); + // Check if we have access to a subdir which contains the 'Music' folder. + while ( (file = file.getParentFile()) != null) { + File candidate = new File(file, "Music"); + if (candidate.exists() && !defaultPaths.contains(file.getAbsolutePath())) { + defaultPaths.add(candidate.getAbsolutePath()); + break; + } + } + } + } else { + // Try to discover media paths using getExternalMediaDirs() on 5.x and newer + for (File file : context.getExternalMediaDirs()) { + // Seems to happen on some Samsung 5.x devices. :-( + if (file == null) + continue; + + String path = file.getAbsolutePath(); + int match = path.indexOf("/Android/media/"); // From Environment.DIR_ANDROID + Environment.DIR_MEDIA (both hidden) + if (match >= 0) + defaultPaths.add(path.substring(0, match)); + } + } + + // Fall back to old API and some guessing if nothing was found (yet). + if (defaultPaths.size() == 0) { + // this should always exist + defaultPaths.add(Environment.getExternalStorageDirectory().getAbsolutePath()); + // this *may* exist + File sdCard = new File("/storage/sdcard1"); + if (sdCard.isDirectory()) + defaultPaths.add(sdCard.getAbsolutePath()); + } + return new ArrayList<String>(defaultPaths); + } + + /** + * Returns default paths which should be blacklisted + * + * @return array with guessed blacklist + */ + private static ArrayList<String> discoverDefaultBlacklistedPaths(Context context) { + final String[] defaultBlacklistPostfix = { "Android/data", "Android/media", "Alarms", "Notifications", "Ringtones", "media/audio" }; + ArrayList<String> defaultPaths = new ArrayList<>(); + + for (String path : discoverDefaultMediaPaths(context)) { + for (int i = 0; i < defaultBlacklistPostfix.length; i++) { + File guess = new File(path + "/" + defaultBlacklistPostfix[i]); + if (guess.isDirectory()) + defaultPaths.add(guess.getAbsolutePath()); + } + } + return defaultPaths; + } + + /** + * Updates the scanner preferences + * + * @param context the context to use + * @param prefs the preferences to store - this will update ALL fields, so you are + * supposed to first call getPreferences() to obtain the current values + */ + public static void setPreferences(Context context, MediaLibrary.Preferences prefs) { + MediaLibraryBackend backend = getBackend(context); + + try (ObjectOutputStream oos = new ObjectOutputStream(context.openFileOutput(PREFERENCES_FILE, 0))) { + oos.writeObject(prefs); + } catch (Exception e) { + Log.w("VanillaMusic", "Failed to store media preferences: " + e); + } + + sPreferences = prefs; + } + + /** + * Triggers a rescan of the library + * + * @param context the context to use + * @param forceFull starts a full / slow scan if true + * @param drop drop the existing library if true + */ + public static void startLibraryScan(Context context, boolean forceFull, boolean drop) { + MediaLibraryBackend backend = getBackend(context); // also initialized sScanner + if (drop) { + sScanner.flushDatabase(); + } + + if (forceFull) { + sScanner.startFullScan(); + } else { + sScanner.startNormalScan(); + } + } + + /** + * Stops any running scan + * + * @param context the context to use + */ + public static void abortLibraryScan(Context context) { + MediaLibraryBackend backend = getBackend(context); // also initialized sScanner + sScanner.abortScan(); + } + + /** + * Whacky function to get the current scan progress + * + * @param context the context to use + * @return a description of the progress + */ + public static MediaLibrary.ScanProgress describeScanProgress(Context context) { + MediaLibraryBackend backend = getBackend(context); // also initialized sScanner + return sScanner.describeScanProgress(); + } + + /** + * Dumps a copy of the media database to a specified path. + * + * @param context the context to use. + * @param dst the destination path of the db dump. + */ + public static void createDebugDump(Context context, String dst) { + final String src = context.getDatabasePath(MediaLibraryBackend.DATABASE_NAME).getPath(); + try { + try (InputStream in = new FileInputStream(src)) { + try (OutputStream out = new FileOutputStream(dst)) { + byte[] buffer = new byte[4096]; + int len = 0; + while ((len = in.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + } + } + } catch (Exception e) { + Log.v("VanillaMusic", "Debug dump failed: "+e); + } + } + + /** + * Registers a new library observer for the media library + * + * The MediaLibrary will call `onLibraryChanged()` if + * the media library changed. + * + * `ongoing` will be set to `true` if you are expected to receive + * more updates soon. A value of `false` indicates that no + * scan is going on. + * + * @param observer the content observer we are going to call on changes + */ + public static void registerLibraryObserver(LibraryObserver observer) { + if (sLibraryObservers.contains(observer)) + throw new IllegalStateException("LibraryObserver was already registered"); + + sLibraryObservers.add(observer); + } + + /** + * Unregisters a library observer which was previously registered + * by calling registerLibraryObserver(). + * + * @param observer the content observer to unregister. + */ + public static void unregisterLibraryObserver(LibraryObserver observer) { + boolean removed = sLibraryObservers.remove(observer); + + if (!removed) + throw new IllegalArgumentException("This library observer was never registered!"); + } + + /** + * Broadcasts a change to all registered observers + * + * @param type the type of this event. + * @param id the id of type which changed, -1 if unknown + * @param ongoing whether or not to expect more of these updates soon + */ + public static void notifyObserver(LibraryObserver.Type type, long id, boolean ongoing) { + ArrayList<LibraryObserver> list = sLibraryObservers; + for (int i = list.size(); --i != -1; ) + list.get(i).onChange(type, id, ongoing); + } + + /** + * Perform a media query on the database, returns a cursor + * + * @param context the context to use + * @param table the table to query, one of MediaLibrary.TABLE_* + * @param projection the columns to returns in this query + * @param selection the selection (WHERE) to use + * @param selectionArgs arguments for the selection + * @param orderBy how the result should be sorted + */ + public static Cursor queryLibrary(Context context, String table, String[] projection, String selection, String[] selectionArgs, String orderBy) { + return getBackend(context).query(false, table, projection, selection, selectionArgs, null, null, orderBy, null); + } + + /** + * Removes a single song from the database + * + * @param context the context to use + * @param id the song id to delete + * @return the number of affected rows + */ + public static int removeSong(Context context, long id) { + int rows = getBackend(context).delete(TABLE_SONGS, SongColumns._ID+"="+id, null); + + if (rows > 0) { + getBackend(context).cleanOrphanedEntries(true); + notifyObserver(LibraryObserver.Type.SONG, id, false); + notifyObserver(LibraryObserver.Type.PLAYLIST, LibraryObserver.Value.UNKNOWN, false); + } + return rows; + } + + /** + * Updates the play or skipcount of a song + * + * @param context the context to use + * @param id the song id to update + */ + public static void updateSongPlayCounts(Context context, long id, boolean played) { + final String column = played ? MediaLibrary.SongColumns.PLAYCOUNT : MediaLibrary.SongColumns.SKIPCOUNT; + String selection = MediaLibrary.SongColumns._ID+"="+id; + getBackend(context).execSQL("UPDATE "+MediaLibrary.TABLE_SONGS+" SET "+column+"="+column+"+1 WHERE "+selection); + } + + /** + * Creates a new empty playlist + * + * @param context the context to use + * @param name the name of the new playlist + * @return long the id of the created playlist, -1 on error + */ + public static long createPlaylist(Context context, String name) { + ContentValues v = new ContentValues(); + v.put(MediaLibrary.PlaylistColumns._ID, hash63(name)); + v.put(MediaLibrary.PlaylistColumns.NAME, name); + v.put(MediaLibrary.PlaylistColumns.NAME_SORT, keyFor(name)); + long id = getBackend(context).insert(MediaLibrary.TABLE_PLAYLISTS, null, v); + + if (id != -1) + notifyObserver(LibraryObserver.Type.PLAYLIST, id, false); + return id; + } + + /** + * Deletes a playlist and all of its child elements + * + * @param context the context to use + * @param id the playlist id to delete + * @return boolean true if the playlist was deleted + */ + public static boolean removePlaylist(Context context, long id) { + // first, wipe all songs + removeFromPlaylist(context, MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"="+id, null); + int rows = getBackend(context).delete(MediaLibrary.TABLE_PLAYLISTS, MediaLibrary.PlaylistColumns._ID+"="+id, null); + boolean removed = (rows > 0); + + if (removed) + notifyObserver(LibraryObserver.Type.PLAYLIST, id, false); + return removed; + } + + /** + * Adds a batch of songs to a playlist + * + * @param context the context to use + * @param playlistId the id of the playlist parent + * @param ids an array list with the song ids to insert + * @return the number of added items + */ + public static int addToPlaylist(Context context, long playlistId, ArrayList<Long> ids) { + long pos = 0; + // First we need to get the position of the last item + String[] projection = { MediaLibrary.PlaylistSongColumns.POSITION }; + String selection = MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"="+playlistId; + String order = MediaLibrary.PlaylistSongColumns.POSITION+" DESC"; + Cursor cursor = queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS_SONGS, projection, selection, null, order); + if (cursor.moveToFirst()) + pos = cursor.getLong(0) + 1; + cursor.close(); + + ArrayList<ContentValues> bulk = new ArrayList<>(); + for (Long id : ids) { + if (getBackend(context).getColumnFromSongId(MediaLibrary.SongColumns.MTIME, id) == 0) // no mtime? song does not exist. + continue; + + ContentValues v = new ContentValues(); + v.put(MediaLibrary.PlaylistSongColumns.PLAYLIST_ID, playlistId); + v.put(MediaLibrary.PlaylistSongColumns.SONG_ID, id); + v.put(MediaLibrary.PlaylistSongColumns.POSITION, pos); + bulk.add(v); + pos++; + } + int rows = getBackend(context).bulkInsert(MediaLibrary.TABLE_PLAYLISTS_SONGS, null, bulk); + + if (rows > 0) + notifyObserver(LibraryObserver.Type.PLAYLIST, playlistId, false); + return rows; + } + + /** + * Removes a set of items from a playlist + * + * @param context the context to use + * @param selection the selection for the items to drop + * @param selectionArgs arguments for `selection' + * @return the number of deleted rows, -1 on error + */ + public static int removeFromPlaylist(Context context, String selection, String[] selectionArgs) { + // Grab the list of affected playlist id's before performing a delete. + // These are needed for the observer notification. + ArrayList<Long> playlists = new ArrayList<>(); + String[] projection = { "DISTINCT("+MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+")" }; + Cursor cursor = queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS_SONGS, projection, selection, selectionArgs, null); + while(cursor.moveToNext()) { + playlists.add(cursor.getLong(0)); + } + cursor.close(); + + int affected = 0; + if (playlists.size() > 0) { + affected = getBackend(context).delete(MediaLibrary.TABLE_PLAYLISTS_SONGS, selection, selectionArgs); + for (long id : playlists) { + notifyObserver(LibraryObserver.Type.PLAYLIST, id, false); + } + } + + return affected; + } + + /** + * Renames an existing playlist + * + * @param context the context to use + * @param playlistId the id of the playlist to rename + * @param newName the new name of the playlist + * @return the id of the new playlist, -1 on error + */ + public static long renamePlaylist(Context context, long playlistId, String newName) { + long newId = createPlaylist(context, newName); + if (newId >= 0) { + String selection = MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"="+playlistId; + ContentValues v = new ContentValues(); + v.put(MediaLibrary.PlaylistSongColumns.PLAYLIST_ID, newId); + getBackend(context).update(MediaLibrary.TABLE_PLAYLISTS_SONGS, v, selection, null); + removePlaylist(context, playlistId); + } + + if (newId != -1) { + notifyObserver(LibraryObserver.Type.PLAYLIST, playlistId, false); + notifyObserver(LibraryObserver.Type.PLAYLIST, newId, false); + } + return newId; + } + + /** + * Moves an item in a playlist. Note: both items should be in the + * same playlist - 'fun things' will happen otherwise. + * + * @param context the context to use + * @param from the _id of the 'dragged' element + * @param to the _id of the 'repressed' element + */ + public static void movePlaylistItem(Context context, long from, long to) { + long fromPos, toPos, playlistId; + + String[] projection = { MediaLibrary.PlaylistSongColumns.POSITION, MediaLibrary.PlaylistSongColumns.PLAYLIST_ID }; + String selection = MediaLibrary.PlaylistSongColumns._ID+"="; + + // Get playlist id and position of the 'from' item + Cursor cursor = queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS_SONGS, projection, selection+Long.toString(from), null, null); + cursor.moveToFirst(); + fromPos = cursor.getLong(0); + playlistId = cursor.getLong(1); + cursor.close(); + + // Get position of the target item + cursor = queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS_SONGS, projection, selection+Long.toString(to), null, null); + cursor.moveToFirst(); + toPos = cursor.getLong(0); + cursor.close(); + + // Moving down -> We actually want to be below the target + if (toPos > fromPos) + toPos++; + + // shift all rows +1 + String setArg = MediaLibrary.PlaylistSongColumns.POSITION+"="+MediaLibrary.PlaylistSongColumns.POSITION+"+1"; + selection = MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"="+playlistId+" AND "+MediaLibrary.PlaylistSongColumns.POSITION+" >= "+toPos; + getBackend(context).execSQL("UPDATE "+MediaLibrary.TABLE_PLAYLISTS_SONGS+" SET "+setArg+" WHERE "+selection); + + ContentValues v = new ContentValues(); + v.put(MediaLibrary.PlaylistSongColumns.POSITION, toPos); + selection = MediaLibrary.PlaylistSongColumns._ID+"="+from; + getBackend(context).update(MediaLibrary.TABLE_PLAYLISTS_SONGS, v, selection, null); + + notifyObserver(LibraryObserver.Type.PLAYLIST, playlistId, false); + } + + /** + * Returns the number of songs in the music library + * + * @param context the context to use + * @return the number of songs + */ + public static int getLibrarySize(Context context) { + int count = 0; + Cursor cursor = queryLibrary(context, TABLE_SONGS, new String[]{"count(*)"}, null, null, null); + if (cursor.moveToFirst()) + count = cursor.getInt(0); + cursor.close(); + return count; + } + + /** + * Returns the 'key' of given string used for sorting and searching + * + * @param name the string to convert + * @return the the key of given name + */ + public static String keyFor(String name) { + return MediaStore.Audio.keyFor(name); + } + + /** + * Simple 63 bit hash function for strings + * + * @param str the string to hash + * @return a positive long + */ + public static long hash63(String str) { + if (str == null) + return 0; + + long hash = 0; + int len = str.length(); + for (int i = 0; i < len ; i++) { + hash = 31*hash + str.charAt(i); + } + return (hash < 0 ? hash*-1 : hash); + } + + // Columns of Song entries + public interface SongColumns { + /** + * The id of this song in the database + */ + String _ID = "_id"; + /** + * The title of this song + */ + String TITLE = "title"; + /** + * The sortable title of this song + */ + String TITLE_SORT = "title_sort"; + /** + * The position in the album of this song + */ + String SONG_NUMBER = "song_num"; + /** + * The disc in a multi-disc album containing this song + */ + String DISC_NUMBER = "disc_num"; + /** + * The album where this song belongs to + */ + String ALBUM_ID = "album_id"; + /** + * The year of this song + */ + String YEAR = "year"; + /** + * How often the song was played + */ + String PLAYCOUNT = "playcount"; + /** + * How often the song was skipped + */ + String SKIPCOUNT = "skipcount"; + /** + * The duration of this song + */ + String DURATION = "duration"; + /** + * The path to the music file + */ + String PATH = "path"; + /** + * The mtime of this item + */ + String MTIME = "mtime"; + /** + * Various flags of this entry, see SONG_FLAG... + */ + String FLAGS = "_flags"; + } + + // Columns of Album entries + public interface AlbumColumns { + /** + * The id of this album in the database + */ + String _ID = SongColumns._ID; + /** + * The title of this album + */ + String ALBUM = "album"; + /** + * The sortable title of this album + */ + String ALBUM_SORT = "album_sort"; + /** + * The primary contributor / artist reference for this album + */ + String PRIMARY_ARTIST_ID = "primary_artist_id"; + /** + * The year of this album + */ + String PRIMARY_ALBUM_YEAR = "primary_album_year"; + /** + * The mtime of this item + */ + String MTIME = "mtime"; + } + + // Columns of Contributors entries + public interface ContributorColumns { + /** + * The id of this contributor + */ + String _ID = SongColumns._ID; + /** + * The name of this contributor + */ + String _CONTRIBUTOR = "_contributor"; + /** + * The sortable title of this contributor + */ + String _CONTRIBUTOR_SORT = "_contributor_sort"; + /** + * The mtime of this item + */ + String MTIME = "mtime"; + + /** + * ONLY IN VIEWS - the artist + */ + String ARTIST = "artist"; + /** + * ONLY IN VIEWS - the artist_sort key + */ + String ARTIST_SORT = "artist_sort"; + /** + * ONLY IN VIEWS - the artist id + */ + String ARTIST_ID = "artist_id"; + + /** + * ONLY IN VIEWS - the albumartist + */ + String ALBUMARTIST = "albumartist"; + /** + * ONLY IN VIEWS - the albumartist_sort key + */ + String ALBUMARTIST_SORT = "albumartist_sort"; + /** + * ONLY IN VIEWS - the albumartist id + */ + String ALBUMARTIST_ID = "albumartist_id"; + + /** + * ONLY IN VIEWS - the composer + */ + String COMPOSER = "composer"; + /** + * ONLY IN VIEWS - the composer_sort key + */ + String COMPOSER_SORT = "composer_sort"; + /** + * ONLY IN VIEWS - the composer id + */ + String COMPOSER_ID = "composer_id"; + + } + + // Songs <-> Contributor mapping + public interface ContributorSongColumns { + /** + * The role of this entry + */ + String ROLE = "role"; + /** + * the contirbutor id this maps to + */ + String _CONTRIBUTOR_ID = "_contributor_id"; + /** + * the song this maps to + */ + String SONG_ID = "song_id"; + } + + // Columns of Genres entries + public interface GenreColumns { + /** + * The id of this genre + */ + String _ID = SongColumns._ID; + /** + * The name of this genre + */ + String _GENRE = "_genre"; + /** + * The sortable title of this genre + */ + String _GENRE_SORT = "_genre_sort"; + } + + // Songs <-> Contributor mapping + public interface GenreSongColumns { + /** + * the genre id this maps to + */ + String _GENRE_ID = "_genre_id"; + /** + * the song this maps to + */ + String SONG_ID = "song_id"; + } + + // Playlists + public interface PlaylistColumns { + /** + * The id of this playlist + */ + String _ID = SongColumns._ID; + /** + * The name of this playlist + */ + String NAME = "name"; + /** + * Sortable column for name + */ + String NAME_SORT = "name_sort"; + } + + // Song <-> Playlist mapping + public interface PlaylistSongColumns { + /** + * The ID of this entry + */ + String _ID = SongColumns._ID; + /** + * The playlist this entry belongs to + */ + String PLAYLIST_ID = "playlist_id"; + /** + * The song this entry references to + */ + String SONG_ID = "song_id"; + /** + * The order attribute + */ + String POSITION = "position"; + } + + // Preference keys + public interface PreferenceColumns { + /** + * The key of this preference + */ + String KEY = "key"; + /** + * The value of this preference + */ + String VALUE = "value"; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaLibraryBackend.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaLibraryBackend.java new file mode 100644 index 0000000..3e1f0f2 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaLibraryBackend.java @@ -0,0 +1,400 @@ +/* + * Copyright (C) 2016-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +import android.content.Context; +import android.content.ContentValues; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.database.Cursor; +import android.util.Log; +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class MediaLibraryBackend extends SQLiteOpenHelper { + /** + * Enables or disables debugging + */ + private static final boolean DEBUG = false; + /** + * The database version we are using + */ + private static final int DATABASE_VERSION = 20190210; + /** + * on-disk file to store the database + */ + static final String DATABASE_NAME = "media-library.db"; + /** + * The magic mtime to use for songs which are in PENDING_DELETION state. + * This is NOT 0 as the mtime is always expected to be > 0 for existing rows + */ + private static final int PENDING_DELETION_MTIME = 1; + /** + * Regexp to detect genre queries which we can optimize + */ + private static final Pattern sQueryMatchGenreSearch = Pattern.compile("(^|.+ )"+MediaLibrary.GenreSongColumns._GENRE_ID+"=(\\d+)$"); + /** + * Regexp to detect costy artist_id queries which we can optimize + */ + private static final Pattern sQueryMatchArtistSearch = Pattern.compile("(^|.+ )"+MediaLibrary.ContributorColumns.ARTIST_ID+"=(\\d+)$"); + /** + * Regexp to detect costy albumartist_id queries which we can optimize + */ + private static final Pattern sQueryMatchAlbArtistSearch = Pattern.compile("(^|.+ )"+MediaLibrary.ContributorColumns.ALBUMARTIST_ID+"=(\\d+)$"); + /** + * Regexp to detect costy composer_id queries which we can optimize + */ + private static final Pattern sQueryMatchComposerSearch = Pattern.compile("(^|.+ )"+MediaLibrary.ContributorColumns.COMPOSER_ID+"=(\\d+)$"); + + /** + * Constructor for the MediaLibraryBackend helper + * + * @param context the context to use + */ + MediaLibraryBackend(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + /** + * Called when database does not exist + * + * @param dbh the writeable database handle + */ + @Override + public void onCreate(SQLiteDatabase dbh) { + MediaSchema.createDatabaseSchema(dbh); + } + + /** + * Called when the existing database + * schema is outdated + * + * @param dbh the writeable database handle + * @param oldVersion the current version in use + * @param newVersion the target version + */ + @Override + public void onUpgrade(SQLiteDatabase dbh, int oldVersion, int newVersion) { + MediaSchema.upgradeDatabaseSchema(dbh, oldVersion); + } + + /** + * Returns the `long' value stored in the column of the given id. + * + * @param column the column to return of `id' + * @param id the song id to query + * @return the value of `column' + */ + long getColumnFromSongId(String column, long id) { + long mtime = 0; + Cursor cursor = query(false, MediaLibrary.TABLE_SONGS, new String[]{ column }, MediaLibrary.SongColumns._ID+"="+Long.toString(id), null, null, null, null, "1"); + if (cursor.moveToFirst()) + mtime = cursor.getLong(0); + cursor.close(); + return mtime; + } + + /** + * Wrapper for SQLiteDatabse.delete() function + * + * @param table the table to delete data from + * @param whereClause the selection + * @param whereArgs arguments to selection + * @return the number of affected rows + */ + int delete(String table, String whereClause, String[] whereArgs) { + SQLiteDatabase dbh = getWritableDatabase(); + return dbh.delete(table, whereClause, whereArgs); + } + + /** + * Wrapper for SQLiteDatabase.update() function + * + * @param table the table to update + * @param values the data to set / modify + * @param whereClause the selection + * @param whereArgs arguments to selection + * @return the number of affected rows + */ + int update (String table, ContentValues values, String whereClause, String[] whereArgs) { + SQLiteDatabase dbh = getWritableDatabase(); + return dbh.update(table, values, whereClause, whereArgs); + } + + /** + * Wrapper for SQLiteDatabase.execSQL() function + * + * @param sql the raw sql string + */ + void execSQL(String sql) { + getWritableDatabase().execSQL(sql); + } + + /** + * Wrapper for SQLiteDatabase.insert() function + * + * @param table the table to insert data to + * @param nullColumnHack android hackery (see SQLiteDatabase documentation) + * @param values the values to insert + */ + long insert (String table, String nullColumnHack, ContentValues values) { + long result = -1; + try { + result = getWritableDatabase().insertOrThrow(table, nullColumnHack, values); + } catch (Exception e) { + // avoid logspam as done by insert() + } + + return result; + } + + /** + * Marks all songs as 'deleteable' - but doesn't delete them yet. + * Calling cleanOrphanedEntries() would take care of the actual deletion. + * This is a hacky way to get rid of all songs that a scan didn't touch. + */ + void setPendingDeletion() { + SQLiteDatabase dbh = getWritableDatabase(); + dbh.execSQL("UPDATE "+MediaLibrary.TABLE_SONGS+" SET "+MediaLibrary.SongColumns.MTIME+"="+PENDING_DELETION_MTIME); + } + + /** + * Purges orphaned entries from the media library + * + * @param fullCleanup also remove orphaned playlist entries and songs marked for deletion. + */ + void cleanOrphanedEntries(boolean fullCleanup) { + SQLiteDatabase dbh = getWritableDatabase(); + + // Remove all songs which are marked for deletion and playlist orphaned playlist entries. + if (fullCleanup) { + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_SONGS+" WHERE "+MediaLibrary.SongColumns.MTIME+"="+PENDING_DELETION_MTIME); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_PLAYLISTS_SONGS+" WHERE "+MediaLibrary.PlaylistSongColumns.SONG_ID+" NOT IN (SELECT "+MediaLibrary.SongColumns._ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + } + + // And remove any orphaned references. + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_ALBUMS+" WHERE "+MediaLibrary.AlbumColumns._ID+" NOT IN (SELECT "+MediaLibrary.SongColumns.ALBUM_ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_GENRES_SONGS+" WHERE "+MediaLibrary.GenreSongColumns.SONG_ID+" NOT IN (SELECT "+MediaLibrary.SongColumns._ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_GENRES+" WHERE "+MediaLibrary.GenreColumns._ID+" NOT IN (SELECT "+MediaLibrary.GenreSongColumns._GENRE_ID+" FROM "+MediaLibrary.TABLE_GENRES_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" WHERE "+MediaLibrary.ContributorSongColumns.SONG_ID+" NOT IN (SELECT "+MediaLibrary.SongColumns._ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_CONTRIBUTORS+" WHERE "+MediaLibrary.ContributorColumns._ID+" NOT IN (SELECT "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+");"); + } + + /** + * Wrapper for SQLiteDatabase.insert() function working in one transaction + * + * @param table the table to insert data to + * @param nullColumnHack android hackery (see SQLiteDatabase documentation) + * @param valuesList an array list of ContentValues to insert + * @return the number of inserted rows + */ + int bulkInsert (String table, String nullColumnHack, ArrayList<ContentValues> valuesList) { + SQLiteDatabase dbh = getWritableDatabase(); + + int count = 0; + + dbh.beginTransactionNonExclusive(); + try { + for(ContentValues values : valuesList) { + try { + long result = dbh.insertOrThrow(table, nullColumnHack, values); + if (result > 0) + count++; + } catch (Exception e) { + // avoid logspam + } + } + dbh.setTransactionSuccessful(); + } finally { + dbh.endTransaction(); + } + + return count; + } + + /** + * Wrappr for SQLiteDatabase.query() function + */ + Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { + + if (MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE.equals(table)) { + Log.v("VanillaMusic", "+++ warning : using HUGE table in genquery!"); + } + + if (selection != null) { + if (MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS.equals(table)) { + // artist matches in the song-view are costy: try to give sqlite a hint + String[] contributorMatch = extractVirtualColumn(selection); + if (contributorMatch != null) { + selection = contributorMatch[0]; + final String contributorId = contributorMatch[1]; + final String contributorRole = contributorMatch[2]; + + selection += MediaLibrary.SongColumns._ID+" IN (SELECT "+MediaLibrary.ContributorSongColumns.SONG_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" WHERE " + + MediaLibrary.ContributorSongColumns.ROLE+"="+contributorRole+" AND "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+"="+contributorId+")"; + } + } + + if (MediaLibrary.VIEW_ALBUMS_ARTISTS.equals(table)) { + // looking up artists by albums will magically return every album where this + // artist has at least one item (while still using the primary_artist_id as the artist key) + String[] contributorMatch = extractVirtualColumn(selection); + if (contributorMatch != null) { + selection = contributorMatch[0]; + final String contributorId = contributorMatch[1]; + final String contributorRole = contributorMatch[2]; + + selection += MediaLibrary.SongColumns._ID+" IN (SELECT DISTINCT "+MediaLibrary.SongColumns.ALBUM_ID+" FROM "+MediaLibrary.TABLE_SONGS+" WHERE " + + MediaLibrary.SongColumns._ID+" IN (SELECT "+MediaLibrary.ContributorSongColumns.SONG_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" WHERE " + + MediaLibrary.ContributorSongColumns.ROLE+"="+contributorRole+" AND "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+"="+contributorId+"))"; + } + } + + // Genre queries are a special beast: 'optimize' all of them + Matcher genreMatch = sQueryMatchGenreSearch.matcher(selection); + if (genreMatch.matches()) { + selection = genreMatch.group(1); // keep the non-genre search part of the query + final String genreId = genreMatch.group(2); // and extract the searched genre id + final String songsQuery = buildSongIdFromGenreSelect(genreId); + + if(table.equals(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS) || + table.equals(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE) ) { + selection += MediaLibrary.SongColumns._ID+" IN ("+songsQuery+") "; + } + + if (table.equals(MediaLibrary.VIEW_ALBUMS_ARTISTS)) { + selection += MediaLibrary.AlbumColumns._ID+" IN ("+ + buildSongIdFromGenreSelect(MediaLibrary.SongColumns.ALBUM_ID, MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, songsQuery)+") "; + } + + if (table.equals(MediaLibrary.VIEW_ARTISTS)) { + selection += MediaLibrary.ContributorColumns.ARTIST_ID+" IN ("+ + buildSongIdFromGenreSelect(MediaLibrary.ContributorColumns.ARTIST_ID, MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, songsQuery)+") "; + } + + if (table.equals(MediaLibrary.VIEW_ALBUMARTISTS)) { + selection += MediaLibrary.ContributorColumns.ALBUMARTIST_ID+" IN ("+ + buildSongIdFromGenreSelect(MediaLibrary.ContributorColumns.ALBUMARTIST_ID, MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE, songsQuery)+") "; + Log.v("VanillaMusic", "+++ warning: huge genrequery for albumartist!"); + } + + if (table.equals(MediaLibrary.VIEW_COMPOSERS)) { + selection += MediaLibrary.ContributorColumns.COMPOSER_ID+" IN ("+ + buildSongIdFromGenreSelect(MediaLibrary.ContributorColumns.COMPOSER_ID, MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE, songsQuery)+") "; + Log.v("VanillaMusic", "+++ warning: huge genrequery composer!"); + } + + } + } + + if (DEBUG) + debugQuery(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); + + Cursor cursor = getReadableDatabase().query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); + if (cursor != null) { + // Hold on! This is not some kind of black magic - it makes '''sense''': + // SQLites count() performance is pretty poor, but most queries will call getCount() during their + // lifetime anyway - unfortunately this might happen in the main thread, causing some lag. + // Androids SQLite class caches the result of getCount() calls, so we are going to run it + // here as we are (hopefully!) in a background thread anyway. + cursor.getCount(); + } + return cursor; + } + + /** + * Detects queries for artists, composers and albumartists and returns the + * role of the contributor. + * + * @param sql the raw sql query + * @return String[]{ sql-part, contributor-id, contributor-role } + */ + private String[] extractVirtualColumn(String sql) { + final Pattern[] pattern = new Pattern[]{ sQueryMatchArtistSearch, sQueryMatchComposerSearch, sQueryMatchAlbArtistSearch }; + final int[] roles = { MediaLibrary.ROLE_ARTIST, MediaLibrary.ROLE_COMPOSER, MediaLibrary.ROLE_ALBUMARTIST }; + + for (int i=0; i < roles.length; i++) { + Matcher matcher = pattern[i].matcher(sql); + if (matcher.matches()) { + return new String[]{ matcher.group(1), matcher.group(2), String.format("%d", roles[i]) }; + } + } + return null; + } + + /** + * Returns a select query to get all songs from a genre + * + * @param genreId the id to query as a string + * @return an SQL string which should return song id's for the queried genre + */ + private String buildSongIdFromGenreSelect(String genreId) { + return "SELECT "+MediaLibrary.GenreSongColumns.SONG_ID+" FROM "+MediaLibrary.TABLE_GENRES_SONGS+" WHERE " + +MediaLibrary.GenreSongColumns._GENRE_ID+"="+genreId+" GROUP BY "+MediaLibrary.GenreSongColumns.SONG_ID; + } + + /** + * Returns a select query to get artists or albums from a genre + * + * @param target the target to query + * @param table the table to query + * @param genreSelect the select string generated by buildSongIdFromGenreSelect + * @return an SQL string + */ + private String buildSongIdFromGenreSelect(String target, String table, String genreSelect) { + return "SELECT "+target+" FROM "+ table +" WHERE " + +MediaLibrary.SongColumns._ID+" IN ("+genreSelect+") GROUP BY "+target; + } + + /** + * Debug function to print and benchmark queries + */ + private void debugQuery(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { + final String LT = "VanillaMusicSQL"; + Log.v(LT, "---- start query ---"); + Log.v(LT, "SELECT"); + for (String c : columns) { + Log.v(LT, " "+c); + } + Log.v(LT, "FROM "+table+" WHERE "+selection+" "); + if (selectionArgs != null) { + Log.v(LT, " /* with args: "); + for (String a : selectionArgs) { + Log.v(LT, a+", "); + } + Log.v(LT, " */"); + } + Log.v(LT, " GROUP BY "+groupBy+" HAVING "+having+" ORDER BY "+orderBy+" LIMIT "+limit); + + Log.v(LT, "DBH = "+getReadableDatabase()); + + Cursor dryRun = getReadableDatabase().query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); + long results = 0; + long startAt = System.currentTimeMillis(); + if (dryRun != null) { + while(dryRun.moveToNext()) { + results++; + } + dryRun.close(); + } + long tookMs = System.currentTimeMillis() - startAt; + Log.v(LT, "--- finished in "+tookMs+" ms with count="+results); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaMetadataExtractor.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaMetadataExtractor.java new file mode 100644 index 0000000..109ff8d --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaMetadataExtractor.java @@ -0,0 +1,508 @@ +/* + * Copyright (C) 2016 - 2022 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +import ch.blinkenlights.bastp.Bastp; +import android.media.MediaMetadataRetriever; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import java.io.FileInputStream; +import java.io.IOException; + +import android.util.Log; +public class MediaMetadataExtractor extends HashMap<String, ArrayList<String>> { + // Well known tags + public final static String ALBUM = "ALBUM"; + public final static String ALBUMARTIST = "ALBUM_ARTIST"; + public final static String ARTIST = "ARTIST"; + public final static String BITRATE = "BITRATE"; + public final static String COMPOSER = "COMPOSER"; + public final static String DISC_COUNT = "DISC_COUNT"; + public final static String DISC_NUMBER = "DISC_NUMBER"; + public final static String DURATION = "DURATION"; + public final static String GENRE = "GENRE"; + public final static String MIME_TYPE = "MIME"; + public final static String TRACK_COUNT = "TRACK_COUNT"; + public final static String TRACK_NUMBER = "TRACK_NUM"; + public final static String TITLE = "TITLE"; + public final static String YEAR = "YEAR"; + + /** + * Regexp used to match a year in a date field + */ + private static final Pattern sFilterYear = Pattern.compile(".*(\\d{4}).*"); + /** + * Regexp matching the first lefthand integer + */ + private static final Pattern sFilterLeftInt = Pattern.compile("^0*(\\d+).*$"); + /** + * Regexp matching anything + */ + private static final Pattern sFilterAny = Pattern.compile("^([\\s\\S]*)$"); + /** + * Regexp matching possible genres + */ + private static final Pattern sFilterGenre = Pattern.compile("^\\s*\\(?(\\d+)\\)?\\s*$"); + /** + * Genres as defined by androids own MediaScanner.java + */ + private static final String[] ID3_GENRES = { + "Blues", + "Classic Rock", + "Country", + "Dance", + "Disco", + "Funk", + "Grunge", + "Hip-Hop", + "Jazz", + "Metal", + "New Age", + "Oldies", + "Other", + "Pop", + "R&B", + "Rap", + "Reggae", + "Rock", + "Techno", + "Industrial", + "Alternative", + "Ska", + "Death Metal", + "Pranks", + "Soundtrack", + "Euro-Techno", + "Ambient", + "Trip-Hop", + "Vocal", + "Jazz+Funk", + "Fusion", + "Trance", + "Classical", + "Instrumental", + "Acid", + "House", + "Game", + "Sound Clip", + "Gospel", + "Noise", + "AlternRock", + "Bass", + "Soul", + "Punk", + "Space", + "Meditative", + "Instrumental Pop", + "Instrumental Rock", + "Ethnic", + "Gothic", + "Darkwave", + "Techno-Industrial", + "Electronic", + "Pop-Folk", + "Eurodance", + "Dream", + "Southern Rock", + "Comedy", + "Cult", + "Gangsta", + "Top 40", + "Christian Rap", + "Pop/Funk", + "Jungle", + "Native American", + "Cabaret", + "New Wave", + "Psychadelic", + "Rave", + "Showtunes", + "Trailer", + "Lo-Fi", + "Tribal", + "Acid Punk", + "Acid Jazz", + "Polka", + "Retro", + "Musical", + "Rock & Roll", + "Hard Rock", + // The following genres are Winamp extensions + "Folk", + "Folk-Rock", + "National Folk", + "Swing", + "Fast Fusion", + "Bebob", + "Latin", + "Revival", + "Celtic", + "Bluegrass", + "Avantgarde", + "Gothic Rock", + "Progressive Rock", + "Psychedelic Rock", + "Symphonic Rock", + "Slow Rock", + "Big Band", + "Chorus", + "Easy Listening", + "Acoustic", + "Humour", + "Speech", + "Chanson", + "Opera", + "Chamber Music", + "Sonata", + "Symphony", + "Booty Bass", + "Primus", + "Porn Groove", + "Satire", + "Slow Jam", + "Club", + "Tango", + "Samba", + "Folklore", + "Ballad", + "Power Ballad", + "Rhythmic Soul", + "Freestyle", + "Duet", + "Punk Rock", + "Drum Solo", + "A capella", + "Euro-House", + "Dance Hall", + "Goa", + "Drum & Bass", + "Club-House", + "Hardcore", + "Terror", + "Indie", + "Britpop", + "Negerpunk", + "Polsk Punk", + "Beat", + "Christian Gangsta", + "Heavy Metal", + "Black Metal", + "Crossover", + "Contemporary Christian", + "Christian Rock", + "Merengue", + "Salsa", + "Thrash Metal", + "Anime", + "JPop", + "Synthpop", + // 148 goes here, Winamp 5.6 would have 148 -> 191 these ¯\_(ツ)_/¯ + }; + + /** + * True if we consider the file to be a good media item + */ + private boolean mIsMediaFile = false; + /** + * True if we should try bastp for 'experimental' formats + */ + private boolean mForceBastp = false; + + /** + * Constructor for MediaMetadataExtractor + * + * @param path the path to scan + */ + public MediaMetadataExtractor(String path) { + this(path, false); + } + + /** + * Constructor for MediaMetadataExtractor + * + * @param path the path to scan + * @param forceBastp always prefer bastp if possible + */ + public MediaMetadataExtractor(String path, boolean forceBastp) { + mForceBastp = forceBastp; + extractMetadata(path); + } + + /** + * Returns the first element matching this key, null on if not found + * + * @param key the key to look up + * @return the value of the first entry, null if the key was not found + */ + public String getFirst(String key) { + String result = null; + if (containsKey(key)) + result = get(key).get(0); + return result; + } + + /** + * @return a human-friendly description of the mime type and bit rate + */ + public String getFormat() { + StringBuilder sb = new StringBuilder(18); + sb.append(decodeMimeType(getFirst(MIME_TYPE))); + String bitrate = getFirst(BITRATE); + if (bitrate != null && bitrate.length() > 3) { + sb.append(' ') + .append(bitrate.substring(0, bitrate.length() - 3)) + .append("kbps"); + } + return sb.toString(); + } + + /** + * Returns true if this file contains any (interesting) data + * @return true if file is considered to be media data + */ + public boolean isMediaFile() { + return mIsMediaFile; + } + + /** + * Attempts to populate this instance with tags found in given path + * + * @param path the path to parse + */ + private void extractMetadata(String path) { + if (!isEmpty()) + throw new IllegalStateException("Expected to be called on a clean HashMap"); + + Log.v("VanillaMusic", "Extracting tags from "+path); + + HashMap bastpTags = (new Bastp()).getTags(path); + MediaMetadataRetriever mediaTags = new MediaMetadataRetriever(); + boolean nativelyReadable = false; + + try { + FileInputStream fis = new FileInputStream(path); + try { + mediaTags.setDataSource(fis.getFD()); + nativelyReadable = true; + } catch (Exception e) { + Log.v("VanillaMusic", "Error calling setDataSource for "+path+": "+e); + } + fis.close(); + } catch (Exception e) { + nativelyReadable = false; + Log.v("VanillaMusic", "Error creating fis for "+path+": "+e); + } + + // Check if this is a usable audio file + if (!nativelyReadable || + mediaTags.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO) == null || + mediaTags.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO) != null || + mediaTags.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) == null) { + try { + mediaTags.release(); + } catch (IOException e) { + Log.v("VanillaMusic", "mediaTags.release() failed: " + e); + } + + return; + } + + // Bastp can not read the duration and bitrates, so we always get it from the system + ArrayList<String> duration = new ArrayList<>(1); + duration.add(mediaTags.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)); + this.put(DURATION, duration); + + ArrayList<String> bitrate = new ArrayList<>(1); + bitrate.add(mediaTags.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)); + this.put(BITRATE, bitrate); + + ArrayList<String> mime = new ArrayList<>(1); + mime.add(mediaTags.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)); + this.put(MIME_TYPE, mime); + + + // ...but we are using bastp for FLAC, OGG and OPUS as it handles them well + // Everything else goes to the framework (such as pcm, m4a and mp3) + String bastpType = (bastpTags.containsKey("type") ? (String)bastpTags.get("type") : ""); + switch (bastpType) { + case "FLAC": + case "OGG": + case "OPUS": + populateSelf(bastpTags); + break; + case "MP3/ID3v2": + case "MP3/Lame": + case "MP4": + // ^-- these tagreaders are not fully stable, but can be enabled on demand + if(mForceBastp) { + populateSelf(bastpTags); + break; + } + // else: fallthrough + default: + populateSelf(mediaTags); + } + convertNumericGenre(); + + // We consider this a media file if it has some common tags OR + // if bastp was able to parse it (which is stricter than Android's own parser) + mIsMediaFile = (containsKey(TITLE) || containsKey(ALBUM) || containsKey(ARTIST) || !bastpType.equals("")); + + try { + mediaTags.release(); + } catch (IOException e) { + Log.v("VanillaMusic", "mediaTags.release() failed: " + e); + } + } + + /** + * Populates `this' with tags read from bastp + * + * @param bastp A hashmap as returned by bastp + */ + private void populateSelf(HashMap bastp) { + // mapping between vorbiscomment -> constant + String[] map = new String[]{ "TITLE", TITLE, "ARTIST", ARTIST, "ALBUM", ALBUM, "ALBUMARTIST", ALBUMARTIST, "COMPOSER", COMPOSER, "GENRE", GENRE, + "TRACKNUMBER", TRACK_NUMBER, "TRACKTOTAL", TRACK_COUNT, "DISCNUMBER", DISC_NUMBER, "DISCTOTAL", DISC_COUNT, + "YEAR", YEAR }; + // switch to integer filter if i >= x + int filterByIntAt = 12; + // the filter we are normally using + Pattern filter = sFilterAny; + + for (int i=0; i<map.length; i+=2) { + if (i >= filterByIntAt) + filter = sFilterLeftInt; + + if (bastp.containsKey(map[i])) { + addFiltered(filter, map[i+1], (ArrayList<String>)bastp.get(map[i])); + } + } + + // If only one of (ARTIST, ALBUMARTIST) is present, populate the other + if (!containsKey(ARTIST) && containsKey(ALBUMARTIST)) { + put(ARTIST, get(ALBUMARTIST)); + } + if (containsKey(ARTIST) && !containsKey(ALBUMARTIST)) { + put(ALBUMARTIST, get(ARTIST)); + } + + // Try to guess YEAR from date field if only DATE was specified + // We expect it to match \d{4} + if (!containsKey(YEAR) && bastp.containsKey("DATE")) { + addFiltered(sFilterYear, YEAR, (ArrayList<String>)bastp.get("DATE")); + } + + } + + /** + * Populates `this' with tags read from the MediaMetadataRetriever + * + * @param tags a MediaMetadataRetriever object + */ + private void populateSelf(MediaMetadataRetriever tags) { + int[] mediaMap = new int[] { MediaMetadataRetriever.METADATA_KEY_TITLE, MediaMetadataRetriever.METADATA_KEY_ARTIST, MediaMetadataRetriever.METADATA_KEY_ALBUM, + MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST, MediaMetadataRetriever.METADATA_KEY_COMPOSER, MediaMetadataRetriever.METADATA_KEY_GENRE, + MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER, MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER, MediaMetadataRetriever.METADATA_KEY_YEAR }; + String[] selfMap = new String[]{ TITLE, ARTIST, ALBUM, ALBUMARTIST, COMPOSER, GENRE, DISC_NUMBER, TRACK_NUMBER, YEAR }; + int filterByIntAt = 6; + Pattern filter = sFilterAny; + + for (int i=0; i<selfMap.length; i++) { + String data = tags.extractMetadata(mediaMap[i]); + if (i >= filterByIntAt) + filter = sFilterLeftInt; + + if (data != null) { + ArrayList<String> md = new ArrayList<String>(1); + md.add(data); + addFiltered(filter, selfMap[i], md); + } + } + } + + /** + * Matches all elements of `data' with `filter' and adds the result as `key' + * + * @param filter the pattern to use, result is expected to be in capture group 1 + * @param key the key to use for the data to put + * @param data the array list to inspect + */ + private void addFiltered(Pattern filter, String key, ArrayList<String> data) { + ArrayList<String> list = new ArrayList<>(); + for (String s : data) { + Matcher matcher = filter.matcher(s); + if (matcher.matches()) { + list.add(matcher.group(1).trim()); + } + } + if (list.size() > 0) + put(key, list); + } + + /** + * Detects legacy numeric-genre definitions and + * replaces them with one of ID3_GENRES[] + */ + private void convertNumericGenre() { + int genreIdx = -1; + String rawGenre = getFirst(GENRE); + + if (rawGenre == null) + return; // no genre, nothing to do + + Matcher matcher = sFilterGenre.matcher(rawGenre); + if (matcher.matches()) { + try { + genreIdx = Integer.parseInt(matcher.group(1)); + } catch (NumberFormatException e) {} // ignored + } + + if (genreIdx >= 0 && genreIdx < ID3_GENRES.length) { + ArrayList<String> data = new ArrayList<String>(1); + data.add(ID3_GENRES[genreIdx]); + remove(GENRE); + addFiltered(sFilterAny, GENRE, data); + } + } + + /** + * Decode the given MIME type into a more human-friendly description. + * + * @return a human-friendly description of the MIME type + */ + private static String decodeMimeType(String mime) + { + if ("audio/mpeg".equals(mime)) { + return "MP3"; + } else if ("audio/mp4".equals(mime)) { + return "AAC"; + } else if ("audio/vorbis".equals(mime)) { + return "Ogg Vorbis"; + } else if ("application/ogg".equals(mime)) { + return "Ogg Vorbis"; + } else if ("audio/flac".equals(mime)) { + return "FLAC"; + } + return mime; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaMigrations.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaMigrations.java new file mode 100644 index 0000000..c77e273 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaMigrations.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +import android.content.ContentValues; +import android.database.sqlite.SQLiteDatabase; +import android.database.Cursor; +import android.util.Log; + + +public class MediaMigrations { + /** + * Migrate to 20180416 + * That is: populate NAME_SORT in the new source database + * + * @param dbh the database to work on + * @param fromDb the name of the source database + * @param toDb the name of the target database + **/ + static void migrate_to_20180416(SQLiteDatabase dbh, String fromDb, String toDb) { + Cursor cursor = dbh.query(fromDb, new String[]{MediaLibrary.PlaylistColumns._ID, MediaLibrary.PlaylistColumns.NAME}, null, null, null, null, null); + while (cursor.moveToNext()) { + long id = cursor.getLong(0); + String name = cursor.getString(1); + String key = MediaLibrary.keyFor(name); + + Log.v("VanillaMusic", "migrate_to_20180416 -> id="+id+", name="+name+" -> key = "+key); + ContentValues v = new ContentValues(); + v.put(MediaLibrary.PlaylistColumns._ID, id); + v.put(MediaLibrary.PlaylistColumns.NAME, name); + v.put(MediaLibrary.PlaylistColumns.NAME_SORT, key); + dbh.insert(toDb, null, v); + } + cursor.close(); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaScanner.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaScanner.java new file mode 100644 index 0000000..6b2a289 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaScanner.java @@ -0,0 +1,832 @@ +/* + * Copyright (C) 2016-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +import ch.blinkenlights.android.vanilla.R; +import ch.blinkenlights.android.vanilla.NotificationHelper; + +import android.app.Notification; +import android.content.Context; +import android.content.ContentValues; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.database.ContentObserver; +import android.util.Log; +import android.provider.MediaStore; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Message; +import android.os.PowerManager; +import android.os.Process; +import android.os.SystemClock; + +import java.io.File; +import java.util.ArrayList; +import java.util.regex.Pattern; + +public class MediaScanner implements Handler.Callback { + /** + * Our scan plan + */ + private MediaScanPlan mScanPlan; + /** + * Our message handler + */ + private Handler mHandler; + /** + * The context to use for native library queries + */ + private Context mContext; + /** + * The wake lock we hold during the scan + */ + private PowerManager.WakeLock mWakeLock; + /** + * Instance of a media backend + */ + private MediaLibraryBackend mBackend; + /** + * True if this is a from-scratch import + * Set by KICKSTART rpc + */ + private boolean mIsInitialScan; + /** + * True if we are currently in a scan phase + */ + private boolean mScanIsRunning; + /** + * True if we must do a full cleanup of orphaned entries after the scan finished. + */ + private boolean mPendingCleanup; + /** + * Our NotificationHelper instance. + */ + private NotificationHelper mNotificationHelper; + /** + * uptimeMillis ts at which we will dispatch the next scan update report + */ + private long mNextProgressReportAt; + /** + * The id we are using for the scan notification + */ + private static final int NOTIFICATION_ID = 56162; + /** + * The notification channel to use + */ + private static final String NOTIFICATION_CHANNEL = "Scanner"; + /** + * Relax mtime check while searching for native modifications by this many seconds + */ + private static final int NATIVE_VRFY_MTIME_SLACK = 100; + /** + * Delay native scans by this many ms to coalesce multiple modifications + */ + private static final int NATIVE_VRFY_COALESCE_DELAY = 3500; + + MediaScanner(Context context, MediaLibraryBackend backend) { + mContext = context; + mBackend = backend; + mScanPlan = new MediaScanPlan(); + HandlerThread handlerThread = new HandlerThread("MediaScannerThread", Process.THREAD_PRIORITY_LOWEST); + handlerThread.start(); + mHandler = new Handler(handlerThread.getLooper(), this); + mWakeLock = ((PowerManager)context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VanillaMusic:Indexer"); + mNotificationHelper = new NotificationHelper(context, NOTIFICATION_CHANNEL, context.getString(R.string.media_stats_progress)); + + // the content observer to use + ContentObserver mObserver = new ContentObserver(null) { + @Override + public void onChange(boolean self) { + startQuickScan(NATIVE_VRFY_COALESCE_DELAY); + } + }; + context.getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mObserver); + } + + /** + * Performs a 'fast' scan by checking the native and our own + * library for new and changed files + */ + public void startNormalScan() { + setNativeLastMtime(MTIME_DIRTY); + mScanPlan.addNextStep(RPC_NATIVE_VRFY, null) + .addNextStep(RPC_LIBRARY_VRFY, null); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_KICKSTART, 0)); + } + + /** + * Performs a 'slow' scan by inspecting all files on the device + */ + public void startFullScan() { + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(mContext); + for (String path : prefs.mediaFolders) { + mScanPlan.addNextStep(RPC_READ_DIR, new File(path)); + } + mScanPlan.addNextStep(RPC_LIBRARY_VRFY, null); + mScanPlan.addNextStep(RPC_NATIVE_VRFY, null); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_KICKSTART, 0)); + } + + /** + * Called by the content observer if a change in the media library + * has been detected + * + * @param delay how many ms we should wait (used to coalesce multiple calls) + */ + public void startQuickScan(int delay) { + if (!mHandler.hasMessages(MSG_GUESS_QUICKSCAN) && !mHandler.hasMessages(MSG_SCAN_RPC)) { + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_GUESS_QUICKSCAN, 0, 0), delay); + } + } + + /** + * Stops a running scan + */ + public void abortScan() { + mHandler.removeMessages(MSG_SCAN_RPC); + mScanPlan.clear(); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_KICKSTART, 0)); + } + + /** + * Prepares a flush of the databse. + */ + public void flushDatabase() { + mBackend.setPendingDeletion(); + mPendingCleanup = true; + setNativeLastMtime(MTIME_PRISTINE); + } + + /** + * Returns some scan statistics + * + * @return a MediaLibrary.ScanProgress object + */ + public MediaLibrary.ScanProgress describeScanProgress() { + MediaLibrary.ScanProgress progress = new MediaLibrary.ScanProgress(); + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(mContext); + MediaScanPlan.Statistics stats = mScanPlan.getStatistics(); + + progress.isRunning = mScanIsRunning; + progress.lastFile = stats.lastFile; + progress.seen = stats.seen; + progress.changed = stats.changed; + progress.total = prefs._nativeLibraryCount; + + return progress; + } + + private static final int MSG_SCAN_RPC = 0; + private static final int MSG_SCAN_FINISHED = 1; + private static final int MSG_NOTIFY_CHANGE = 2; + private static final int MSG_GUESS_QUICKSCAN = 3; + private static final int RPC_KICKSTART = 100; + private static final int RPC_READ_DIR = 101; + private static final int RPC_INSPECT_FILE = 102; + private static final int RPC_LIBRARY_VRFY = 103; + private static final int RPC_NATIVE_VRFY = 104; + + @Override + public boolean handleMessage(Message message) { + int rpc = (message.what == MSG_SCAN_RPC ? message.arg1 : message.what); + + switch (rpc) { + case MSG_NOTIFY_CHANGE: { + MediaLibrary.notifyObserver(LibraryObserver.Type.SONG, LibraryObserver.Value.UNKNOWN, true); + break; + } + case MSG_SCAN_FINISHED: { + mScanIsRunning = false; + if (mIsInitialScan) { + mIsInitialScan = false; + MediaLibrary.notifyObserver(LibraryObserver.Type.PLAYLIST, LibraryObserver.Value.OUTDATED, false); + } + if (mPendingCleanup) { + mPendingCleanup = false; + mBackend.cleanOrphanedEntries(true); + // scan run possibly deleted file which may affect playlists: + MediaLibrary.notifyObserver(LibraryObserver.Type.PLAYLIST, LibraryObserver.Value.UNKNOWN, false); + } + + // Send a last change notification to all observers. + // This lets all consumers know about (possible) + // cleanups of orphaned files. The `false' value + // also signals that this will be our last update + // for this scan. + mHandler.removeMessages(MSG_NOTIFY_CHANGE); + MediaLibrary.notifyObserver(LibraryObserver.Type.SONG, LibraryObserver.Value.UNKNOWN, false); + MediaLibrary.notifyObserver(LibraryObserver.Type.SCAN_PROGRESS, LibraryObserver.Value.UNKNOWN, false); + + updateNotification(false); + break; + } + case MSG_GUESS_QUICKSCAN: { + guessQuickScanPlan(); + break; + } + case RPC_KICKSTART: { + // a new scan was triggered: check if this is a 'initial / from scratch' scan + if (!mIsInitialScan && MediaLibrary.getPreferences(mContext)._nativeLastMtime == 0) { + mIsInitialScan = true; + } + break; + } + case RPC_INSPECT_FILE: { + final File file = (File)message.obj; + boolean changed = rpcInspectFile(file); + mScanPlan.registerProgress(file.toString(), changed); + if (changed && !mHandler.hasMessages(MSG_NOTIFY_CHANGE)) { + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_NOTIFY_CHANGE), 500); + } + + // Unlike MSG_NOTIFY_CHANGE, we don't want the progress report to lag behind, but we also don't want + // to call it on EVERY file inspection; so we add our own delay which will not be influenced by + // the message queue size. + long now = SystemClock.uptimeMillis(); + if (now >= mNextProgressReportAt) { + mNextProgressReportAt = now + 80; + MediaLibrary.notifyObserver(LibraryObserver.Type.SCAN_PROGRESS, LibraryObserver.Value.UNKNOWN, true); + updateNotification(true); + } + break; + } + case RPC_READ_DIR: { + rpcReadDirectory((File)message.obj); + break; + } + case RPC_LIBRARY_VRFY: { + rpcLibraryVerify((Cursor)message.obj); + break; + } + case RPC_NATIVE_VRFY: { + rpcNativeVerify((Cursor)message.obj, message.arg2); + break; + } + default: { + throw new IllegalArgumentException(); + } + } + + if (message.what == MSG_SCAN_RPC && !mHandler.hasMessages(MSG_SCAN_RPC)) { + mScanIsRunning = true; + MediaScanPlan.Step step = mScanPlan.getNextStep(); + if (step == null) { + mHandler.sendEmptyMessage(MSG_SCAN_FINISHED); + } else { + Log.v("VanillaMusic", "xxx --- starting scan of type "+step.msg); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, step.msg, 0, step.arg)); + } + } + + return true; + } + + private static final int MTIME_PRISTINE = 0; + private static final int MTIME_DIRTY = 1; + /** + * Updates the _nativeLastMtime value in the media scanner storage + * + * @param mtime or one of MTIME_* + */ + private void setNativeLastMtime(int mtime) { + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(mContext); + prefs._nativeLastMtime = mtime; + MediaLibrary.setPreferences(mContext, prefs); + } + + /** + * Triggers an update to the scan progress notification + * + * @param visible if true, the notification is visible (and will get updated) + */ + private void updateNotification(boolean visible) { + MediaLibrary.ScanProgress progress = describeScanProgress(); + + if (visible) { + // We there are 5 drawables, pick one based on the 'uptime-seconds'. + int tick = (int)(SystemClock.uptimeMillis() / 1000) % 5; + int icon = R.drawable.status_scan_0 + tick; + String title = mContext.getResources().getString(R.string.media_library_scan_running); + String content = progress.lastFile; + Notification notification = mNotificationHelper.getNewBuilder(mContext) + .setProgress(progress.total, progress.seen, false) + .setContentTitle(title) + .setContentText(content) + .setSmallIcon(icon) + .setOngoing(true) + .getNotification(); // build() is API 16 :-/ + mNotificationHelper.notify(NOTIFICATION_ID, notification); + + if (!mWakeLock.isHeld()) + mWakeLock.acquire(); + } else { + mNotificationHelper.cancel(NOTIFICATION_ID); + + if (mWakeLock.isHeld()) + mWakeLock.release(); + } + } + + /** + * Checks the state of the native media db to deceide if we are going to + * check for deleted or new/modified items + */ + private void guessQuickScanPlan() { + int lastSeenDbSize = MediaLibrary.getPreferences(mContext)._nativeLibraryCount; + String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0"; + String[] projection = { "COUNT("+MediaStore.Audio.Media.IS_MUSIC+")" }; + Cursor cursor = null; + try { + cursor = mContext.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null, null); + } catch (SecurityException e) { + Log.e("VanillaMusic", "rpcObserveRemoval query failed: "+e); + } + + if (cursor == null) + return; + + cursor.moveToFirst(); + int currentDbSize = cursor.getInt(0); + cursor.close(); + + // Store new db size + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(mContext); + prefs._nativeLibraryCount = currentDbSize; + MediaLibrary.setPreferences(mContext, prefs); + + if (currentDbSize < lastSeenDbSize) { + // db is smaller! check for deleted files + mScanPlan.addNextStep(RPC_LIBRARY_VRFY, null); + } else { + // same size or more entries -> check only for modifications + mScanPlan.addNextStep(RPC_NATIVE_VRFY, null); + } + + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_KICKSTART, 0)); + } + + /** + * Scans the android library, inspecting every found file + * + * @param cursor the cursor we are using + * @param mtime the mtime to carry over, ignored if cursor is null + */ + private void rpcNativeVerify(Cursor cursor, int mtime) { + if (cursor == null) { + mtime = MediaLibrary.getPreferences(mContext)._nativeLastMtime; // starting a new scan -> read stored mtime from preferences + String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0 AND "+ MediaStore.MediaColumns.DATE_MODIFIED +" > " + (mtime - NATIVE_VRFY_MTIME_SLACK); + String sort = MediaStore.MediaColumns.DATE_MODIFIED; + String[] projection = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_MODIFIED }; + try { + cursor = mContext.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null, sort); + } catch(SecurityException e) { + Log.e("VanillaMusic", "rpcNativeVerify failed: "+e); + } + } + + if (cursor == null) + return; // still null.. fixme: handle me better + + if (cursor.moveToNext()) { + String path = cursor.getString(0); + mtime = cursor.getInt(1); + if (path != null) { // this seems to be a thing... + File entry = new File(path); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_INSPECT_FILE, 0, entry)); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_NATIVE_VRFY, mtime, cursor)); + } + } else { + cursor.close(); + setNativeLastMtime(mtime); + Log.v("VanillaMusic", "NativeLibraryScanner finished, mtime mark is now at "+mtime); + } + } + + /** + * Scans every file in our own library and checks for changes + * + * @param cursor the cursor we are using + */ + private void rpcLibraryVerify(Cursor cursor) { + if (cursor == null) + cursor = mBackend.query(false, MediaLibrary.TABLE_SONGS, new String[]{MediaLibrary.SongColumns.PATH}, null, null, null, null, null, null); + + if (cursor.moveToNext()) { + File entry = new File(cursor.getString(0)); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_INSPECT_FILE, 0, entry)); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, RPC_LIBRARY_VRFY, 0, cursor)); + } else { + cursor.close(); + } + } + + /** + * Loops trough given directory and adds all found + * files to the scan queue + * + * @param dir the directory to scan + */ + private void rpcReadDirectory(File dir) { + if (!dir.isDirectory()) + return; + + if (new File(dir, ".nomedia").exists()) + return; + + if (isDotfile(dir)) + return; + + File[] dirents = dir.listFiles(); + if (dirents == null) + return; + + for (File file : dirents) { + int rpc = (file.isFile() ? RPC_INSPECT_FILE : RPC_READ_DIR); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SCAN_RPC, rpc, 0, file)); + } + } + + /** + * Checks if a string is null, empty or whitespace. + * + * @param s the string to check + * @return true if null, empty or whitespace + */ + private static boolean isUnset(String s) { + return s == null || s.trim().isEmpty(); + } + + + /** + * Inspects a single file and adds it to the database or removes it. maybe. + * + * @param file the file to add + * @return true if we modified the database + */ + private boolean rpcInspectFile(File file) { + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(mContext); + String path = file.getAbsolutePath(); + long songId = MediaLibrary.hash63(path); + + if (isBlacklisted(file)) + return false; + + if (isDotfile(file)) + return false; + + long dbEntryMtime = mBackend.getColumnFromSongId(MediaLibrary.SongColumns.MTIME, songId) * 1000; // this is in unixtime -> convert to 'ms' + long songFlags = mBackend.getColumnFromSongId(MediaLibrary.SongColumns.FLAGS, songId); + long fileMtime = file.lastModified(); + long playCount = 0; + long skipCount = 0; + boolean hasChanged = false; + boolean mustInsert = false; + + if (fileMtime > 0 && dbEntryMtime >= fileMtime && (songFlags & MediaLibrary.SONG_FLAG_OUTDATED) == 0) { + return false; // on-disk mtime is older than db mtime and it still exists -> nothing to do + } + + if (dbEntryMtime != 0) { + // DB entry exists but is outdated - drop current entry and maybe re-insert it + // this tries to preserve play and skipcounts of the song + playCount = mBackend.getColumnFromSongId(MediaLibrary.SongColumns.PLAYCOUNT, songId); + skipCount = mBackend.getColumnFromSongId(MediaLibrary.SongColumns.SKIPCOUNT, songId); + // Remove the song from the database for now but do not delete any + // playlist references to it. + mBackend.delete(MediaLibrary.TABLE_SONGS, MediaLibrary.SongColumns._ID+"="+songId, null); + mBackend.cleanOrphanedEntries(false); + mPendingCleanup = true; // Ensure that we run a full cleanup after all scans finished, to get rid of orphaned playlist entries. + hasChanged = true; // notify caller about change even if we are not going to re-insert this file. + } + + // Check if we are willing to insert this file + // This is the case if we consider it to be playable on this device. + MediaMetadataExtractor tags = new MediaMetadataExtractor(path, prefs.forceBastp); + mustInsert = tags.isMediaFile(); + + if (mustInsert) { + hasChanged = true; + + // Clear old flags of this song: + songFlags &= ~MediaLibrary.SONG_FLAG_OUTDATED; // This file is not outdated anymore + songFlags &= ~MediaLibrary.SONG_FLAG_NO_ARTIST; // May find an artist now. + songFlags &= ~MediaLibrary.SONG_FLAG_NO_ALBUM; // May find an album now. + + // Get tags which always must be set + String title = tags.getFirst(MediaMetadataExtractor.TITLE); + if (isUnset(title)) + title = file.getName(); + + String album = tags.getFirst(MediaMetadataExtractor.ALBUM); + if (isUnset(album)) { + album = "<No Album>"; + songFlags |= MediaLibrary.SONG_FLAG_NO_ALBUM; + } + + String artist = tags.getFirst(MediaMetadataExtractor.ARTIST); + if (isUnset(artist)) { + artist = "<No Artist>"; + songFlags |= MediaLibrary.SONG_FLAG_NO_ARTIST; + } + + String discNumber = tags.getFirst(MediaMetadataExtractor.DISC_NUMBER); + if (isUnset(discNumber)) + discNumber = "1"; // untagged, but most likely '1' - this prevents annoying sorting issues with partially tagged files + + long artistId = MediaLibrary.hash63(artist); + long albumId = MediaLibrary.hash63(album); + + // Overwrite albumId with a hash that included the parent dir if set in preferences + if (prefs.groupAlbumsByFolder) { + albumId = MediaLibrary.hash63(album + "\n" + file.getParent()); + } + + ContentValues v = new ContentValues(); + v.put(MediaLibrary.SongColumns._ID, songId); + v.put(MediaLibrary.SongColumns.TITLE, title); + v.put(MediaLibrary.SongColumns.TITLE_SORT, MediaLibrary.keyFor(title)); + v.put(MediaLibrary.SongColumns.ALBUM_ID, albumId); + v.put(MediaLibrary.SongColumns.DURATION, tags.getFirst(MediaMetadataExtractor.DURATION)); + v.put(MediaLibrary.SongColumns.SONG_NUMBER, tags.getFirst(MediaMetadataExtractor.TRACK_NUMBER)); + v.put(MediaLibrary.SongColumns.DISC_NUMBER, discNumber); + v.put(MediaLibrary.SongColumns.YEAR, tags.getFirst(MediaMetadataExtractor.YEAR)); + v.put(MediaLibrary.SongColumns.PLAYCOUNT, playCount); + v.put(MediaLibrary.SongColumns.SKIPCOUNT, skipCount); + v.put(MediaLibrary.SongColumns.PATH, path); + v.put(MediaLibrary.SongColumns.FLAGS, songFlags); + mBackend.insert(MediaLibrary.TABLE_SONGS, null, v); + + v.clear(); + v.put(MediaLibrary.AlbumColumns._ID, albumId); + v.put(MediaLibrary.AlbumColumns.ALBUM, album); + v.put(MediaLibrary.AlbumColumns.ALBUM_SORT, MediaLibrary.keyFor(album)); + v.put(MediaLibrary.AlbumColumns.PRIMARY_ARTIST_ID, artistId); + v.put(MediaLibrary.AlbumColumns.PRIMARY_ALBUM_YEAR,tags.getFirst(MediaMetadataExtractor.YEAR)); + long albumInsert = mBackend.insert(MediaLibrary.TABLE_ALBUMS, null, v); + if (albumInsert == -1) { + // Insert failed, so the column probably already existed. + // We need to ensure that the album table is up-to-date as it contains + // some 'cached' (PRIMARY_*) values. + // Failure to do so would mean that we never update the year or may point to an + // orphaned artist id. + v.clear(); + v.put(MediaLibrary.AlbumColumns.PRIMARY_ARTIST_ID, artistId); + v.put(MediaLibrary.AlbumColumns.PRIMARY_ALBUM_YEAR,tags.getFirst(MediaMetadataExtractor.YEAR)); + mBackend.update(MediaLibrary.TABLE_ALBUMS, v, MediaLibrary.AlbumColumns._ID+"=?", new String[]{ Long.toString(albumId) }); + } + + v.clear(); + v.put(MediaLibrary.ContributorColumns._ID, artistId); + v.put(MediaLibrary.ContributorColumns._CONTRIBUTOR, artist); + v.put(MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT, MediaLibrary.keyFor(artist)); + mBackend.insert(MediaLibrary.TABLE_CONTRIBUTORS, null, v); + + v.clear(); + v.put(MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID, artistId); + v.put(MediaLibrary.ContributorSongColumns.SONG_ID, songId); + v.put(MediaLibrary.ContributorSongColumns.ROLE, MediaLibrary.ROLE_ARTIST); + mBackend.insert(MediaLibrary.TABLE_CONTRIBUTORS_SONGS, null, v); + + // Composers are optional: only add if we found it + String composer = tags.getFirst(MediaMetadataExtractor.COMPOSER); + if (composer != null) { + long composerId = MediaLibrary.hash63(composer); + v.clear(); + v.put(MediaLibrary.ContributorColumns._ID, composerId); + v.put(MediaLibrary.ContributorColumns._CONTRIBUTOR, composer); + v.put(MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT, MediaLibrary.keyFor(composer)); + mBackend.insert(MediaLibrary.TABLE_CONTRIBUTORS, null, v); + + v.clear(); + v.put(MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID, composerId); + v.put(MediaLibrary.ContributorSongColumns.SONG_ID, songId); + v.put(MediaLibrary.ContributorSongColumns.ROLE, MediaLibrary.ROLE_COMPOSER); + mBackend.insert(MediaLibrary.TABLE_CONTRIBUTORS_SONGS, null, v); + } + + // Same as with composer: albumartist is an optional tag + String albumartist = tags.getFirst(MediaMetadataExtractor.ALBUMARTIST); + if (albumartist != null) { + long albumartistId = MediaLibrary.hash63(albumartist); + v.clear(); + v.put(MediaLibrary.ContributorColumns._ID, albumartistId); + v.put(MediaLibrary.ContributorColumns._CONTRIBUTOR, albumartist); + v.put(MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT, MediaLibrary.keyFor(albumartist)); + mBackend.insert(MediaLibrary.TABLE_CONTRIBUTORS, null, v); + + v.clear(); + v.put(MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID, albumartistId); + v.put(MediaLibrary.ContributorSongColumns.SONG_ID, songId); + v.put(MediaLibrary.ContributorSongColumns.ROLE, MediaLibrary.ROLE_ALBUMARTIST); + mBackend.insert(MediaLibrary.TABLE_CONTRIBUTORS_SONGS, null, v); + } + + // A song might be in multiple genres + if (tags.containsKey(MediaMetadataExtractor.GENRE)) { + ArrayList<String> genres = tags.get(MediaMetadataExtractor.GENRE); + for (String genre : genres) { + long genreId = MediaLibrary.hash63(genre); + v.clear(); + v.put(MediaLibrary.GenreColumns._ID, genreId); + v.put(MediaLibrary.GenreColumns._GENRE, genre); + v.put(MediaLibrary.GenreColumns._GENRE_SORT, MediaLibrary.keyFor(genre)); + mBackend.insert(MediaLibrary.TABLE_GENRES, null, v); + + v.clear(); + v.put(MediaLibrary.GenreSongColumns._GENRE_ID, genreId); + v.put(MediaLibrary.GenreSongColumns.SONG_ID, songId); + mBackend.insert(MediaLibrary.TABLE_GENRES_SONGS, null, v); + } + } + } // end if (mustInsert) + + Log.v("VanillaMusic", "MediaScanner: inserted "+path); + return hasChanged; + } + + private static final Pattern sIgnoredFilenames = Pattern.compile("^([^\\.]+|.+\\.(jpe?g|gif|png|bmp|webm|txt|pdf|avi|mp4|mkv|zip|tgz|xml|tmp|bin))$", Pattern.CASE_INSENSITIVE); + /** + * Returns true if the file should not be scanned + * + * @param file the file to inspect + * @return boolean + */ + private boolean isBlacklisted(File file) { + if (sIgnoredFilenames.matcher(file.getName()).matches()) + return true; + + int wlPoints = -1; + int blPoints = -1; + + for (String path : MediaLibrary.getPreferences(mContext).mediaFolders) { + if (path.length() > wlPoints && + file.getPath().toLowerCase().startsWith(path.toLowerCase())) { + wlPoints = path.length(); + } + } + + for (String path : MediaLibrary.getPreferences(mContext).blacklistedFolders) { + if (path.length() > blPoints && + file.getPath().toLowerCase().startsWith(path.toLowerCase())) { + blPoints = path.length(); + } + } + + // Consider a file to be blacklisted if it is not + // present in any whitelisted dir OR if we found + // a blacklist entry with a longer prefix. + return (wlPoints < 0 || blPoints > wlPoints); + } + + + private static final Pattern sDotfilePattern = Pattern.compile("^\\..*$", Pattern.CASE_INSENSITIVE); + /** + * Returns true if the file is a hidden dotfile. + * + * @param file to inspect + * @return boolean + */ + private boolean isDotfile(File file) { + return sDotfilePattern.matcher(file.getName()).matches(); + } + + // MediaScanPlan describes how we are going to perform the media scan + class MediaScanPlan { + class Step { + private static final int MODE_NORMAL = 1; // this step is always run + private static final int MODE_OPTIONAL = 2; // only run if previous step found NO changes + private static final int MODE_CHAINED = 3; // only run if previous step DID find changes + int msg; + Object arg; + int mode; + Step (int msg, Object arg, int mode) { + this.msg = msg; + this.arg = arg; + this.mode = mode; + } + } + + class Statistics { + String lastFile; + int seen = 0; + int changed = 0; + void reset() { + this.seen = 0; + this.changed = 0; + this.lastFile = null; + } + } + + /** + * All steps in this plan + */ + private ArrayList<Step> mSteps; + /** + * Statistics of the currently running step + */ + private Statistics mStats; + + MediaScanPlan() { + mSteps = new ArrayList<>(); + mStats = new Statistics(); + } + + Statistics getStatistics() { + return mStats; + } + + /** + * Called by the scanner to signal that a file was handled + * + * @param path the file we scanned + * @param changed true if this triggered a database update + */ + void registerProgress(String path, boolean changed) { + mStats.lastFile = path; + mStats.seen++; + if (changed) { + mStats.changed++; + } + } + + /** + * Flushes all progress, turning the object into a fresh state + */ + void clear() { + mSteps.clear(); + mStats.reset(); + } + + /** + * Adds the next step in our plan + * + * @param msg the message to add + * @param arg the argument to msg + */ + MediaScanPlan addNextStep(int msg, Object arg) { + mSteps.add(new Step(msg, arg, Step.MODE_NORMAL)); + return this; + } + + /** + * Adds an optional step to our plan. This will NOT + * run if the previous step caused database changes + * + * @param msg the message to add + * @param arg the argument to msg + */ + MediaScanPlan addOptionalStep(int msg, Object arg) { + mSteps.add(new Step(msg, arg, Step.MODE_OPTIONAL)); + return this; + } + + /** + * Adds a chained step to our plan. This will ONLY + * run if the previous step caused database changes + * + * @param msg the message to add + * @param arg the argument to msg + */ + MediaScanPlan addChainedStep(int msg, Object arg) { + mSteps.add(new Step(msg, arg, Step.MODE_CHAINED)); + return this; + } + + /** + * Returns the next step of our scan plan + * + * @return a new step object, null if we hit the end + */ + Step getNextStep() { + Step next = (mSteps.size() != 0 ? mSteps.remove(0) : null); + if (next != null) { + if (next.mode == Step.MODE_OPTIONAL && mStats.changed != 0) { + next = null; + mSteps.clear(); + } + if (next.mode == Step.MODE_CHAINED && mStats.changed == 0) { + next = null; + mSteps.clear(); + } + } + mStats.reset(); + return next; + } + } +} + diff --git a/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaSchema.java b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaSchema.java new file mode 100644 index 0000000..8c21065 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/medialibrary/MediaSchema.java @@ -0,0 +1,369 @@ +/* + * Copyright (C) 2016-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.medialibrary; + +import android.database.sqlite.SQLiteDatabase; + +public class MediaSchema { + /** + * SQL Schema of `songs' table + */ + private static final String DATABASE_CREATE_SONGS = "CREATE TABLE "+ MediaLibrary.TABLE_SONGS + " (" + + MediaLibrary.SongColumns._ID +" INTEGER PRIMARY KEY, " + + MediaLibrary.SongColumns.TITLE +" TEXT NOT NULL, " + + MediaLibrary.SongColumns.TITLE_SORT +" VARCHAR(64) NOT NULL, " + + MediaLibrary.SongColumns.SONG_NUMBER +" INTEGER, " + + MediaLibrary.SongColumns.DISC_NUMBER +" INTEGER, " + + MediaLibrary.SongColumns.YEAR +" INTEGER, " + + MediaLibrary.SongColumns.ALBUM_ID +" INTEGER NOT NULL, " + + MediaLibrary.SongColumns.PLAYCOUNT +" INTEGER NOT NULL DEFAULT 0, " + + MediaLibrary.SongColumns.SKIPCOUNT +" INTEGER NOT NULL DEFAULT 0, " + + MediaLibrary.SongColumns.MTIME +" TIMESTAMP DEFAULT (strftime('%s', CURRENT_TIMESTAMP)), " + + MediaLibrary.SongColumns.DURATION +" INTEGER NOT NULL, " + + MediaLibrary.SongColumns.PATH +" VARCHAR(4096) NOT NULL, " + + MediaLibrary.SongColumns.FLAGS +" INTEGER NOT NULL DEFAULT 0 " + + ");"; + + /** + * SQL Schema of `albums' table + */ + private static final String DATABASE_CREATE_ALBUMS = "CREATE TABLE "+ MediaLibrary.TABLE_ALBUMS + " (" + + MediaLibrary.AlbumColumns._ID +" INTEGER PRIMARY KEY, " + + MediaLibrary.AlbumColumns.ALBUM +" TEXT NOT NULL, " + + MediaLibrary.AlbumColumns.ALBUM_SORT +" VARCHAR(64) NOT NULL, " + + MediaLibrary.AlbumColumns.PRIMARY_ALBUM_YEAR+" INTEGER, " + + MediaLibrary.AlbumColumns.PRIMARY_ARTIST_ID +" INTEGER NOT NULL DEFAULT 0, " + + MediaLibrary.AlbumColumns.MTIME +" TIMESTAMP DEFAULT CURRENT_TIMESTAMP " + + ");"; + + /** + * SQL Schema of `contributors' table + */ + private static final String DATABASE_CREATE_CONTRIBUTORS = "CREATE TABLE "+ MediaLibrary.TABLE_CONTRIBUTORS + " (" + + MediaLibrary.ContributorColumns._ID +" INTEGER PRIMARY KEY, " + + MediaLibrary.ContributorColumns._CONTRIBUTOR +" TEXT NOT NULL, " + + MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT +" TEXT NOT NULL, " + + MediaLibrary.ContributorColumns.MTIME +" TIMESTAMP DEFAULT CURRENT_TIMESTAMP " + + ");"; + + /** + * SQL Schema of 'contributors<->songs' table + */ + private static final String DATABASE_CREATE_CONTRIBUTORS_SONGS = "CREATE TABLE "+ MediaLibrary.TABLE_CONTRIBUTORS_SONGS+ " (" + + MediaLibrary.ContributorSongColumns.ROLE +" INTEGER, " + + MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID +" INTEGER, " + + MediaLibrary.ContributorSongColumns.SONG_ID +" INTEGER, " + + "PRIMARY KEY("+MediaLibrary.ContributorSongColumns.ROLE+"," + +MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+"," + +MediaLibrary.ContributorSongColumns.SONG_ID+") " + + ");"; + + /** + * song, role index on contributors_songs table + */ + private static final String NAME_IDX_CONTRIBUTORS_SONGS = "idx_contributors_songs"; + private static final String INDEX_IDX_CONTRIBUTORS_SONGS = "CREATE INDEX "+NAME_IDX_CONTRIBUTORS_SONGS+" ON "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS + +" ("+MediaLibrary.ContributorSongColumns.SONG_ID+", "+MediaLibrary.ContributorSongColumns.ROLE+")" + +";"; + + /** + * SQL Schema of `genres' table + */ + private static final String DATABASE_CREATE_GENRES = "CREATE TABLE "+ MediaLibrary.TABLE_GENRES + " (" + + MediaLibrary.GenreColumns._ID +" INTEGER PRIMARY KEY, " + + MediaLibrary.GenreColumns._GENRE +" TEXT NOT NULL, " + + MediaLibrary.GenreColumns._GENRE_SORT +" TEXT NOT NULL " + + ");"; + + /** + * SQL Schema of 'genres<->songs' table + */ + private static final String DATABASE_CREATE_GENRES_SONGS = "CREATE TABLE "+ MediaLibrary.TABLE_GENRES_SONGS + " (" + + MediaLibrary.GenreSongColumns._GENRE_ID +" INTEGER, " + + MediaLibrary.GenreSongColumns.SONG_ID +" INTEGER, " + + "PRIMARY KEY("+MediaLibrary.GenreSongColumns._GENRE_ID+"," + +MediaLibrary.GenreSongColumns.SONG_ID+") " + + ");"; + + /** + * SQL Schema for the playlists table + */ + private static final String DATABASE_CREATE_PLAYLISTS = "CREATE TABLE "+ MediaLibrary.TABLE_PLAYLISTS +" (" + + MediaLibrary.PlaylistColumns._ID +" INTEGER PRIMARY KEY, " + + MediaLibrary.PlaylistColumns.NAME +" TEXT NOT NULL, " + + MediaLibrary.PlaylistColumns.NAME_SORT +" TEXT NOT NULL " + + ");"; + + /** + * SQL Schema of 'songs<->playlists' table + */ + private static final String DATABASE_CREATE_PLAYLISTS_SONGS = "CREATE TABLE "+ MediaLibrary.TABLE_PLAYLISTS_SONGS + " (" + + MediaLibrary.PlaylistSongColumns._ID +" INTEGER PRIMARY KEY, " + + MediaLibrary.PlaylistSongColumns.PLAYLIST_ID +" INTEGER NOT NULL, " + + MediaLibrary.PlaylistSongColumns.SONG_ID +" INTEGER NOT NULL, " + + MediaLibrary.PlaylistSongColumns.POSITION +" INTEGER NOT NULL " + + ");"; + + /** + * Index to select a playlist quickly + */ + private static final String INDEX_IDX_PLAYLIST_ID = "CREATE INDEX idx_playlist_id ON "+MediaLibrary.TABLE_PLAYLISTS_SONGS + +" ("+MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+")" + +";"; + + /** + * Index to select a song from a playlist quickly + */ + private static final String INDEX_IDX_PLAYLIST_ID_SONG = "CREATE INDEX idx_playlist_id_song ON "+MediaLibrary.TABLE_PLAYLISTS_SONGS + +" ("+MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+", "+MediaLibrary.PlaylistSongColumns.SONG_ID+")" + +";"; + + /** + * Additional columns to select for artist info + */ + private static final String VIEW_ARTIST_SELECT = "_artist."+MediaLibrary.ContributorColumns._CONTRIBUTOR+" AS "+MediaLibrary.ContributorColumns.ARTIST + +",_artist."+MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT+" AS "+MediaLibrary.ContributorColumns.ARTIST_SORT + +",_artist."+MediaLibrary.ContributorColumns._ID+" AS "+MediaLibrary.ContributorColumns.ARTIST_ID; + + /** + * Additional columns to select for albumartist info + */ + private static final String VIEW_ALBUMARTIST_SELECT = "_albumartist."+MediaLibrary.ContributorColumns._CONTRIBUTOR+" AS "+MediaLibrary.ContributorColumns.ALBUMARTIST + +",_albumartist."+MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT+" AS "+MediaLibrary.ContributorColumns.ALBUMARTIST_SORT + +",_albumartist."+MediaLibrary.ContributorColumns._ID+" AS "+MediaLibrary.ContributorColumns.ALBUMARTIST_ID; + + /** + * Additional columns to select for composer info + */ + private static final String VIEW_COMPOSER_SELECT = "_composer."+MediaLibrary.ContributorColumns._CONTRIBUTOR+" AS "+MediaLibrary.ContributorColumns.COMPOSER + +",_composer."+MediaLibrary.ContributorColumns._CONTRIBUTOR_SORT+" AS "+MediaLibrary.ContributorColumns.COMPOSER_SORT + +",_composer."+MediaLibrary.ContributorColumns._ID+" AS "+MediaLibrary.ContributorColumns.COMPOSER_ID; + + + /** + * View which includes song, album and artist information, enough for a filled song projection + */ + private static final String VIEW_CREATE_SONGS_ALBUMS_ARTISTS = "CREATE VIEW "+ MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS+ " AS " + + "SELECT *, " + VIEW_ARTIST_SELECT + " FROM " + MediaLibrary.TABLE_SONGS + +" LEFT JOIN "+MediaLibrary.TABLE_ALBUMS+" ON "+MediaLibrary.TABLE_SONGS+"."+MediaLibrary.SongColumns.ALBUM_ID+" = "+MediaLibrary.TABLE_ALBUMS+"."+MediaLibrary.AlbumColumns._ID + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" INDEXED BY "+NAME_IDX_CONTRIBUTORS_SONGS + +" ON "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+"."+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_ARTIST + +" AND "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+"."+MediaLibrary.ContributorSongColumns.SONG_ID+" = "+MediaLibrary.TABLE_SONGS+"."+MediaLibrary.SongColumns._ID + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _artist ON _artist."+MediaLibrary.ContributorColumns._ID+" = "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+"."+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID + +" ;"; + + /** + * View wich includes SONGS_ALBUMS_ARTISTS and any other contributors + * This view should only be used if needed as the SQL query is pretty expensive + */ + private static final String VIEW_CREATE_SONGS_ALBUMS_ARTISTS_HUGE = "CREATE VIEW "+ MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE+" AS " + + "SELECT *, "+ VIEW_ALBUMARTIST_SELECT +", "+ VIEW_COMPOSER_SELECT +" FROM "+MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS + // albumartists + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" as __albumartists INDEXED BY "+NAME_IDX_CONTRIBUTORS_SONGS + +" ON __albumartists."+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_ALBUMARTIST + +" AND __albumartists."+MediaLibrary.ContributorSongColumns.SONG_ID+" = "+MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS+"."+MediaLibrary.SongColumns._ID + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _albumartist ON" + +" _albumartist."+MediaLibrary.ContributorColumns._ID+" = __albumartists."+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID + // composers + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" as __composers INDEXED BY "+NAME_IDX_CONTRIBUTORS_SONGS + +" ON __composers."+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_COMPOSER + +" AND __composers."+MediaLibrary.ContributorSongColumns.SONG_ID+" = "+MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS+"."+MediaLibrary.SongColumns._ID + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _composer ON" + +" _composer."+MediaLibrary.ContributorColumns._ID+" = __composers."+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID + +" ;"; + + /** + * View which includes album and artist information + */ + private static final String VIEW_CREATE_ALBUMS_ARTISTS = "CREATE VIEW "+ MediaLibrary.VIEW_ALBUMS_ARTISTS+ " AS " + + "SELECT " + MediaLibrary.TABLE_ALBUMS + ".*, " + VIEW_ARTIST_SELECT + ", SUM(" + MediaLibrary.SongColumns.DURATION + ")" + " AS " + MediaLibrary.SongColumns.DURATION + +" FROM " + MediaLibrary.TABLE_ALBUMS + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _artist" + +" ON _artist."+MediaLibrary.ContributorColumns._ID+" = "+MediaLibrary.TABLE_ALBUMS+"."+MediaLibrary.AlbumColumns.PRIMARY_ARTIST_ID + +" LEFT JOIN " + MediaLibrary.TABLE_SONGS + +" ON " + MediaLibrary.TABLE_SONGS + "." + MediaLibrary.SongColumns.ALBUM_ID + " = " + MediaLibrary.TABLE_ALBUMS + "." + MediaLibrary.AlbumColumns._ID + +" GROUP BY " + MediaLibrary.TABLE_ALBUMS + "." + MediaLibrary.AlbumColumns._ID + +" ;"; + + /** + * View which includes artist information + */ + private static final String VIEW_CREATE_ARTISTS = "CREATE VIEW "+ MediaLibrary.VIEW_ARTISTS+ " AS " + + "SELECT *, " + VIEW_ARTIST_SELECT + " FROM "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _artist WHERE "+MediaLibrary.ContributorColumns._ID+" IN " + +" (SELECT "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS + +" WHERE "+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_ARTIST+" GROUP BY "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+")" + +" ;"; + + /** + * View which includes albumArtists information + */ + private static final String VIEW_CREATE_ALBUMARTISTS = "CREATE VIEW "+ MediaLibrary.VIEW_ALBUMARTISTS+ " AS " + + "SELECT *, " + VIEW_ALBUMARTIST_SELECT + " FROM "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _albumartist WHERE "+MediaLibrary.ContributorColumns._ID+" IN " + +" (SELECT "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS + +" WHERE "+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_ALBUMARTIST+" GROUP BY "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+")" + +" ;"; + + /** + * View which includes composer information + */ + private static final String VIEW_CREATE_COMPOSERS = "CREATE VIEW "+ MediaLibrary.VIEW_COMPOSERS+ " AS " + + "SELECT *, " + VIEW_COMPOSER_SELECT + " FROM "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _composer WHERE "+MediaLibrary.ContributorColumns._ID+" IN " + +" (SELECT "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS + +" WHERE "+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_COMPOSER+" GROUP BY "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+")" + +" ;"; + + /** + * View like VIEW_CREATE_ARTISTS but includes playlist information + */ + private static final String VIEW_CREATE_PLAYLISTS_SONGS = "CREATE VIEW "+ MediaLibrary.VIEW_PLAYLISTS_SONGS+" AS " + + "SELECT *, " + VIEW_ARTIST_SELECT + " FROM " + MediaLibrary.TABLE_PLAYLISTS_SONGS + +" LEFT JOIN "+MediaLibrary.TABLE_SONGS+" ON "+MediaLibrary.TABLE_PLAYLISTS_SONGS+"."+MediaLibrary.PlaylistSongColumns.SONG_ID+"="+MediaLibrary.TABLE_SONGS+"."+MediaLibrary.SongColumns._ID + // -> same sql as VIEW_CREATE_SONGS_ALBUMS_ARTISTS follows: + +" LEFT JOIN "+MediaLibrary.TABLE_ALBUMS+" ON "+MediaLibrary.TABLE_SONGS+"."+MediaLibrary.SongColumns.ALBUM_ID+" = "+MediaLibrary.TABLE_ALBUMS+"."+MediaLibrary.AlbumColumns._ID + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" INDEXED BY "+NAME_IDX_CONTRIBUTORS_SONGS + +" ON "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+"."+MediaLibrary.ContributorSongColumns.ROLE+"="+MediaLibrary.ROLE_ARTIST + +" AND "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+"."+MediaLibrary.ContributorSongColumns.SONG_ID+" = "+MediaLibrary.TABLE_SONGS+"."+MediaLibrary.SongColumns._ID + +" LEFT JOIN "+MediaLibrary.TABLE_CONTRIBUTORS+" AS _artist ON _artist."+MediaLibrary.ContributorColumns._ID+" = "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+"."+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID + +" ;"; + + /** + * View of all playlists, including additional information such as the duration. + */ + private static final String VIEW_CREATE_PLAYLISTS = "CREATE VIEW "+ MediaLibrary.VIEW_PLAYLISTS+ " AS " + + "SELECT " + MediaLibrary.TABLE_PLAYLISTS + ".*, SUM(_s." + MediaLibrary.SongColumns.DURATION + ") AS " + MediaLibrary.SongColumns.DURATION + " FROM " + MediaLibrary.TABLE_PLAYLISTS + +" LEFT JOIN " + MediaLibrary.TABLE_PLAYLISTS_SONGS + " AS _ps ON " + MediaLibrary.TABLE_PLAYLISTS + "." + MediaLibrary.PlaylistColumns._ID +" = _ps." + MediaLibrary.PlaylistSongColumns.PLAYLIST_ID + +" LEFT JOIN " + MediaLibrary.TABLE_SONGS + " AS _s ON _s." + MediaLibrary.SongColumns._ID + " = _ps." + MediaLibrary.PlaylistSongColumns.SONG_ID + +" GROUP BY " + MediaLibrary.TABLE_PLAYLISTS + "." + MediaLibrary.PlaylistColumns._ID + +" ;"; + + /** + * Creates a new database schema on dbh + * + * @param dbh the writeable dbh to act on + */ + public static void createDatabaseSchema(SQLiteDatabase dbh) { + dbh.execSQL(DATABASE_CREATE_SONGS); + dbh.execSQL(DATABASE_CREATE_ALBUMS); + dbh.execSQL(DATABASE_CREATE_CONTRIBUTORS); + dbh.execSQL(DATABASE_CREATE_CONTRIBUTORS_SONGS); + dbh.execSQL(INDEX_IDX_CONTRIBUTORS_SONGS); + dbh.execSQL(DATABASE_CREATE_GENRES); + dbh.execSQL(DATABASE_CREATE_GENRES_SONGS); + dbh.execSQL(DATABASE_CREATE_PLAYLISTS); + dbh.execSQL(DATABASE_CREATE_PLAYLISTS_SONGS); + dbh.execSQL(INDEX_IDX_PLAYLIST_ID); + dbh.execSQL(INDEX_IDX_PLAYLIST_ID_SONG); + dbh.execSQL(VIEW_CREATE_SONGS_ALBUMS_ARTISTS); + dbh.execSQL(VIEW_CREATE_SONGS_ALBUMS_ARTISTS_HUGE); + dbh.execSQL(VIEW_CREATE_ALBUMS_ARTISTS); + dbh.execSQL(VIEW_CREATE_ARTISTS); + dbh.execSQL(VIEW_CREATE_ALBUMARTISTS); + dbh.execSQL(VIEW_CREATE_COMPOSERS); + dbh.execSQL(VIEW_CREATE_PLAYLISTS); + dbh.execSQL(VIEW_CREATE_PLAYLISTS_SONGS); + } + + /** + * Upgrades an existing database + * + * @param dbh the writeable dbh to use + * @param oldVersion the version of the old (aka: existing) database + */ + public static void upgradeDatabaseSchema(SQLiteDatabase dbh, int oldVersion) { + if (oldVersion < 20170101) { + // this is ugly but was never released as a stable version, so + // it's good enough to keep playlists for testers + dbh.execSQL("DROP TABLE songs"); + dbh.execSQL("DROP TABLE albums"); + dbh.execSQL(DATABASE_CREATE_SONGS); + dbh.execSQL(DATABASE_CREATE_ALBUMS); + } + + if (oldVersion < 20170102) { + dbh.execSQL("UPDATE songs SET disc_num=1 WHERE disc_num IS null"); + } + + if (oldVersion < 20170211) { + // older versions of triggerFullMediaScan did this by mistake + dbh.execSQL("UPDATE songs SET mtime=1 WHERE mtime=0"); + } + + if (oldVersion < 20170217) { + dbh.execSQL(VIEW_CREATE_ALBUMARTISTS); + dbh.execSQL(VIEW_CREATE_COMPOSERS); + dbh.execSQL(VIEW_CREATE_SONGS_ALBUMS_ARTISTS_HUGE); + } + + if (oldVersion >= 20170120 && oldVersion < 20170407) { + dbh.execSQL("DROP TABLE preferences"); + } + + if (oldVersion >= 20170407 && oldVersion < 20170608) { + // renames were buggy for some time -> get rid of duplicates + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_SONGS+" WHERE "+MediaLibrary.SongColumns._ID+" IN ("+ + "SELECT "+MediaLibrary.SongColumns._ID+" FROM "+MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS+" GROUP BY "+ + MediaLibrary.SongColumns._ID+" HAVING count("+MediaLibrary.SongColumns._ID+") > 1)"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_ALBUMS+" WHERE "+MediaLibrary.AlbumColumns._ID+" NOT IN (SELECT "+MediaLibrary.SongColumns.ALBUM_ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_GENRES_SONGS+" WHERE "+MediaLibrary.GenreSongColumns.SONG_ID+" NOT IN (SELECT "+MediaLibrary.SongColumns._ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_GENRES+" WHERE "+MediaLibrary.GenreColumns._ID+" NOT IN (SELECT "+MediaLibrary.GenreSongColumns._GENRE_ID+" FROM "+MediaLibrary.TABLE_GENRES_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+" WHERE "+MediaLibrary.ContributorSongColumns.SONG_ID+" NOT IN (SELECT "+MediaLibrary.SongColumns._ID+" FROM "+MediaLibrary.TABLE_SONGS+");"); + dbh.execSQL("DELETE FROM "+MediaLibrary.TABLE_CONTRIBUTORS+" WHERE "+MediaLibrary.ContributorColumns._ID+" NOT IN (SELECT "+MediaLibrary.ContributorSongColumns._CONTRIBUTOR_ID+" FROM "+MediaLibrary.TABLE_CONTRIBUTORS_SONGS+");"); + } + + if (oldVersion < 20170619) { + // Android 4.x tends to not use idx_contributors_songs, resulting in full table scans. + // We will force the use of this index on views doing a LEFT JOIN as it doesn't cause + // any harm to newer sqlite versions. (We know that this is the best index to use). + dbh.execSQL("DROP VIEW "+MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS); + dbh.execSQL("DROP VIEW "+MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE); + dbh.execSQL("DROP VIEW "+MediaLibrary.VIEW_PLAYLISTS_SONGS); + dbh.execSQL(VIEW_CREATE_SONGS_ALBUMS_ARTISTS); + dbh.execSQL(VIEW_CREATE_SONGS_ALBUMS_ARTISTS_HUGE); + dbh.execSQL(VIEW_CREATE_PLAYLISTS_SONGS); + } + + if (oldVersion >= 20170211 && oldVersion < 20180129) { + // Minor indexer changes - invalidate (but do not drop) all + // existing entries. + dbh.execSQL("UPDATE songs SET mtime=1"); + } + + if (oldVersion < 20180305) { + dbh.execSQL("ALTER TABLE "+MediaLibrary.TABLE_SONGS+" ADD COLUMN "+MediaLibrary.SongColumns.FLAGS+" INTEGER NOT NULL DEFAULT 0 "); + } + + if (oldVersion < 20180416) { + // This adds NAME_SORT, so we need to pre-populate all keys. + dbh.execSQL("ALTER TABLE "+MediaLibrary.TABLE_PLAYLISTS+" RENAME TO _migrate"); + dbh.execSQL(MediaSchema.DATABASE_CREATE_PLAYLISTS); + MediaMigrations.migrate_to_20180416(dbh, "_migrate", MediaLibrary.TABLE_PLAYLISTS); + dbh.execSQL("DROP TABLE _migrate"); + } + + if (oldVersion < 20181021) { + // Recreate view to include album duration + dbh.execSQL("DROP VIEW " + MediaLibrary.VIEW_ALBUMS_ARTISTS); + dbh.execSQL(VIEW_CREATE_ALBUMS_ARTISTS); + } + + if (oldVersion < 20190210) { + dbh.execSQL(VIEW_CREATE_PLAYLISTS); + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/Action.java b/app/src/main/java/ch/blinkenlights/android/vanilla/Action.java new file mode 100644 index 0000000..849b560 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/Action.java @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.SharedPreferences; + +/** + * Various actions that can be passed to {@link PlaybackService#performAction(Action, PlaybackActivity)}. + */ +enum Action { + /** + * Dummy action: do nothing. + */ + Nothing, + /** + * Open the library activity. + */ + Library, + /** + * If playing music, pause. Otherwise, start playing. + */ + PlayPause, + /** + * Skip to the next song. + */ + NextSong, + /** + * Go back to the previous song. + */ + PreviousSong, + /** + * Skip to the first song from the next album. + */ + NextAlbum, + /** + * Skip to the last song from the previous album. + */ + PreviousAlbum, + /** + * Cycle the repeat mode. + */ + Repeat, + /** + * Cycle the shuffle mode. + */ + Shuffle, + /** + * Enqueue the rest of the current album. + */ + EnqueueAlbum, + /** + * Enqueue the rest of the songs by the current artist. + */ + EnqueueArtist, + /** + * Enqueue the rest of the songs in the current genre. + */ + EnqueueGenre, + /** + * Clear the queue of all remaining songs. + */ + ClearQueue, + /** + * Displays the queue + */ + ShowQueue, + /** + * Toggle the controls in the playback activity. + */ + ToggleControls, + /** + * Seek 10 seconds forward + */ + SeekForward, + /** + * Seek 10 seconds back + */ + SeekBackward; + + /** + * Retrieve an action from the given SharedPreferences. + * + * @param prefs The SharedPreferences instance to load from. + * @param key The preference key to load. + * @param def The value to return if the key is not found or cannot be loaded. + * @return The loaded action or def if no action could be loaded. + */ + public static Action getAction(SharedPreferences prefs, String key, Action def) + { + try { + String pref = prefs.getString(key, null); + if (pref == null) + return def; + return Enum.valueOf(Action.class, pref); + } catch (Exception e) { + return def; + } + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/AudioPickerActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/AudioPickerActivity.java new file mode 100644 index 0000000..540f886 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/AudioPickerActivity.java @@ -0,0 +1,297 @@ +/* + * Copyright (C) 2014-2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Activity; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.AsyncTask; +import android.os.Bundle; +import android.provider.MediaStore; +import android.view.View; +import android.view.Window; +import android.widget.TextView; +import android.widget.Button; +import android.widget.ProgressBar; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class AudioPickerActivity extends PlaybackActivity { + /** + * The cancel button + */ + private Button mCancelButton; + /** + * The enqueue button + */ + private Button mEnqueueButton; + /** + * The play button + */ + private Button mPlayButton; + /** + * The general purpose text view + */ + private TextView mTextView; + /** + * Our endless progress bar + */ + private ProgressBar mProgressBar; + /** + * Song we found, or failed to find + */ + private Song mSong; + /** + * Our async worker task to search for mSong + */ + private AudioPickerWorker mWorker; + + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + + Intent intent = getIntent(); + if (intent == null) { + finish(); + return; + } + + if (PermissionRequestActivity.requestPermissions(this, intent)) { + finish(); + return; + } + + Uri uri = intent.getData(); + if (uri == null) { + finish(); + return; + } + + // Basic sanity test done: Create worker + // and setup window. + mWorker = new AudioPickerWorker(); + + // Basic sanity test done: Setup window + requestWindowFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.audiopicker); + + // ...and resolve + bind all elements + mCancelButton = (Button)findViewById(R.id.cancel); + mCancelButton.setEnabled(true); + mCancelButton.setOnClickListener(this); + + mEnqueueButton = (Button)findViewById(R.id.enqueue); + mEnqueueButton.setOnClickListener(this); + + mPlayButton = (Button)findViewById(R.id.play); + mPlayButton.setOnClickListener(this); + + mTextView = (TextView)findViewById(R.id.filepath); + mProgressBar = (ProgressBar)findViewById(R.id.progress); + + // UI is ready, we can now execute the actual task. + mWorker.execute(uri); + } + + @Override + public void onClick(View view) + { + int mode; + QueryTask query; + + switch(view.getId()) { + case R.id.play: + mode = SongTimeline.MODE_PLAY; + break; + case R.id.enqueue: + mode = SongTimeline.MODE_ENQUEUE; + break; + default: + mWorker.cancel(false); + finish(); + return; + } + + // This code is not reached unless mSong is filled and non-empty + if (mSong.id < 0) { + query = MediaUtils.buildFileQuery(mSong.path, Song.FILLED_PROJECTION, false /* recursive */); + } else { + query = MediaUtils.buildQuery(MediaUtils.TYPE_SONG, mSong.id, Song.FILLED_PROJECTION, null); + } + + query.mode = mode; + + PlaybackService service = PlaybackService.get(this); + service.addSongs(query); + finish(); + } + + /** + * Called after AudioPickerWorker finished. + * This inspects the result and sets up the view + * if we got a song, cancels the activity otherwise. + * + * @param song the song we found, may be null + */ + private void onSongResolved(Song song) { + mSong = song; + + if (song == null) { + finish(); + return; + } + + // Enable enqueue button if playback service is already + // active (= we are most likely playing a song) + if (PlaybackService.hasInstance()) + mEnqueueButton.setEnabled(true); + + mPlayButton.setEnabled(true); + + // Set the title to display, we use the filename as a fallback + // if the title is empty for whatever reason. + String displayName = song.title; + if ("".equals(song.title)) + displayName = new File(song.path).getName(); + + mTextView.setText(song.title); + mTextView.setVisibility(View.VISIBLE); + mProgressBar.setVisibility(View.GONE); + } + + /** + * Background worker to resolve a song from an Uri. + * Will call onSongResolved(Song) on completion. + */ + private class AudioPickerWorker extends AsyncTask<Uri, Void, Song> { + @Override + protected Song doInBackground(Uri... uri) { + return getSongForUri(uri[0]); + } + @Override + protected void onPostExecute(Song song) { + onSongResolved(song); + } + + /** + * Attempts to resolve given uri to a song object + * + * @param uri The uri to resolve + * @return A song object, null on failure + */ + private Song getSongForUri(Uri uri) { + Song song = new Song(-1); + Cursor cursor = null; + + if (uri.getScheme().equals("content")) { + if (uri.getHost().equals("media")) { + cursor = getCursorForMediaContent(uri); + } else { + cursor = getCursorForAnyContent(uri); + } + } + + if (uri.getScheme().equals("file")) { + cursor = MediaUtils.getCursorForFileQuery(uri.getPath()); + } + + if (cursor != null) { + if (cursor.moveToNext()) { + song.populate(cursor); + } + cursor.close(); + } + return song.isFilled() ? song : null; + } + + /** + * Returns the cursor for a file stored in androids media library. + * + * @param uri the uri to query - expected to be content://media/... + * @return cursor the cursor, may be null. + */ + private Cursor getCursorForMediaContent(Uri uri) { + Cursor cursor = null; + Cursor pathCursor = getContentResolver().query(uri, new String[]{ MediaStore.Audio.Media.DATA }, null, null, null); + if (pathCursor != null) { + if (pathCursor.moveToNext()) { + String mediaPath = pathCursor.getString(0); + if (mediaPath != null) { // this happens on android 4.x sometimes?! + QueryTask query = MediaUtils.buildFileQuery(mediaPath, Song.FILLED_PROJECTION, false /* recursive */); + cursor = query.runQuery(getApplicationContext()); + } + } + pathCursor.close(); + } + return cursor; + } + + /** + * Returns the cursor for any content:// uri. The contents will be stored + * in our application cache. + * + * @param uri the uri to query + * @return cursor the cursor, may be null. + */ + private Cursor getCursorForAnyContent(Uri uri) { + Cursor cursor = null; + File outFile = null; + InputStream ins = null; + OutputStream ous = null; + + // Cache a local copy, this should really run in a background thread, but we + // are usually reading local files, which is fast enough. + try { + byte[] buffer = new byte[8192]; + ins = getContentResolver().openInputStream(uri); + outFile = File.createTempFile("cached-download-", ".bin", getCacheDir()); + ous = new FileOutputStream(outFile); + + int len = 0; + while ((len = ins.read(buffer)) != -1) { + ous.write(buffer, 0, len); + if (isCancelled()) { + throw new IOException("Canceled"); + } + } + outFile.deleteOnExit(); + } catch (IOException e) { + if (outFile != null) { + outFile.delete(); + } + outFile = null; // signals failure. + } finally { + try { if (ins != null) ins.close(); } catch(IOException e) {} + try { if (ous != null) ous.close(); } catch(IOException e) {} + } + + if (outFile != null) { + cursor = MediaUtils.getCursorForFileQuery(outFile.getPath()); + } + return cursor; + } + } + + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/AudioSearchActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/AudioSearchActivity.java new file mode 100644 index 0000000..d51534e --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/AudioSearchActivity.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Activity; +import android.app.SearchManager; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.provider.MediaStore; +import android.view.Window; + +public class AudioSearchActivity extends PlaybackActivity { + /** + * The AsyncTask used to perform the query. + */ + private AudioSearchWorker mWorker; + + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + + Intent intent = getIntent(); + String action = (intent == null ? null : intent.getAction()); + if (action == null || !action.equals(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH)) { + finish(); + return; + } + + if (PermissionRequestActivity.requestPermissions(this, intent)) { + finish(); + return; + } + + requestWindowFeature(Window.FEATURE_NO_TITLE); + // Fixme: add a progress dialog. + + String query = intent.getExtras().getString(SearchManager.QUERY); + mWorker = new AudioSearchWorker(); + mWorker.execute(query); + } + + /** + * Called by AudioSearchWorker after the search completed. + */ + private void onSearchCompleted() { + finish(); + } + + /** + * Async worker class used to perform the search + */ + private class AudioSearchWorker extends AsyncTask<String, Void, Void> { + @Override + protected Void doInBackground(String... search) { + Context ctx = getApplicationContext(); + MediaAdapter adapter = new MediaAdapter(ctx, MediaUtils.TYPE_SONG, null, null); + adapter.setFilter(search[0]); + + QueryTask query = adapter.buildSongQuery(Song.FILLED_PROJECTION); + query.mode = SongTimeline.MODE_PLAY; + + PlaybackService service = PlaybackService.get(ctx); + service.pause(); + service.setShuffleMode(SongTimeline.SHUFFLE_ALBUMS); + service.emptyQueue(); + service.addSongs(query); + if (service.getTimelineLength() > 0) { + service.play(); + } + return null; + } + @Override + protected void onPostExecute(Void nil) { + onSearchCompleted(); + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/BastpUtil.java b/app/src/main/java/ch/blinkenlights/android/vanilla/BastpUtil.java new file mode 100644 index 0000000..4f652e7 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/BastpUtil.java @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2013-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.util.LruCache; +import ch.blinkenlights.bastp.Bastp; +import java.util.ArrayList; +import java.util.HashMap; + +public class BastpUtil { + /** + * Our global instance cache + */ + private RGLruCache rgCache; + /** + * What we return & cache + */ + public class GainValues { + public float album; + public float track; + public boolean found; + } + /** + * LRU cache for ReplayGain values + */ + private class RGLruCache extends LruCache<String, GainValues> { + public RGLruCache(int size) { + super(size); + } + } + + + public BastpUtil() { + rgCache = new RGLruCache(64); + } + + /** + * Returns a GainValues object for `path' + */ + public GainValues getReplayGainValues(String path) { + if(path == null) { + // path must not be null + path = "//null\\"; + } + + GainValues cached = rgCache.get(path); + if(cached == null) { + cached = getReplayGainValuesFromFile(path); + rgCache.put(path, cached); + } + return cached; + } + + /** + * Parse given file and return track,album replay gain values + */ + private GainValues getReplayGainValuesFromFile(String path) { + HashMap tags = (new Bastp()).getTags(path); + GainValues gv = new GainValues(); + + // normal replay gain + if(tags.containsKey("REPLAYGAIN_TRACK_GAIN")) { + gv.track = getFloatFromString((String)((ArrayList)tags.get("REPLAYGAIN_TRACK_GAIN")).get(0)); + gv.found = true; + } + if(tags.containsKey("REPLAYGAIN_ALBUM_GAIN")) { + gv.album = getFloatFromString((String)((ArrayList)tags.get("REPLAYGAIN_ALBUM_GAIN")).get(0)); + gv.found = true; + } + + // R128 replay gain + boolean r128 = false; + if(tags.containsKey("R128_BASTP_BASE_GAIN")) { + // This is the gain found in the opus header which automatically gets applied by the media framework. + // We therefore do not need to include it in our calculation, but we set the 'found' bit and reset + // both album and track gain information as an opus file should only ever contain r128 gain infos. + float base = getFloatFromString((String)((ArrayList)tags.get("R128_BASTP_BASE_GAIN")).get(0)) / 256.0f; + if (base != 0.0f) { + gv.track = 0; + gv.album = 0; + gv.found = true; + } + } + if(tags.containsKey("R128_TRACK_GAIN")) { + gv.track += getFloatFromString((String)((ArrayList)tags.get("R128_TRACK_GAIN")).get(0)) / 256.0f; + gv.found = true; + r128 = true; + } + if(tags.containsKey("R128_ALBUM_GAIN")) { + gv.album += getFloatFromString((String)((ArrayList)tags.get("R128_ALBUM_GAIN")).get(0)) / 256.0f; + gv.found = true; + r128 = true; + } + + if (r128) { + gv.track += 5.0f; + gv.album += 5.0f; + } + return gv; + } + + /** + * Parses common replayGain string values + */ + private float getFloatFromString(String rg_raw) { + float rg_float = 0f; + try { + String nums = rg_raw.replaceAll("[^0-9.-]",""); + rg_float = Float.parseFloat(nums); + } catch(Exception e) {} + return rg_float; + } + +} + diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/BottomBarControls.java b/app/src/main/java/ch/blinkenlights/android/vanilla/BottomBarControls.java new file mode 100644 index 0000000..ecae037 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/BottomBarControls.java @@ -0,0 +1,310 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Context; +import android.content.res.Resources; +import android.graphics.drawable.Drawable; +import android.graphics.Bitmap; +import android.os.Parcelable; +import android.util.AttributeSet; +import android.view.Gravity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageButton; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.PopupMenu; +import android.widget.SearchView; +import android.widget.TextView; + + +public class BottomBarControls extends LinearLayout + implements View.OnClickListener + , PopupMenu.OnMenuItemClickListener + { + /** + * The application context + */ + private final Context mContext; + /** + * The title of the currently playing song + */ + private TextView mTitle; + /** + * The artist of the currently playing song + */ + private TextView mArtist; + /** + * Cover image + */ + private ImageView mCover; + /** + * A layout hosting the song information + */ + private LinearLayout mControlsContent; + /** + * Standard android search view + */ + private SearchView mSearchView; + /** + * The assembled PopupMenu + */ + private PopupMenu mPopupMenu; + /** + * ControlsContent click consumer, may be null + */ + private View.OnClickListener mParentClickConsumer; + /** + * Owner of our options menu and consumer of clicks + */ + private Activity mParentMenuConsumer; + + + public BottomBarControls(Context context, AttributeSet attrs) { + super(context, attrs); + mContext = context; + } + + @Override + public void onFinishInflate() { + mTitle = (TextView)findViewById(R.id.title); + mArtist = (TextView)findViewById(R.id.artist); + mCover = (ImageView)findViewById(R.id.cover); + mSearchView = (SearchView)findViewById(R.id.search_view); + mControlsContent = (LinearLayout)findViewById(R.id.content_controls); + + styleSearchView(mSearchView, mContext.getResources().getColor(android.R.color.background_light)); + + super.onFinishInflate(); + } + + @Override + public void onClick(View view) { + Object tag = view.getTag(); + if (tag instanceof PopupMenu) { + openMenu(); + } else if (tag instanceof MenuItem) { + mParentMenuConsumer.onOptionsItemSelected((MenuItem)tag); + } else if (view == mControlsContent && mParentClickConsumer != null) { + // dispatch this click to parent, claiming it came from + // the top view (= this) + mParentClickConsumer.onClick(this); + } + } + + @Override + public boolean onMenuItemClick(MenuItem item) { + return mParentMenuConsumer.onOptionsItemSelected(item); + } + + @Override + public Parcelable onSaveInstanceState() { + // Forcefully hide (and clear) search as we are not going to restore the state + showSearch(false); + return super.onSaveInstanceState(); + } + + /** + * Sets the ControlsContent to be clickable + */ + public void setOnClickListener(View.OnClickListener listener) { + mParentClickConsumer = listener; + mControlsContent.setOnClickListener(this); + } + + /** + * Configures a query text listener for the search view + */ + public void setOnQueryTextListener(SearchView.OnQueryTextListener owner) { + mSearchView.setOnQueryTextListener(owner); + } + + /** + * Boots the options menu + * + * @param owner the activity who will receive our callbacks + */ + @SuppressLint("NewApi") // PopupMenu with gravity is API19, checked by menuMargin() + public void enableOptionsMenu(Activity owner) { + mParentMenuConsumer = owner; + + ImageButton menuButton = getImageButton(getResources().getDrawable(R.drawable.ic_menu_moreoverflow)); + mPopupMenu = (menuMargin() ? new PopupMenu(mContext, menuButton, Gravity.RIGHT) : new PopupMenu(mContext, menuButton)); + mPopupMenu.setOnMenuItemClickListener(this); + + // Let parent populate the menu + mParentMenuConsumer.onCreateOptionsMenu(mPopupMenu.getMenu()); + + // The menu is now ready, we an now add all invisible + // items with an icon to the toolbar + Menu menu = mPopupMenu.getMenu(); + for (int i=0; i < menu.size(); i++) { + MenuItem menuItem = menu.getItem(i); + if (menuItem.isVisible() == false && menuItem.getIcon() != null) { + ImageButton button = getImageButton(menuItem.getIcon()); + button.setTag(menuItem); + button.setOnClickListener(this); + mControlsContent.addView(button, -1); + } + } + + // Add menu button as last item + menuButton.setTag(mPopupMenu); + menuButton.setOnClickListener(this); + int specialSnowflake = menuMargin() ? dpToPx(36) : LinearLayout.LayoutParams.WRAP_CONTENT; + menuButton.setLayoutParams(new LinearLayout.LayoutParams(specialSnowflake, LinearLayout.LayoutParams.WRAP_CONTENT)); + mControlsContent.addView(menuButton, -1); + + // Add a clickable and empty view + // We will use this to add a margin to the menu button if required + // Note that the view will ALWAYS be present, even if it is 0dp wide to keep + // the menu button at position -2 + View spacer = new View(mContext); + spacer.setOnClickListener(this); + spacer.setTag(mPopupMenu); + int spacerDp = menuMargin() ? dpToPx(4) : 0; + spacer.setLayoutParams(new LinearLayout.LayoutParams(spacerDp, LinearLayout.LayoutParams.MATCH_PARENT)); + mControlsContent.addView(spacer, -1); + } + + /** + * Opens the OptionsMenu of this view + */ + public void openMenu() { + if (mPopupMenu == null || mParentMenuConsumer == null) + return; + mParentMenuConsumer.onPrepareOptionsMenu(mPopupMenu.getMenu()); + mPopupMenu.show(); + } + + /** + * Sets the search view to given state + * + * @param visible enables or disables the search box visibility + * @return boolean old state + */ + public boolean showSearch(boolean visible) { + boolean wasVisible = mSearchView.getVisibility() == View.VISIBLE; + if (wasVisible != visible) { + mSearchView.setVisibility(visible ? View.VISIBLE : View.GONE); + mControlsContent.setVisibility(visible ? View.GONE : View.VISIBLE); + if (visible) + mSearchView.setIconified(false); // requests focus AND shows the soft keyboard even if the view already was expanded + else + mSearchView.setQuery("", false); + } + return wasVisible; + } + + /** + * Updates the cover image of this view + * + * @param cover the bitmap to display. Will use a placeholder image if cover is null + */ + public void setCover(Bitmap cover) { + if (cover == null) + mCover.setImageResource(R.drawable.fallback_cover); + else + mCover.setImageBitmap(cover); + } + + /** + * Updates the song metadata + * + * @param song the song info to display, may be null + */ + public void setSong(Song song) { + if (song == null) { + mTitle.setText(null); + mArtist.setText(null); + mCover.setImageBitmap(null); + } else { + Resources res = mContext.getResources(); + String title = song.title == null ? res.getString(R.string.unknown) : song.title; + String artist = song.artist == null ? res.getString(R.string.unknown) : song.artist; + mTitle.setText(title); + mArtist.setText(artist); + } + } + + /** + * Returns a new image button to be placed on the bar + * + * @param drawable The icon to use + */ + private ImageButton getImageButton(Drawable drawable) { + + ImageButton button = new ImageButton(mContext); + button.setImageDrawable(drawable); + button.setBackgroundResource(R.drawable.unbound_ripple_light); + return button; + } + + /** + * Changing the colors of a search view is a MAJOR pain using XML + * This cheap trick just loop trough the view and changes the + * color of all text- and image views to 'style' + * + * @param view the view to search + * @param color the color to apply + */ + private void styleSearchView(View view, int color) { + if (view != null) { + if (view instanceof TextView) { + ((TextView)view).setTextColor(color); + } else if (view instanceof ImageView) { + ((ImageView)view).setColorFilter(color); + } else if (view instanceof ViewGroup) { + ViewGroup group = (ViewGroup)view; + for (int i=0; i< group.getChildCount(); i++) { + styleSearchView(group.getChildAt(i), color); + } + } + } + } + + /** + * Returns true if we need to add a margin to the menu. + * Because ...reasons. + */ + private boolean menuMargin() { + // Was false for holo, maybe will be true again in the future? ;-) + return true; + } + + /** + * Convert dp into pixels + * + * @param dp input as dp + * @return output as px + */ + private int dpToPx(int dp) { + return (int)(getResources().getDisplayMetrics().density * dp); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/CoverBitmap.java b/app/src/main/java/ch/blinkenlights/android/vanilla/CoverBitmap.java new file mode 100644 index 0000000..cd289d9 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/CoverBitmap.java @@ -0,0 +1,447 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * Copyright 2017-2020 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.res.Resources; +import android.content.res.TypedArray; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.BitmapShader; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.PorterDuff; +import android.graphics.PorterDuffColorFilter; +import android.graphics.Rect; +import android.graphics.RectF; +import android.graphics.Shader; +import android.util.DisplayMetrics; +import android.util.TypedValue; + +/** + * Class containing utility functions to create Bitmaps display song info and + * album art. + */ +public final class CoverBitmap { + /** + * Draw cover in background and a box with song info on top. + */ + public static final int STYLE_OVERLAPPING_BOX = 0; + /** + * Draw cover on top or left with song info on bottom or right (depending + * on orientation). + */ + public static final int STYLE_INFO_BELOW = 1; + /** + * Draw no song info, only the cover. + */ + public static final int STYLE_NO_INFO = 2; + /** + * Whether or not to debug painting operations. + */ + private static final boolean DEBUG_PAINT = false; + /** + * Cover slack ratio + */ + private static final float SLACK_RATIO = 0.95f; + + private static int TEXT_SIZE = -1; + private static int TEXT_SIZE_BIG; + private static int PADDING; + private static int TOP_PADDING; + private static int BOTTOM_PADDING; + + /** + * Initialize the regular text size members. + * + * @param context A context to use. + */ + private static void loadTextSizes(Context context) + { + DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + TEXT_SIZE = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, metrics); + TEXT_SIZE_BIG = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, metrics); + PADDING = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, metrics); + // padding to take actionbar into account. + TOP_PADDING = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, metrics); + // space we keep from the view bottom. + BOTTOM_PADDING = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, metrics); + } + + /** + * Helper function to draw text within a set width + * + * @param canvas The canvas to draw to + * @param text The text to draw + * @param left The x coordinate of the left edge of the text + * @param top The y coordinate of the top edge of the text + * @param width The measured width of the text + * @param maxWidth The maximum width of the text. Text outside of this width + * will be truncated. + * @param paint The paint style to use + */ + private static void drawText(Canvas canvas, String text, int left, int top, int width, int maxWidth, Paint paint) + { + canvas.save(); + int offset = Math.max(0, maxWidth - width) / 2; + canvas.clipRect(left, top, left + maxWidth, top + paint.getTextSize() * 2); + canvas.drawText(text, left + offset, top - paint.ascent(), paint); + canvas.restore(); + } + + /** + * Create an image representing the given song. Includes cover art and + * possibly song title/artist/ablum, depending on the given style. + * + * @param context A context to use. + * @param style One of CoverBitmap.STYLE_* + * @param coverArt The cover art for the song. + * @param song Title and other data are taken from here for info modes. + * @param width Maximum width of image + * @param height Maximum height of image + * @return The image, or null if the song was null, or width or height + * were less than 1 + */ + public static Bitmap createBitmap(Context context, int style, Bitmap coverArt, Song song, int width, int height) + { + switch (style) { + case STYLE_OVERLAPPING_BOX: + return createOverlappingBitmap(context, coverArt, song, width, height); + case STYLE_INFO_BELOW: + return createSeparatedBitmap(context, coverArt, song, width, height); + case STYLE_NO_INFO: + return createScaledBitmap(coverArt, width, height); + default: + throw new IllegalArgumentException("Invalid bitmap type given: " + style); + } + } + + private static Bitmap createOverlappingBitmap(Context context, Bitmap cover, Song song, int width, int height) + { + if (TEXT_SIZE == -1) + loadTextSizes(context); + + Paint paint = new Paint(); + paint.setAntiAlias(true); + + String title = song.title == null ? "" : song.title; + String album = song.album == null ? "" : song.album; + String artist = song.artist == null ? "" : song.artist; + + int titleSize = TEXT_SIZE_BIG; + int subSize = TEXT_SIZE; + int padding = PADDING; + + paint.setTextSize(titleSize); + int titleWidth = (int)paint.measureText(title); + paint.setTextSize(subSize); + int albumWidth = (int)paint.measureText(album); + int artistWidth = (int)paint.measureText(artist); + + int boxWidth = Math.min(width, Math.max(titleWidth, Math.max(artistWidth, albumWidth)) + padding * 2); + int boxHeight = Math.min(height, titleSize + subSize * 2 + padding * 4); + + int coverWidth = 0; + int coverHeight = 0; + if (cover != null) { + cover = createScaledBitmap(cover, width, height); + coverWidth = cover.getWidth(); + coverHeight = cover.getHeight(); + } + + Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + + if (DEBUG_PAINT) { + Paint dpaint = new Paint(); + dpaint.setColor(0xffff0000); + dpaint.setStyle(Paint.Style.FILL); + canvas.drawPaint(dpaint); + } + + if (coverWidth != 0) { + canvas.drawBitmap(cover, (width-coverWidth)/2, (height-coverHeight)/2, new Paint()); + } + + int left = (width - boxWidth) / 2; + int top = (height - boxHeight) / 2; + int right = (width + boxWidth) / 2; + int bottom = (height + boxHeight) / 2; + + paint.setARGB(150, 0, 0, 0); + canvas.drawRect(left, top, right, bottom, paint); + + int maxWidth = boxWidth - padding * 2; + paint.setARGB(255, 255, 255, 255); + top += padding; + left += padding; + + paint.setTextSize(titleSize); + drawText(canvas, title, left, top, titleWidth, maxWidth, paint); + top += titleSize + padding; + + paint.setTextSize(subSize); + drawText(canvas, album, left, top, albumWidth, maxWidth, paint); + top += subSize + padding; + + drawText(canvas, artist, left, top, artistWidth, maxWidth, paint); + + return bitmap; + } + + private static Bitmap createSeparatedBitmap(Context context, Bitmap cover, Song song, int width, int height) + { + if (TEXT_SIZE == -1) + loadTextSizes(context); + + int textSize = TEXT_SIZE; + int textSizeBig = TEXT_SIZE_BIG; + int padding = PADDING; + int topPadding = TOP_PADDING; + int bottomPadding = BOTTOM_PADDING; + + // Get desired text color from theme and draw textual information + int colors[] = ThemeHelper.getDefaultCoverColors(context); + // inverted cover background color. + int textColor = 0xFF000000 + (0xFFFFFF - (colors[0] & 0xFFFFFF)); + // Whether or not the image is rendered in vertical mode. + boolean verticalMode = width > height; + + // Prepare text and calculate minimum height, so we can ensure + // that the cover doesn't 'eat' into it. + String title = song.title == null ? "" : song.title; + String album = song.album == null ? "" : song.album; + String artist = song.artist == null ? "" : song.artist; + // Space required to draw the bottom text. + int textTotalHeight = padding + textSizeBig + (padding+textSize) * 2 + padding; + // Y coord where text shall be placed. + int textStart = (verticalMode ? (height-textTotalHeight)/2 : height - bottomPadding - textTotalHeight); + + Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(bitmap); + + if (DEBUG_PAINT) { + Paint dpaint = new Paint(); + dpaint.setColor(0xffff0033); + dpaint.setStyle(Paint.Style.FILL); + canvas.drawPaint(dpaint); + } + + if (cover != null) { + Bitmap scaled; + if (verticalMode) { + int hh = height/2; + int hw = width/2; + scaled = createScaledBitmap(cover, Math.min(hw, height), Math.min(hw, height)); + canvas.drawBitmap(scaled, (hw-scaled.getWidth())/2, (height-scaled.getHeight())/2, null); + } else { + scaled = createScaledBitmap(cover, width, textStart); + canvas.drawBitmap(scaled, (width-scaled.getWidth())/2, 0, null); + } + } + + // Where to start drawing the text. + int top = textStart; + + // Now draw the text: + PorterDuffColorFilter filter = new PorterDuffColorFilter(textColor, PorterDuff.Mode.SRC_ATOP); + Paint paint = new Paint(); + paint.setAntiAlias(true); + + // how much to shift text to the right forcefully. + int tshift = (verticalMode ? width/2 : 0); + // Title + paint.setColorFilter(filter); + paint.setTextSize(textSizeBig); + int twidth = (int)paint.measureText(title); + int tstart = tshift+(width - tshift - twidth)/2; + drawText(canvas, title, tstart, top, width, twidth, paint); + + // Bottom text + paint.setAlpha(0xAA); + paint.setTextSize(textSize); + + // Album + top += textSizeBig + padding; + twidth = (int)paint.measureText(album); + tstart = tshift+(width - tshift - twidth)/2; + drawText(canvas, album, tstart, top, width, twidth, paint); + + // Artist + top += textSize + padding; + twidth = (int)paint.measureText(artist); + tstart = tshift+(width - tshift - twidth)/2; + drawText(canvas, artist, tstart, top, width, twidth, paint); + + return bitmap; + } + + /** + * Scales a bitmap to fit in a rectangle of the given size. Aspect ratio is + * preserved. At least one dimension of the result will match the provided + * dimension exactly. + * + * @param source The bitmap to be scaled + * @param width Maximum width of image + * @param height Maximum height of image + * @return The scaled bitmap. + */ + private static Bitmap createScaledBitmap(Bitmap source, int width, int height) + { + int sourceWidth = source.getWidth(); + int sourceHeight = source.getHeight(); + float scale = Math.min((float)width / sourceWidth, (float)height / sourceHeight); + sourceWidth *= scale; + sourceHeight *= scale; + Bitmap scaled = Bitmap.createScaledBitmap(source, (int)(SLACK_RATIO*sourceWidth), (int)(SLACK_RATIO*sourceHeight), true); + return createBorderedBitmap(scaled, sourceWidth, sourceHeight); + } + + /** + * Creates a bitmap with a round border. The returned bitmap will fit exactly + * into the passed in dimensions and the source image is not scaled. + * + * @param source the source bitmap to use + * @param width the with of the returned bitmap + * @param height the height of the returned bitmap + * @return the painted bitmap + */ + private static Bitmap createBorderedBitmap(Bitmap source, int width, int height) { + Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(dst); + + if (DEBUG_PAINT) { + Paint dpaint = new Paint(); + dpaint.setColor(0xff0000ff); + dpaint.setStyle(Paint.Style.FILL); + canvas.drawPaint(dpaint); + } + + BitmapShader shader = new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); + Paint paint = new Paint(); + paint.setAntiAlias(true); + paint.setShader(shader); + + RectF rect = new RectF(0.0f, 0.0f, source.getWidth(), source.getHeight()); + float radius = 12; + canvas.translate((height-source.getHeight())/2, (width-source.getWidth())/2); + canvas.drawRoundRect(rect, radius, radius, paint); + return dst; + } + + /** + * Generate the default cover (a rendition of a music note). Returns a square iamge. + * Both dimensions are the lesser of width and height. + * + * @param width The max width + * @param height The max height + * @return The default cover. + */ + public static Bitmap generateDefaultCover(Context context, int width, int height) + { + int size = Math.min(width, height); + + int[] colors = ThemeHelper.getDefaultCoverColors(context); + int rgb_background = colors[0]; + int rgb_note_inner = colors[1]; + + final int line_thickness = size / 10; + final int line_vertical = line_thickness*5; + final int line_horizontal = line_thickness*3; + final int circle_radius = line_thickness*2; + + final int total_len_x = circle_radius*2 + line_horizontal - line_thickness; // total length of x axis + final int total_len_y = circle_radius + line_vertical + (line_thickness/2); // total length of y axis + final int xoff = circle_radius + (size - total_len_x)/2; // 'center offset' of x + final int yoff = size - circle_radius - (size - total_len_y)/2; // 'center offset' of y + + Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); + bitmap.eraseColor(rgb_background); + + Paint paint = new Paint(); + paint.setAntiAlias(true); + paint.setColor(rgb_note_inner); + + Canvas canvas = new Canvas(bitmap); + // main circle + canvas.drawCircle(xoff, yoff, circle_radius, paint); + // vertical line + int lpos = xoff + circle_radius - line_thickness; // lpos + thickness will touch the outer right edge of the circle + int tpos = yoff - line_vertical; // tpos + vertical will be the center of the circle + canvas.drawRoundRect(new RectF(lpos, tpos, lpos+line_thickness, yoff), 0, 0, paint); + // horizontal line + int hdiff = tpos - (line_thickness/2); // shift this up by half of the thickness to have the circle radius touch the top of the vertical line + canvas.drawRoundRect(new RectF(lpos, hdiff, lpos+line_horizontal, hdiff+line_thickness), line_thickness, line_thickness, paint); + + return bitmap; + } + + /** + * Draws a placeholder cover from given title string + * + * @param title A text string to use in the cover + * @return bitmap The drawn bitmap + */ + public static Bitmap generatePlaceholderCover(Context context, int width, int height, String title) + { + if (title == null || width < 1 || height < 1) + return null; + + final float textSize = width * 0.4f; + + title = title.replaceFirst("(?i)^The ", ""); // 'The\s' shall not be a part of the string we are drawing. + title = title.replaceAll("[ <>_-]", ""); // Remove clutter, so eg. J-Rock becomes JR + String subText = (title+" ").substring(0,2); + + // Use only the first char if it is 'wide' + if(Character.UnicodeBlock.of(subText.charAt(0)) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) { + subText = subText.substring(0,1); + } + + Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); + Canvas canvas = new Canvas(bitmap); + Paint paint = new Paint(); + + // Picks a semi-random color from tiles_colors.xml + TypedValue tv = new TypedValue(); + context.getTheme().resolveAttribute(R.attr.themed_letter_tile_colors, tv, false); + TypedArray colors = context.getResources().obtainTypedArray(tv.data); + int color = colors.getColor(Math.abs(title.hashCode()) % colors.length(), 0); + colors.recycle(); + paint.setColor(color); + + paint.setStyle(Paint.Style.FILL); + canvas.drawPaint(paint); + + paint.setARGB(255, 255, 255, 255); + paint.setAntiAlias(true); + paint.setTextSize(textSize); + + Rect bounds = new Rect(); + paint.getTextBounds(subText, 0, subText.length(), bounds); + + canvas.drawText(subText, (width/2f)-bounds.exactCenterX(), (height/2f)-bounds.exactCenterY(), paint); + return bitmap; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/CoverCache.java b/app/src/main/java/ch/blinkenlights/android/vanilla/CoverCache.java new file mode 100644 index 0000000..ca218e1 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/CoverCache.java @@ -0,0 +1,527 @@ +/* + * Copyright (C) 2015-2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.ContentResolver; +import android.content.ContentValues; +import android.content.Context; +import android.content.res.Resources; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.graphics.Bitmap; +import android.graphics.Bitmap.CompressFormat; +import android.graphics.BitmapFactory; +import android.media.MediaMetadataRetriever; +import android.net.Uri; +import android.os.Environment; +import android.util.DisplayMetrics; +import android.util.Log; + +import java.io.ByteArrayOutputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Random; +import java.util.regex.Pattern; + + +public class CoverCache { + /** + * Display metrics as reported by the system during class creation. + */ + private final static DisplayMetrics METRICS = Resources.getSystem().getDisplayMetrics(); + /** + * Returned size of small album covers + * 44sp is the width & height of a library row + */ + public final static int SIZE_SMALL = (int)(44 * METRICS.density); + /** + * Cover to use in remote views with a medium size. + */ + public final static int SIZE_MEDIUM = (int)(240 * METRICS.density); + /** + * Cover to use in the highest quality possible (full cover view). + */ + public final static int SIZE_LARGE = (METRICS.heightPixels > METRICS.widthPixels ? METRICS.widthPixels : METRICS.heightPixels); + /** + * Use all cover providers to load cover art + */ + public static final int COVER_MODE_ALL = 0xF; + /** + * Use androids builtin cover mechanism to load covers + */ + public static final int COVER_MODE_ANDROID = 0x1; + /** + * Use vanilla musics cover load mechanism + */ + public static final int COVER_MODE_VANILLA = 0x2; + /** + * Use vanilla musics SHADOW cover load mechanism + */ + public static final int COVER_MODE_SHADOW = 0x4; + /** + * Use vanilla musics INLINE cover load mechanism + */ + public static final int COVER_MODE_INLINE = 0x8; + /** + * Shared on-disk cache class + */ + private static BitmapDiskCache sBitmapDiskCache; + /** + * Bitmask on how we are going to load coverart + */ + public static int mCoverLoadMode = 0; + /** + * The public downloads directory of this device + */ + private static final File sDownloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); + + + /** + * Constructs a new BitmapCache object + * Will initialize the internal LRU cache on first call + * + * @param context A context to use + */ + public CoverCache(Context context) { + if (sBitmapDiskCache == null) { + sBitmapDiskCache = new BitmapDiskCache(context.getApplicationContext(), 25*1024*1024); + } + } + + /** + * Returns a (possibly uncached) cover for the song - will return null if the song has no cover + * + * @param ctx The context to retrieve the bitmap from cache via external content uri + * @param song The song used to identify the artwork to load + * @return a bitmap or null if no artwork was found + */ + public Bitmap getCoverFromSong(Context ctx, Song song, int size) { + CoverKey key = new CoverCache.CoverKey(MediaUtils.TYPE_ALBUM, song.albumId, size); + Bitmap cover = getStoredCover(key); + if (cover == null) { + cover = sBitmapDiskCache.createBitmap(ctx, song, size*size); + if (cover != null) { + storeCover(key, cover); + cover = getStoredCover(key); // return lossy version to avoid random quality changes + } + } + return cover; + } + + /** + * Returns the on-disk cached version of the cover. + * Should only be used on a background thread + * + * @param key The cache key to use + * @return bitmap or null on cache miss + */ + private Bitmap getStoredCover(CoverKey key) { + return sBitmapDiskCache.get(key); + } + + /** + * Stores a new entry in the on-disk cache + * Use getStoredCover to read the cached contents back + * + * @param key The cache key to use + * @param cover The bitmap to store + */ + private void storeCover(CoverKey key, Bitmap cover) { + sBitmapDiskCache.put(key, cover); + } + + /** + * Deletes all items hold in the cover caches + */ + public static void evictAll() { + if (sBitmapDiskCache != null) { + sBitmapDiskCache.evictAll(); + } + } + + + /** + * Object used as cache key. Objects with the same + * media type, id and size are considered to be equal + */ + public static class CoverKey { + public final int coverSize; + public final int mediaType; + public final long mediaId; + + CoverKey(int mediaType, long mediaId, int coverSize) { + this.mediaType = mediaType; + this.mediaId = mediaId; + this.coverSize = coverSize; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof CoverKey + && this.mediaId == ((CoverKey)obj).mediaId + && this.mediaType == ((CoverKey)obj).mediaType + && this.coverSize == ((CoverKey)obj).coverSize) { + return true; + } + return false; + } + + @Override + public int hashCode() { + return (int)this.mediaId + this.mediaType*(int)1e4 + this.coverSize * (int)1e5; + } + + @Override + public String toString() { + return "CoverKey_i"+this.mediaId+"_t"+this.mediaType+"_s"+this.coverSize; + } + + } + + + private static class BitmapDiskCache extends SQLiteOpenHelper { + /** + * Maximal cache size to use in bytes + */ + private final long mCacheSize; + /** + * SQLite table to use + */ + private final static String TABLE_NAME = "covercache"; + /** + * Priority-ordered list of possible cover names + */ + private final static Pattern[] COVER_MATCHES = { + Pattern.compile("(?i).+/(COVER|ALBUM)\\.(JPE?G|PNG|WEBP)$"), + Pattern.compile("(?i).+/ALBUMART(_\\{[-0-9A-F]+\\}_LARGE)?\\.(JPE?G|PNG|WEBP)$"), + Pattern.compile("(?i).+/(CD|FRONT|ARTWORK|FOLDER)\\.(JPE?G|PNG|WEBP)$"), + Pattern.compile("(?i).+\\.(JPE?G|PNG|WEBP)$") }; + /** + * Projection of all columns in the database + */ + private final static String[] FULL_PROJECTION = {"id", "size", "expires", "blob"}; + /** + * Projection of metadata-only columns + */ + private final static String[] META_PROJECTION = {"id", "size", "expires"}; + /** + * Restrict lifetime of cached objects to, at most, OBJECT_TTL + */ + private final static int OBJECT_TTL = 86400*8; + + /** + * Creates a new BitmapDiskCache instance + * + * @param context The context to use + * @param cacheSize The maximal amount of disk space to use in bytes + */ + public BitmapDiskCache(Context context, long cacheSize) { + super(context, "covercache.db", null, 1 /* version */); + mCacheSize = cacheSize; + } + + /** + * Called by SQLiteOpenHelper to create the database schema + */ + @Override + public void onCreate(SQLiteDatabase dbh) { + dbh.execSQL("CREATE TABLE "+TABLE_NAME+" (id INTEGER, expires INTEGER, size INTEGER, blob BLOB);"); + dbh.execSQL("CREATE UNIQUE INDEX idx ON "+TABLE_NAME+" (id);"); + } + + /** + * Called by SqLiteOpenHelper if the database needs an upgrade + */ + @Override + public void onUpgrade(SQLiteDatabase dbh, int oldVersion, int newVersion) { + // first db -> nothing to upgrade + } + + /** + * Trims the on disk cache to given size + * + * @param maxCacheSize Trim cache to this many bytes + */ + private void trim(long maxCacheSize) { + SQLiteDatabase dbh = getWritableDatabase(); + long availableSpace = maxCacheSize - getUsedSpace(); + + if (maxCacheSize == 0) { + // Just drop the whole database (probably a call from evictAll) + dbh.delete(TABLE_NAME, "1", null); + } else if (availableSpace < 0) { + // Try to evict all expired entries first + int affected = dbh.delete(TABLE_NAME, "expires < ?", new String[] { Long.toString(getUnixTime())}); + if (affected > 0) + availableSpace = maxCacheSize - getUsedSpace(); + + if (availableSpace < 0) { + // still not enough space: purge by expire date (this kills random rows as expire times are random) + Cursor cursor = dbh.query(TABLE_NAME, META_PROJECTION, null, null, null, null, "expires ASC"); + if (cursor != null) { + while (cursor.moveToNext() && availableSpace < 0) { + int id = cursor.getInt(0); + int size = cursor.getInt(1); + dbh.delete(TABLE_NAME, "id=?", new String[] { Long.toString(id) }); + availableSpace += size; + } + cursor.close(); + } + } + } + } + + /** + * Deletes all cached elements from the on-disk cache + */ + public void evictAll() { + // purge all cached entries + trim(0); + // and release the dbh + getWritableDatabase().close(); + } + + /** + * Checks if given stamp is considered to be expired + * + * @param stamp The timestamp to check + * @return boolean true if stamp is expired + */ + private boolean isExpired(long stamp) { + return (getUnixTime() > stamp); + } + + /** + * Returns the current unix timestamp + * + * @return long unix seconds since epoc + */ + private long getUnixTime() { + return System.currentTimeMillis() / 1000L; + } + + /** + * Calculates the space used by the sqlite database + * + * @return long the space used in bytes + */ + private long getUsedSpace() { + long usedSpace = -1; + SQLiteDatabase dbh = getWritableDatabase(); + Cursor cursor = dbh.query(TABLE_NAME, new String[]{"SUM(size)"}, null, null, null, null, null); + if (cursor != null) { + if (cursor.moveToNext()) + usedSpace = cursor.getLong(0); + cursor.close(); + } + return usedSpace; + } + + /** + * Stores a bitmap in the disk cache, does not update existing objects + * + * @param key The cover key to use + * @param cover The cover to store as bitmap + */ + public void put(CoverKey key, Bitmap cover) { + SQLiteDatabase dbh = getWritableDatabase(); + + // Ensure that there is some space left + trim(mCacheSize); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + // We store a lossy version as this image was + // created from the original source (and will not be re-compressed) + cover.compress(Bitmap.CompressFormat.JPEG, 85, out); + + Random rnd = new Random(); + long ttl = getUnixTime() + rnd.nextInt(OBJECT_TTL); + + ContentValues values = new ContentValues(); + values.put("id" , key.hashCode()); + values.put("expires", ttl); + values.put("size" , out.size()); + values.put("blob" , out.toByteArray()); + + dbh.insert(TABLE_NAME, null, values); + } + + /** + * Returns a cached bitmap + * + * @param key The key to lookup + * @return a cached bitmap, null on cache miss + */ + public Bitmap get(CoverKey key) { + Bitmap cover = null; + + SQLiteDatabase dbh = getWritableDatabase(); // may also delete + String selection = "id=?"; + String[] selectionArgs = { Long.toString(key.hashCode()) }; + Cursor cursor = dbh.query(TABLE_NAME, FULL_PROJECTION, selection, selectionArgs, null, null, null); + if (cursor != null) { + if (cursor.moveToFirst()) { + long expires = cursor.getLong(2); + byte[] blob = cursor.getBlob(3); + + if (isExpired(expires)) { + dbh.delete(TABLE_NAME, selection, selectionArgs); + } else { + ByteArrayInputStream stream = new ByteArrayInputStream(blob); + cover = BitmapFactory.decodeStream(stream); + } + } + cursor.close(); + } + + return cover; + } + + /** + * Attempts to create a new bitmap object for given song. + * Returns null if no cover art was found + * + * @param ctx The context to read the external content uri of the given song + * @param song the function will search for artwork of this object + * @param maxPxCount the maximum amount of pixels to return (30*30 = 900) + */ + public Bitmap createBitmap(Context ctx, Song song, long maxPxCount) { + if (song.id < 0) + throw new IllegalArgumentException("song id is < 0: " + song.id); + + try { + InputStream inputStream = null; + InputStream sampleInputStream = null; // same as inputStream but used for getSampleSize + + if ((CoverCache.mCoverLoadMode & CoverCache.COVER_MODE_VANILLA) != 0) { + final File baseFile = new File(song.path); // File object of queried song + String bestMatchPath = null; // The best cover-path we found + int bestMatchIndex = COVER_MATCHES.length; // The best cover-index/priority found + int loopCount = 0; // Directory items loop counter + + // Only start search if the base directory of this file is NOT the public + // downloads folder: Picking files from there would lead to a false positive + // in most cases + if (baseFile.getParentFile().equals(sDownloadsDir) == false) { + for (final File entry : baseFile.getParentFile().listFiles()) { + for (int i=0; i < bestMatchIndex ; i++) { + // We are checking each file entry to see if it matches a known + // cover pattern. We abort on first hit as the Pattern array is sorted from good->meh + if (COVER_MATCHES[i].matcher(entry.toString()).matches()) { + bestMatchIndex = i; + bestMatchPath = entry.toString(); + break; + } + } + // Stop loop if we found the best match or if we looped 150 times + if (loopCount++ > 150 || bestMatchIndex == 0) + break; + } + } + + if (bestMatchPath != null) { + final File guessedFile = new File(bestMatchPath); + if (guessedFile.exists() && !guessedFile.isDirectory()) { + inputStream = new FileInputStream(guessedFile); + sampleInputStream = new FileInputStream(guessedFile); + } + } + } + + if (inputStream == null && (CoverCache.mCoverLoadMode & CoverCache.COVER_MODE_SHADOW) != 0) { + final String shadowBase = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + "/.vanilla"; + final String shadowPath = shadowBase + "/" + (song.artist.replaceAll("/", "_"))+"/"+(song.album.replaceAll("/", "_"))+".jpg"; + + File guessedFile = new File(shadowPath); + if (guessedFile.exists() && !guessedFile.isDirectory()) { + inputStream = new FileInputStream(guessedFile); + sampleInputStream = new FileInputStream(guessedFile); + } + } + + if (inputStream == null && (CoverCache.mCoverLoadMode & CoverCache.COVER_MODE_ANDROID) != 0) { + ContentResolver res = ctx.getContentResolver(); + long[] androidIds = MediaUtils.getAndroidMediaIds(ctx, song); + long albumId = androidIds[1]; + + if (albumId != -1) { + // now we can query for the album art path if we found an album id + Uri uri = Uri.parse("content://media/external/audio/albumart/"+albumId); + sampleInputStream = res.openInputStream(uri); + if (sampleInputStream != null) // cache misses are VERY expensive here, so we check if the first open worked + inputStream = res.openInputStream(uri); + } + } + + if (inputStream == null && (CoverCache.mCoverLoadMode & CoverCache.COVER_MODE_INLINE) != 0) { + MediaMetadataRetriever mmr = new MediaMetadataRetriever(); + mmr.setDataSource(song.path); + + byte[] data = mmr.getEmbeddedPicture(); + if (data != null) { + sampleInputStream = new ByteArrayInputStream(data); + inputStream = new ByteArrayInputStream(data); + } + mmr.release(); + } + + if (inputStream != null) { + BitmapFactory.Options bopts = new BitmapFactory.Options(); + bopts.inPreferredConfig = Bitmap.Config.RGB_565; + bopts.inJustDecodeBounds = true; + + final int inSampleSize = getSampleSize(sampleInputStream, bopts, maxPxCount); + /* reuse bopts: we are now REALLY going to decode the image */ + bopts.inJustDecodeBounds = false; + bopts.inSampleSize = inSampleSize; + Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, bopts); + sampleInputStream.close(); + inputStream.close(); + return bitmap; + } + } catch (Exception e) { + // no cover art found + Log.v("VanillaMusic", "Loading coverart for "+song+" failed with exception "+e); + } + // failed! + return null; + } + + /** + * Guess a good sampleSize value for given inputStream + * + * @param inputStream the input stream to read from + * @param bopts the bitmap options to use + * @param maxPxCount how many pixels we are returning at most + */ + private static int getSampleSize(InputStream inputStream, BitmapFactory.Options bopts, long maxPxCount) { + int sampleSize = 1; /* default sample size */ + + BitmapFactory.decodeStream(inputStream, null, bopts); + long hasPixels = bopts.outHeight * bopts.outWidth; + if(hasPixels > maxPxCount) { + sampleSize = Math.round((int)Math.sqrt((float) hasPixels / (float) maxPxCount)); + } + return sampleSize; + } + + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/CoverView.java b/app/src/main/java/ch/blinkenlights/android/vanilla/CoverView.java new file mode 100644 index 0000000..ab9741f --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/CoverView.java @@ -0,0 +1,661 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.util.AttributeSet; +import android.view.View; +import android.view.MotionEvent; +import android.view.VelocityTracker; +import android.view.ViewConfiguration; +import android.view.animation.LinearInterpolator; +import android.widget.Scroller; + +import java.lang.IllegalStateException; +import java.lang.IllegalArgumentException; + +import android.util.Log; + + + +/** + * Displays a flingable/draggable View of cover art/song info images + * generated by CoverBitmap. + */ +public final class CoverView extends View implements Handler.Callback { + /** + * If >= 0, perform the switch after this delay + */ + private final static int ASYNC_SWITCH = -1; + /** + * Maximum amount of pixels we are allowed to scroll to consider + * touch events to be normal touches. + */ + private final static double TOUCH_MAX_SCROLL_PX = 10; + /** + * The system provided display density + */ + private static double sDensity = -1; + /** + * The minimum velocity to move to the next song + */ + private static double sSnapVelocity = -1; + /** + * Computes scroll velocity to detect flings. + */ + private VelocityTracker mVelocityTracker; + /** + * The context. + */ + private final Context mContext; + /** + * The scroller instance we are using. + */ + private final CoverScroller mScroller; + /** + * Our bitmap cache helper + */ + private BitmapBucket mBitmapBucket; + /** + * Our callback to dispatch song events. + */ + private CoverView.Callback mCallback; + /** + * Indicates that we attempted to query and update our songs but couldn't as the + * view was not yet ready. + */ + private boolean mPendingQuery; + /** + * The x coordinate of the initial touch event. + */ + private float mInitialMotionX; + /** + * The y coordinate of the initial touch event. + */ + private float mInitialMotionY; + /** + * The x coordinate of the last touch down or move event. + */ + private float mLastMotionX; + /** + * The y coordinate of the last touch down or move event. + */ + private float mLastMotionY; + /** + * The message handler used by this class. + */ + private Handler mHandler; + /** + * Handler thread only used for UI updates + */ + private Handler mUiHandler; + /** + * Our current scroll position. + * Setting this to '0' means that we will display bitmap[0]. + */ + private int mScrollX = -1; + /** + * The style to use for the cover. + */ + private int mCoverStyle = -1; + /** + * Our public callback interface + */ + public interface Callback { + void shiftCurrentSong(int delta); + void upSwipe(); + void downSwipe(); + } + + /** + * Constructs a new CoverView class, note that setup() must be called + * before the view becomes useable. + */ + public CoverView(Context context, AttributeSet attributes) { + super(context, attributes); + if (sDensity == -1) { + sDensity = context.getResources().getDisplayMetrics().density; + sSnapVelocity = ViewConfiguration.get(context).getScaledMinimumFlingVelocity() * 5; + } + mContext = context; + mBitmapBucket = new BitmapBucket(); + mScroller = new CoverScroller(context); + } + + /** + * Configures and sets up this view + */ + public void setup(Looper looper, Callback callback, int style) { + mUiHandler = new Handler(this); + mHandler = new Handler(looper, this); + mCallback = callback; + mCoverStyle = style; + } + + /** + * Sent if the songs timeline changed and we should check if + * mCacheBitmap is stale. + * Just calls querySongsInternal() via handler to ensure + * that we do this in a background thread. + */ + public void querySongs() { + mHandler.removeMessages(MSG_QUERY_SONGS); + mHandler.sendEmptyMessage(MSG_QUERY_SONGS); + } + + /** + * Called if a specific song got replaced. + * The current implementation does not take this hint into + * account as querySongsInternal() already tries to be efficient. + */ + public void replaceSong(int delta, Song song) { + querySongs(); + } + + /** + * Called by querySongs() - this runs in a background thread. + */ + private void querySongsInternal() { + DEBUG("querySongsInternal"); + + if (getWidth() < 1 || getHeight() < 1) { + mPendingQuery = true; + return; + } + + if (mScrollX < 0) { // initialize mScrollX to show cover '1' by default. + mScrollX = getWidth(); + } + + mHandler.removeMessages(MSG_SET_BITMAP); + PlaybackService service = PlaybackService.get(mContext); + + final Song[] songs = { service.getSong(-1), service.getSong(0), service.getSong(1) }; + final int len = songs.length; + + for (int i = 0; i < len; i++) { + Song song = songs[i]; + if (mBitmapBucket.getSong(i) != song) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_BITMAP, i, 0, song)); + } + } + } + + /** + * Updates the cover in bitmap bucket for given index. + * + * @param i the index to modify + * @param song the source of the cover + */ + private void setSongBitmap(int i, Song song) { + Bitmap bitmap = mBitmapBucket.grepBitmap(song); + + if (bitmap == null && song != null) + bitmap = generateBitmap(song); + + mBitmapBucket.setSongBitmap(i, song, bitmap); + postInvalidate(); + } + + /** + * Returns a correctly sized cover bitmap for given song + */ + private Bitmap generateBitmap(Song song) { + int style = mCoverStyle; + Bitmap cover = song == null ? null : song.getLargeCover(mContext); + + if (cover == null && style != CoverBitmap.STYLE_OVERLAPPING_BOX) { + cover = CoverBitmap.generateDefaultCover(mContext, getWidth(), getHeight()); + } + + return CoverBitmap.createBitmap(mContext, style, cover, song, getWidth(), getHeight()); + } + + + private final static int MSG_QUERY_SONGS = 1; + private final static int MSG_SHIFT_SONG = 2; + private final static int MSG_SET_BITMAP = 3; + private final static int MSG_UI_LONG_CLICK = 4; // should only be used with mUiHandler + + @Override + public boolean handleMessage(Message message) { + switch (message.what) { + case MSG_QUERY_SONGS: + querySongsInternal(); + break; + case MSG_SHIFT_SONG: + DEBUG("Shifting to song: "+message.arg1); + mCallback.shiftCurrentSong(message.arg1); + break; + case MSG_SET_BITMAP: + setSongBitmap(message.arg1, (Song)message.obj); + break; + case MSG_UI_LONG_CLICK: + if (!Looper.getMainLooper().equals(Looper.myLooper())) { + throw new IllegalStateException("MSG_UI_LONG_CLICK must be run from the UI thread"); + } + if (scrollIsNotSignificant()) { + performLongClick(); + } + break; + default: + throw new IllegalArgumentException("Unknown message received: "+message.what); + } + return true; + } + + /** + * Triggers if the view changes its size, may call querySongs() if it was called + * previously but had to be aborted as the view was not yet laid out. + */ + @Override + protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { + if (mPendingQuery && width != 0 && height != 0) { + mPendingQuery = false; + querySongs(); + } + } + + /** + * Lays out this view - only handles our specific use cases + */ + @Override + protected void onMeasure(int widthSpec, int heightSpec) { + // This implementation only tries to handle two cases: use in the + // FullPlaybackActivity, where we want to fill the whole screen, + // and use in the MiniPlaybackActivity, where we want to be square. + + int width = View.MeasureSpec.getSize(widthSpec); + int height = View.MeasureSpec.getSize(heightSpec); + if (View.MeasureSpec.getMode(widthSpec) == View.MeasureSpec.EXACTLY && View.MeasureSpec.getMode(heightSpec) == View.MeasureSpec.EXACTLY) { + // FullPlaybackActivity: fill screen + setMeasuredDimension(width, height); + } else { + // MiniPlaybackActivity: be square + int size = Math.min(width, height); + setMeasuredDimension(size, size); + } + } + + /** + * Paint the cover art views to the canvas. + */ + @Override + protected void onDraw(Canvas canvas) { + int width = getWidth(); + int height = getHeight(); + int x = 0; + int scrollX = mScrollX; + boolean snapshot = !mScroller.isFinished(); + Bitmap bitmap; + + for (int i=0; i <= 2 ; i++) { + bitmap = snapshot ? mBitmapBucket.getSnapshot(i) : mBitmapBucket.getBitmap(i); + if (bitmap != null && scrollX + width > x && scrollX < x + width) { + final int xOffset = (width - bitmap.getWidth()) / 2; + final int yOffset = (int)(height - bitmap.getHeight()) / 2; + canvas.drawBitmap(bitmap, x + xOffset - scrollX, yOffset, null); + } + x += width; + } + advanceScroll(); + } + + /** + * Advances to the next frame of the animation. + */ + private void advanceScroll() { + boolean running = mScroller.computeScrollOffset(); + if (running) { + mScrollX = mScroller.getCurrX(); + if (mScroller.isFinished()) { + // just hit the end! + mBitmapBucket.finalizeScroll(); + mScrollX = getWidth(); + + int coverIntent = mScroller.getCoverIntent(); + if (coverIntent != 0 && ASYNC_SWITCH < 0) + mHandler.sendMessage(mHandler.obtainMessage(MSG_SHIFT_SONG, coverIntent, 0)); + + DEBUG("Scroll finished, invalidating all snapshot bitmaps!"); + } + invalidate(); + } + } + + /** + * Handles all touch events received by this view. + */ + @Override + public boolean onTouchEvent(MotionEvent ev) { + float x = ev.getX(); + float y = ev.getY(); + int scrollX = mScrollX; + int width = getWidth(); + boolean invalidate = false; + + if (mVelocityTracker == null) + mVelocityTracker = VelocityTracker.obtain(); + mVelocityTracker.addMovement(ev); + + switch (ev.getAction()) { + case MotionEvent.ACTION_DOWN: { + + if (mScroller.isFinished()) { + mUiHandler.sendEmptyMessageDelayed(MSG_UI_LONG_CLICK, ViewConfiguration.getLongPressTimeout() * 2); + } else { + // Animation was still running while we got a new down event + // Abort the current animation! + + final int coverIntent = mScroller.getCoverIntent(); + mBitmapBucket.abortScroll(); + mScroller.abortAnimation(); + + if (coverIntent != 0) { + // The running animation was actually supposed to switch to a new song. + // Do this right now as the animation is canceled: + // First, set our non-cached covers to a sane version + mBitmapBucket.prepareScroll(coverIntent); + // ..and fix up the scrolling position. + mScrollX -= coverIntent * getWidth(); + // all done: we can now trigger the song jump + if (ASYNC_SWITCH < 0 || mHandler.hasMessages(MSG_SHIFT_SONG)) { + mHandler.removeMessages(MSG_SHIFT_SONG); + mHandler.sendMessage(mHandler.obtainMessage(MSG_SHIFT_SONG, coverIntent, 0)); + } + } + + // There is no running animation (anymore?), so we can drop the cache. + mBitmapBucket.finalizeScroll(); + } + + mLastMotionX = mInitialMotionX = x; + mLastMotionY = mInitialMotionY = y; + + break; + } + case MotionEvent.ACTION_MOVE: { + final float deltaX = mLastMotionX - x; + final float deltaY = mLastMotionY - y; + + if (Math.abs(deltaX) > Math.abs(deltaY)) { // only change X if the fling is horizontal + if (deltaX < 0) { + int availableToScroll = scrollX - (mBitmapBucket.getSong(0) == null ? width : 0); + if (availableToScroll > 0) { + mScrollX += Math.max(-availableToScroll, (int)deltaX); + invalidate = true; + } + } else if (deltaX > 0) { + int availableToScroll = width * 2 - scrollX; + if (availableToScroll > 0) { + mScrollX += Math.min(availableToScroll, (int)deltaX); + invalidate = true; + } + } + } + + mLastMotionX = x; + mLastMotionY = y; + break; + } + case MotionEvent.ACTION_UP: { + VelocityTracker velocityTracker = mVelocityTracker; + velocityTracker.computeCurrentVelocity(1000); // report velocity in pixels-per-second, as assumed by snap-velocity and co. + final int velocityX = (int) velocityTracker.getXVelocity(); + final int velocityY = (int) velocityTracker.getYVelocity(); + mVelocityTracker.recycle(); + mVelocityTracker = null; + + final int mvx = Math.abs(velocityX); + final int mvy = Math.abs(velocityY); + final float distanceX = mLastMotionX - mInitialMotionX; + int whichCover = 0; + + if (scrollIsNotSignificant()) { + if (mUiHandler.hasMessages(MSG_UI_LONG_CLICK)) { + // long click didn't fire yet -> consider this to be a normal click + performClick(); + } + } else if (Math.abs(distanceX) > width/2) { + whichCover = distanceX < 0 ? 1 : -1; + } else if (mvx > sSnapVelocity || mvy > sSnapVelocity) { + if (mvy > mvx) { + if (velocityY > 0) + mCallback.downSwipe(); + else + mCallback.upSwipe(); + } else { + whichCover = velocityX < 0 ? 1 : -1; + } + } + + // Ensure that the target song actually exists. + // Eg: We may not have song 0 in random mode. + if (mBitmapBucket.getSong(1+whichCover) == null) + whichCover = 0; + + final int scrollTargetX = width + whichCover*width; + + mBitmapBucket.prepareScroll(whichCover); + mScroller.handleFling(velocityX, mScrollX, scrollTargetX, whichCover); + if (ASYNC_SWITCH >= 0) + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHIFT_SONG, whichCover, 0), ASYNC_SWITCH); + mUiHandler.removeMessages(MSG_UI_LONG_CLICK); + + invalidate = true; + break; + } + } + + if (invalidate) + postInvalidate(); + + return true; + } + + /** + * Returns true if the scroll traveled a significant distance + * and is therefore not considered to be random noise during a click. + */ + private boolean scrollIsNotSignificant() { + final float distanceX = mLastMotionX - mInitialMotionX; + final float distanceY = mLastMotionY - mInitialMotionY; + return Math.abs(distanceX) + Math.abs(distanceY) < TOUCH_MAX_SCROLL_PX; + } + + private void DEBUG(String s) { + // Log.v("VanillaMusicCover", s); + } + + + /** + * Class to handle access to our bitmap and song mapping + */ + private class BitmapBucket { + /** + * The pre-generated bitmaps for all 3 songs + */ + private final Bitmap[] mCacheBitmaps = new Bitmap[3]; + /** + * Cached songs, used to check if mCacheBitmaps is still valid + */ + private final Song[] mCacheSongs = new Song[3]; + /** + * A WIP copy: We use this (iff available) to draw. + * This allows us to update mCacheBitmaps while scrolling + */ + private final Bitmap[] mSnapshotBitmaps = new Bitmap[3]; + /** + * A WIP copy of songs, used if we have to restore + * This snapshot is only used internally and copied + * to mCacheBitmaps if we restore our bitmap snapshot. + */ + private final Song[] mSnapshotSongs = new Song[3]; + /** + * Constructor for BitmapBucket + */ + public BitmapBucket() { + } + + public Song getSong(int i) { + return mCacheSongs[i]; + } + + public Bitmap getBitmap(int i) { + return mCacheBitmaps[i]; + } + + public Bitmap getSnapshot(int i) { + return mSnapshotBitmaps[i]; + } + + public void setSongBitmap(int i, Song song, Bitmap bitmap) { + mCacheSongs[i] = song; + mCacheBitmaps[i] = bitmap; + } + + public Bitmap grepBitmap(Song song) { + final int len = mCacheSongs.length; + for (int i = 0; i < len ; i++) { + if (song != null && song.equals(mCacheSongs[i])) { + return mCacheBitmaps[i]; + } + } + return null; + } + + /** + * Hint that we are going to scroll. + * This causes us to populate our bitmap snapshot + * and will cause us to modify the current cache with a guess. + * + * @param futureCover the cover we are going to scroll to + */ + public void prepareScroll(int futureCover) { + // Grab a snapshot of the bitmaps which will be used + // while the animation is running, so that we can concurrently + // modify mCacheBitmaps. + System.arraycopy(mCacheBitmaps, 0, mSnapshotBitmaps, 0, 3); + System.arraycopy(mCacheSongs, 0, mSnapshotSongs, 0, 3); + + // we are going to scroll, so most likely we can save 2 bitmaps by guessing the + // new situation. This doesn't have to be 100% correct as the next querySongs() + // call would fix up wrong guesses. + // FIXME: This may be under-locked: cache checks via getSong() and prepareScroll() may race. + if (futureCover > 0) { + mCacheBitmaps[0] = mCacheBitmaps[1]; + mCacheSongs[0] = mCacheSongs[1]; + mCacheBitmaps[1] = mCacheBitmaps[2]; + mCacheSongs[1] = mCacheSongs[2]; + mCacheBitmaps[2] = null; + mCacheSongs[2] = new Song(-1); + } else if (futureCover < 0) { + mCacheBitmaps[2] = mCacheBitmaps[1]; + mCacheSongs[2] = mCacheSongs[1]; + mCacheBitmaps[1] = mCacheBitmaps[0]; + mCacheSongs[1] = mCacheSongs[0]; + mCacheBitmaps[0] = null; + mCacheSongs[0] = new Song(-1); + } + } + + /** + * Abort a scroll initiated by prepareScroll. + */ + public void abortScroll() { + // undo our guess we did in prepareScroll + System.arraycopy(mSnapshotBitmaps, 0, mCacheBitmaps, 0, 3); + System.arraycopy(mSnapshotSongs, 0, mCacheSongs, 0, 3); + finalizeScroll(); + } + + public void finalizeScroll() { + for (int i=0; i <= 2; i++) { + mSnapshotBitmaps[i] = null; + mSnapshotSongs[i] = null; + } + } + + } + + /** + * The scroller class helps to keep track + * of the current scroll progress. + */ + private class CoverScroller extends Scroller { + /** + * The cover we are scrolling to + */ + private int mCoverIntent; + /** + * Returns a new scroller instance + */ + public CoverScroller(Context context) { + super(context, new LinearInterpolator(), false); + } + + /** + * Returns the cover set by the last handleFling + * call. + * + * @return int the cover set by handleFling. + */ + public int getCoverIntent() { + return mCoverIntent; + } + + @Override + public void abortAnimation() { + mCoverIntent = 0; + super.abortAnimation(); + } + /** + * Starts a fling operation + * + * @param velocity the current velocity + * @param from the current x coordinate + * @param to the target x coordinate + * @param coverIntent the cover we are scrolling to, returned by getCoverIntent() + */ + public void handleFling(int velocity, int from, int to, int coverIntent) { + if (!isFinished()) { + abortAnimation(); + } + + mCoverIntent = coverIntent; + + final int distance = to - from; + int duration = (int)(Math.abs(distance) / sDensity); + if (duration > 200) + duration = 200; + + startScroll(from, 0, distance, 0, duration); + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/DraggableRow.java b/app/src/main/java/ch/blinkenlights/android/vanilla/DraggableRow.java new file mode 100644 index 0000000..96fcc39 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/DraggableRow.java @@ -0,0 +1,233 @@ +/* + * Copyright (C) 2014-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.graphics.Color; +import android.text.format.DateUtils; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.style.ForegroundColorSpan; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.CheckedTextView; +import android.widget.Checkable; + +public class DraggableRow extends LinearLayout implements Checkable { + /** + * True if the checkbox is checked + */ + private boolean mChecked; + /** + * True if setupLayout has been called + */ + private boolean mLayoutSet; + + private TextView mTextView; + private TextView mDurationView; + private CheckedTextView mCheckBox; + private View mPmark; + private ImageView mDragger; + private View mDraggerPadder; + private LazyCoverView mCoverView; + + /** + * Layout types for use with setupLayout + */ + public static final int LAYOUT_TEXTONLY = 0; + public static final int LAYOUT_CHECKBOXES = 1; + public static final int LAYOUT_DRAGGABLE = 2; + public static final int LAYOUT_LISTVIEW = 3; + + + public DraggableRow(Context context, AttributeSet attrs) { + super(context, attrs); + } + + + @Override + public void onFinishInflate() { + mCheckBox = (CheckedTextView)this.findViewById(R.id.checkbox); + mTextView = (TextView)this.findViewById(R.id.text); + mDurationView = findViewById(R.id.duration); + mPmark = (View)this.findViewById(R.id.pmark); + mDragger = (ImageView)this.findViewById(R.id.dragger); + mDraggerPadder = (View)this.findViewById(R.id.dragger_padder); + mCoverView = (LazyCoverView)this.findViewById(R.id.cover); + super.onFinishInflate(); + } + + /** + * Sets up commonly used layouts - can only be called once per view + * + * @param type the layout type to use + */ + public void setupLayout(int type) { + if (!mLayoutSet) { + switch (type) { + case LAYOUT_CHECKBOXES: + mCheckBox.setVisibility(View.VISIBLE); + showDragger(true); + break; + case LAYOUT_DRAGGABLE: + highlightRow(false); // make this visible + mCoverView.setVisibility(View.VISIBLE); + mDurationView.setVisibility(View.VISIBLE); + showDragger(true); + break; + case LAYOUT_LISTVIEW: + highlightRow(false); // make this visible + mCoverView.setVisibility(View.VISIBLE); + mDragger.setImageResource(R.drawable.arrow); + break; + case LAYOUT_TEXTONLY: + default: + break; // do not care + } + mLayoutSet = true; + } + } + + @Override + public boolean isChecked() { + return mChecked; + } + + @Override + public void setChecked(boolean checked) { + mChecked = checked; + mCheckBox.setChecked(mChecked); + } + + @Override + public void toggle() { + setChecked(!mChecked); + } + + /** + * We glue tags to the text view to make getTag() simpler and consistent + * with the on click listener interception + */ + @Override + public void setTag(Object tag) { + mTextView.setTag(tag); + } + + @Override + public Object getTag() { + return mTextView.getTag(); + } + + /** + * Marks a row as highlighted + * @param state Enable or disable highlighting + */ + public void highlightRow(boolean state) { + mPmark.setVisibility( state ? View.VISIBLE : View.INVISIBLE ); + } + + /** + * Change visibility of dragger element + * + * @param state shows or hides the dragger + */ + public void showDragger(boolean state) { + mDragger.setVisibility( state ? View.VISIBLE : View.GONE ); + adjustPadding(); + } + + /** + * Change visibility of duration textview + * + * @param state shows or hides the textview + */ + public void showDuration(boolean state) { + mDurationView.setVisibility( state ? View.VISIBLE : View.GONE ); + adjustPadding(); + } + + public void setDraggerOnClickListener(View.OnClickListener listener) { + TypedValue v = new TypedValue(); + getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, v, true); + + mDragger.setBackgroundResource(v.resourceId); + mDragger.setOnClickListener(listener); + } + + /** + * Sets the text to given string. + * + * @param line the text to display + */ + public void setText(CharSequence line) { + mTextView.setText(line); + } + + /** + * Display two lines + * + * @param line1 the first line to show + * @param line2 the second line to show + */ + public void setText(CharSequence line1, CharSequence line2) { + if (line1 == null) + line1 = "???"; + + SpannableStringBuilder sb = new SpannableStringBuilder(line1); + sb.append("\n"); + sb.append(line2); + sb.setSpan(new ForegroundColorSpan(Color.GRAY), line1.length() + 1, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + mTextView.setText(sb); + } + + /** + * Display given duration, negative values + * result in '--:--' + * + * @param duration the duration in ms to display + */ + public void setDuration(long duration) { + String txt = "--:--"; + if (duration >= 0) { + txt = DateUtils.formatElapsedTime(duration / 1000); + } + + SpannableStringBuilder sb = new SpannableStringBuilder("\n"+txt); + sb.setSpan(new ForegroundColorSpan(Color.GRAY), 1, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + mDurationView.setText(sb); + } + + /** + * Returns an instance of our coverview + */ + public LazyCoverView getCoverView() { + return mCoverView; + } + + /** + * Check whether we need to add padding due to the lack of mDragger's visibility + */ + private void adjustPadding() { + boolean pad = (mDurationView.getVisibility() == View.VISIBLE && mDragger.getVisibility() == View.GONE); + mDraggerPadder.setVisibility( pad ? View.VISIBLE : View.GONE ); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FastScrollGuardedListView.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FastScrollGuardedListView.java new file mode 100644 index 0000000..a41a5c9 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FastScrollGuardedListView.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.res.Resources; +import android.util.AttributeSet; +import android.view.MotionEvent; +import android.widget.ListView; + + +public class FastScrollGuardedListView extends ListView { + + /** + * Start edgeProtection at width-start + */ + private static final int PROTECT_START_DP = 50; // AOSP has this set to 48dip in 5.x + /** + * End protection at width-end + */ + private static final int PROTECT_END_DP = 12; + /** + * The calculated start position in pixel + */ + private float mEdgeProtectStartPx = 0; + /** + * The calculated end position in pixel + */ + private float mEdgeProtectEndPx = 0; + + + public FastScrollGuardedListView(Context context) { + super(context); + } + public FastScrollGuardedListView(Context context, AttributeSet attrs) { + super(context, attrs); + } + public FastScrollGuardedListView(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + } + public FastScrollGuardedListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + super(context, attrs, defStyleAttr, defStyleRes); + } + + /** + * Intercepted touch event from ListView + * We will use this callback to send fake X-coord events if + * the actual event happened in the protected area (eg: the hardcoded fastscroll area) + */ + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + if (mEdgeProtectStartPx == 0) + mEdgeProtectStartPx = getWidth() - PROTECT_START_DP * Resources.getSystem().getDisplayMetrics().density; + if (mEdgeProtectEndPx == 0) + mEdgeProtectEndPx = getWidth() - PROTECT_END_DP * Resources.getSystem().getDisplayMetrics().density; + + if (ev.getX() > mEdgeProtectStartPx && ev.getX() < mEdgeProtectEndPx) { + // Cursor is in protected area: simulate an event with a faked x coordinate + ev = MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), ev.getAction(), mEdgeProtectStartPx, ev.getY(), ev.getMetaState()); + } + return super.onInterceptTouchEvent(ev); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FileSystemAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FileSystemAdapter.java new file mode 100644 index 0000000..8bab6d8 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FileSystemAdapter.java @@ -0,0 +1,472 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2015-2021 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.Intent; +import android.os.FileObserver; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.regex.Pattern; + +/** + * A list adapter that provides a view of the filesystem. The active directory + * is set through a {@link Limiter} and rows are displayed using MediaViews. + */ +public class FileSystemAdapter + extends SortableAdapter + implements LibraryAdapter +{ + private static final Pattern SPACE_SPLIT = Pattern.compile("\\s+"); + private static final Pattern FILE_SEPARATOR = Pattern.compile(File.separator); + private static final Pattern GUESS_MUSIC = Pattern.compile("^(.+\\.(mp3|ogg|mka|opus|flac|aac|m4a|wav))$", Pattern.CASE_INSENSITIVE); + private static final Pattern GUESS_IMAGE = Pattern.compile("^(.+\\.(gif|jpe?g|png|bmp|tiff?|webp))$", Pattern.CASE_INSENSITIVE); + /** + * The root directory of the device + */ + private final File mFsRoot = new File("/"); + /** + * Sort by filename. + */ + private static final int SORT_NAME = 0; + /** + * Sort by file size. + */ + private static final int SORT_SIZE = 1; + /** + * Sort by file modification time. + */ + private static final int SORT_TIME = 2; + /** + * Sort by file extension. + */ + private static final int SORT_EXT = 3; + /** + * The IDs of human-readable descriptions for each sort mode. + * Must be consistent with SORT_* fields. + */ + private static final int[] SORT_RES_IDS = new int[] { + R.string.filename, + R.string.file_size, + R.string.file_time, + R.string.extension }; + + /** + * The owner LibraryActivity. + */ + final LibraryActivity mActivity; + /** + * A LayoutInflater to use. + */ + private final LayoutInflater mInflater; + /** + * The currently active limiter, set by a row expander being clicked. + */ + private Limiter mLimiter; + /** + * The files and folders in the current directory. + */ + private File[] mFiles; + /** + * The currently active filter, entered by the user from the search box. + */ + String[] mFilter; + /** + * Excludes dot files and files not matching mFilter. + */ + private final FilenameFilter mFileFilter = new FilenameFilter() { + @Override + public boolean accept(File dir, String filename) + { + if (filename.charAt(0) == '.') + return false; + if (mFilter != null) { + filename = filename.toLowerCase(); + for (String term : mFilter) { + if (!filename.contains(term)) + return false; + } + } + return true; + } + }; + /** + * Sorts folders before files first, then sorts by current sort mode. + */ + private final Comparator<File> mFileComparator = new Comparator<File>() { + @Override + public int compare(File a, File b) + { + boolean aIsFolder = a.isDirectory(); + boolean bIsFolder = b.isDirectory(); + if (bIsFolder == aIsFolder) { + int mode = aIsFolder ? SORT_NAME : getSortModeIndex(); + int order; + switch (mode) { + case SORT_SIZE: + order = Long.valueOf(a.length()).compareTo(Long.valueOf(b.length())); + break; + case SORT_TIME: + order = Long.valueOf(a.lastModified()) + .compareTo(Long.valueOf(b.lastModified())); + break; + case SORT_EXT: + order = FileUtils.getFileExtension(a.getName()) + .compareToIgnoreCase(FileUtils.getFileExtension(b.getName())); + break; + case SORT_NAME: + order = a.getName().compareToIgnoreCase(b.getName()); + break; + default: + throw new IllegalArgumentException("Invalid sort mode: " + mode); + } + return (isSortDescending() ? -1 : 1) * order; + } else if (bIsFolder) { + return 1; + } + return -1; + } + }; + /** + * The Observer instance for the current directory. + */ + private Observer mFileObserver; + + /** + * Create a FileSystemAdapter. + * + * @param activity The LibraryActivity that will contain this adapter. + * Called on to requery this adapter when the contents of the directory + * change. + * @param limiter An initial limiter to set. If none is given, will be set + * to the external storage directory. + */ + public FileSystemAdapter(LibraryActivity activity, Limiter limiter) + { + mActivity = activity; + mLimiter = limiter; + mInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + if (limiter == null) { + limiter = buildHomeLimiter(activity); + } + setLimiter(limiter); + mSortEntries = SORT_RES_IDS; + } + + @Override + public Object query() + { + File file = getLimiterPath(); + + if (mFileObserver == null) { + mFileObserver = new Observer(file.getPath()); + } + + ArrayList<File> files; + File[] readdir = file.listFiles(mFileFilter); + if (readdir != null) { + files = new ArrayList<File>(Arrays.asList(readdir)); + } else { + files = FileUtils.getFallbackDirectories((Context)mActivity, file); + } + + Collections.sort(files, mFileComparator); + if (!mFsRoot.equals(file)) + files.add(0, new File(file, FileUtils.NAME_PARENT_FOLDER)); + + return files.toArray(new File[files.size()]); + } + + @Override + public void commitQuery(Object data) + { + mFiles = (File[])data; + notifyDataSetChanged(); + } + + @Override + public void clear() + { + mFiles = null; + notifyDataSetInvalidated(); + } + + @Override + public int getCount() + { + if (mFiles == null) + return 0; + return mFiles.length; + } + + @Override + public Object getItem(int pos) + { + return mFiles[pos]; + } + + @Override + public long getItemId(int pos) + { + return FileUtils.songIdFromFile(mFiles[pos]); + } + + @Override + public View getView(int pos, View convertView, ViewGroup parent) + { + DraggableRow row; + ViewHolder holder; + + if (convertView == null) { + row = (DraggableRow)mInflater.inflate(R.layout.draggable_row, parent, false); + row.setupLayout(DraggableRow.LAYOUT_LISTVIEW); + + holder = new ViewHolder(); + row.setTag(holder); + } else { + row = (DraggableRow)convertView; + holder = (ViewHolder)row.getTag(); + } + + final File file = mFiles[pos]; + final String title = file.getName(); + + holder.id = pos; + holder.title = title; + row.setText(title); + row.getCoverView().setImageResource(getImageResourceForFile(file)); + return row; + } + + @Override + public void setFilter(String filter) + { + if (filter == null) + mFilter = null; + else + mFilter = SPACE_SPLIT.split(filter.toLowerCase()); + } + + @Override + public void setLimiter(Limiter limiter) + { + if (mFileObserver != null) + mFileObserver.stopWatching(); + mFileObserver = null; + + if (limiter != null && mFsRoot.equals(limiter.data)) + limiter = null; // Filtering by mFsRoot is like having no filter + + mLimiter = limiter; + } + + @Override + public Limiter getLimiter() + { + return mLimiter; + } + + /** + * Returns a drawable resource id for given file. + * This function is rather fast as the file type is guessed + * based on the extension. + * + * @return resource id to use. + */ + private int getImageResourceForFile(File file) { + int res = R.drawable.file_document; + if (pointsToParentFolder(file)) { + res = R.drawable.arrow_up; + } else if (file.isDirectory()) { + res = R.drawable.folder; + } else if (GUESS_MUSIC.matcher(file.getName()).matches()) { + res = R.drawable.file_music; + } else if (GUESS_IMAGE.matcher(file.getName()).matches()) { + res = R.drawable.file_image; + } + return res; + } + + /** + * Returns the unixpath represented by this limiter + * + * @return the file of this limiter represents + */ + private File getLimiterPath() { + return mLimiter == null ? new File("/") : (File)mLimiter.data; + } + + /** + * Returns true if the filename of 'file' indicates that + * it points to '..' + * + * @return true if given file points to the parent folder + */ + private static boolean pointsToParentFolder(File file) { + return FileUtils.NAME_PARENT_FOLDER.equals(file.getName()); + } + + /** + * Builds a limiter from the given folder. Only files contained in the + * given folder will be shown if the limiter is set on this adapter. + * + * @param file A File pointing to a folder. + * @return A limiter describing the given folder. + */ + public static Limiter buildLimiter(File file) + { + if (pointsToParentFolder(file)) + file = file.getParentFile().getParentFile(); + String[] fields = FILE_SEPARATOR.split(file.getPath().substring(1)); + return new Limiter(MediaUtils.TYPE_FILE, fields, file); + } + + /** + * Builds the limiter pointing to our home directory + * + * @param context the context to use + * @return A limiter which is configured as 'home' directory + */ + public static Limiter buildHomeLimiter(Context context) { + return buildLimiter(FileUtils.getFilesystemBrowseStart(context)); + } + + @Override + public Limiter buildLimiter(long id) { + for (int i = 0; i < mFiles.length; i++) { + if (id == getItemId(i)) { + return buildLimiter(mFiles[i]); + } + } + return null; + } + + @Override + public int getMediaType() + { + return MediaUtils.TYPE_FILE; + } + + /** + * FileObserver that reloads the files in this adapter. + */ + private class Observer extends FileObserver { + public Observer(String path) + { + super(path, FileObserver.CREATE | FileObserver.DELETE | FileObserver.MOVED_TO | FileObserver.MOVED_FROM); + startWatching(); + } + + @Override + public void onEvent(int event, String path) + { + if (path != null) // Android bug? We seem to receive MOVE_SELF events + mActivity.mPagerAdapter.postRequestRequery(FileSystemAdapter.this); + } + } + + @Override + public Intent createData(View view) + { + ViewHolder holder = (ViewHolder)view.getTag(); + File file = mFiles[(int)holder.id]; + + Intent intent = new Intent(); + intent.putExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_FILE); + intent.putExtra(LibraryAdapter.DATA_ID, getItemId((int)holder.id)); + intent.putExtra(LibraryAdapter.DATA_TITLE, holder.title); + intent.putExtra(LibraryAdapter.DATA_EXPANDABLE, file.isDirectory()); + intent.putExtra(LibraryAdapter.DATA_FILE, file.getAbsolutePath()); + return intent; + } + + @Override + public int getDefaultSortMode() { + return SORT_NAME; + } + + @Override + public String getSortSettingsKey() { + return "sort_filesystem"; + } + + /** + * Returns all songs represented by this adapter. + * Note that this will do a recursive query! + * + * @param projection the projection to use + * @return a query task + */ + @Override + public QueryTask buildSongQuery(String[] projection) { + File path = getLimiterPath(); + return MediaUtils.buildFileQuery(path.getPath(), projection, true); + } + + /** + * A row was clicked: this was dispatched by LibraryPagerAdapter + * + * @param intent likely created by createData() + */ + public void onItemClicked(Intent intent) { + boolean isFolder = intent.getBooleanExtra(LibraryAdapter.DATA_EXPANDABLE, false); + boolean isHeader = intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID) + == LibraryAdapter.HEADER_ID; + + if (!isHeader && FileUtils.canDispatchIntent(intent) && FileUtils.dispatchIntent(mActivity, intent)) + return; + + if (isFolder) { + mActivity.onItemExpanded(intent); + } else { + mActivity.onItemClicked(intent); + } + } + + /** + * Context menu of a row: this was dispatched by LibraryPagerAdapter + * + * @param intent likely created by createData() + * @param view the parent view + * @param x x-coords of event + * @param y y-coords of event + */ + public boolean onCreateFancyMenu(Intent intent, View view, float x, float y) { + String path = intent.getStringExtra(LibraryAdapter.DATA_FILE); + boolean isParentRow = (path != null && pointsToParentFolder(new File(path))); + + if (!isParentRow) + return mActivity.onCreateFancyMenu(intent, view, x, y); + // else: no context menu, but consume event. + return true; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FileUtils.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FileUtils.java new file mode 100644 index 0000000..cb03a36 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FileUtils.java @@ -0,0 +1,283 @@ +/* + * Copyright (C) 2015-2020 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import java.io.File; +import java.net.URI; +import java.net.URLConnection; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.StringTokenizer; + +import java.nio.file.Path; + +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.text.TextUtils; +import android.util.Log; + + +/** + * Provides some static File-related utility functions. + */ +public class FileUtils { + /** + * The string (but also valid path!) to use to indicate the current directory + */ + public static final String NAME_CURRENT_FOLDER = "."; + /** + * The string (but also valid path!) to use to indicate the parent directory + */ + public static final String NAME_PARENT_FOLDER = ".."; + + private FileUtils() { + // Private constructor to hide implicit one. + } + + /** + * Converts common path separator characters ('/' or '\\') to the value of File.separatorChar. + * + * @param path The path to convert directory separators within. + * @return A path with all valid separators normalized to the system's. + */ + public static String normalizeDirectorySeparators(String path) { + final StringBuilder sb = new StringBuilder(path); + + for (int i = 0; i < sb.length(); i++) { + final char originalChar = sb.charAt(i); + if (originalChar == '/' || originalChar == '\\') { + sb.setCharAt(i, File.separatorChar); + } + } + return sb.toString(); + } + + /** + * Utility function to prepend n-parent directory traversals to a path. + * + * @param path A relative path to traverse upwards from within. + * @param traversalCount The number of directories to navigate upwards. + * @return The result of creating the relative path. + */ + private static String traversePathUpwards(String path, int traversalCount) { + if (traversalCount < 0) + throw new IllegalArgumentException("Cannot descend into the directory structure."); + + if (traversalCount == 0) + return path; + + StringBuilder sb = new StringBuilder((FileUtils.NAME_PARENT_FOLDER.length() + 1) * traversalCount + + path.length()); + + for (int i = 0; i < traversalCount; i++) { + sb.append(FileUtils.NAME_PARENT_FOLDER); + sb.append(File.separatorChar); + } + sb.append(path); + return sb.toString(); + } + + /** + * Attempts to generate a relative path from a base, to a destination. + * Will attempt to perform directory traversal to find a common path. + * Upon failure to relativize, returns the original destination. + * + * @param base The File the path is relative to e.g. /a/b/c/ + * @param destination The File the resultant path should point to e.g. /a/b/c/d.mp3 + * @return A relative or absolute path pointing to the destination. + */ + public static String relativize(File base, File destination) { + if (destination.isAbsolute() != base.isAbsolute()) + return destination.getPath(); + + File commonParentFile = base; + final String destinationPath = destination.getPath(); + int traversalCount = 0; + + if (commonParentFile.equals(destination)) { + return FileUtils.NAME_CURRENT_FOLDER; + } + + do { + String parentPath = commonParentFile.getPath(); + if (!parentPath.endsWith(File.separator)) { + parentPath += File.separatorChar; + } + + if (destinationPath.startsWith(parentPath)) { + return traversePathUpwards( + destinationPath.substring(parentPath.length()), + traversalCount); + } + ++traversalCount; + } while ((commonParentFile = commonParentFile.getParentFile()) != null); + return destination.getPath(); + } + + /** + * Attempts to resolve a path from a base, if the destination is relative. + * Upon failure to resolve, returns the original destination. + * + * @param base The File the path may be relative to e.g. /a/b/c/ + * @param destination The File the resultant path should point to e.g. d.mp3 + * @return A relative or absolute path pointing to the destination. + */ + public static String resolve(File base, File destination) { + String path = destination.getPath(); + + try { + if (!destination.isAbsolute()) { + path = new File(base, path).getAbsolutePath(); + final ArrayList<String> pathComponents = new ArrayList<>(); + final StringTokenizer pathTokenizer = new StringTokenizer(path, File.separator); + + while (pathTokenizer.hasMoreTokens()) { + final String pathComponent = pathTokenizer.nextToken(); + + if (NAME_PARENT_FOLDER.equals(pathComponent)) { + final int lastComponentPosition = pathComponents.size() - 1; + + if (lastComponentPosition >= 0 + && !NAME_PARENT_FOLDER.equals(pathComponents.get(lastComponentPosition))) { + pathComponents.remove(lastComponentPosition); + } + } else { + pathComponents.add(pathComponent); + } + } + path = File.separator + TextUtils.join(File.separator, pathComponents); + } + } catch (SecurityException ex) { + // Ignore. + } + return path; + } + + + /** + * Checks if dispatching this intent to an external application makes sense + * + * @param intent The intent to examine + * @return bool true if the intent could be dispatched + */ + public static boolean canDispatchIntent(Intent intent) { + boolean canDispatch = false; + + int type = intent.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID); + boolean isFolder = intent.getBooleanExtra(LibraryAdapter.DATA_EXPANDABLE, false); + String path = intent.getStringExtra(LibraryAdapter.DATA_FILE); + if (type == MediaUtils.TYPE_FILE && !isFolder) { + try { + URI uri = new URI("file", path, null); + String mimeGuess = URLConnection.guessContentTypeFromName(uri.toString()); + if (mimeGuess != null && mimeGuess.matches("^(image|text)/.+")) { + canDispatch = true; + } + } catch (URISyntaxException e) { + Log.e("VanillaMusic", "failed to encode "+path+": "+e); + } + } + return canDispatch; + } + + /** + * Opens an intent in an external application + * + * @param activity The library activity to use + * @param intent The intent to examine and launch + * @return bool true if the intent was dispatched + */ + public static boolean dispatchIntent(LibraryActivity activity, Intent intent) { + boolean handled = true; + + String path = intent.getStringExtra(LibraryAdapter.DATA_FILE); + String mimeGuess = URLConnection.guessContentTypeFromName(path); + File file = new File(path); + Uri uri = Uri.fromFile(file); + + Intent extView = new Intent(Intent.ACTION_VIEW); + extView.setDataAndType(uri, mimeGuess); + try { + activity.startActivity(extView); + } catch (Exception ActivityNotFoundException) { + handled = false; + } + return handled; + } + + /** + * Called by FileSystem adapter to get the start folder + * for browsing directories + */ + public static File getFilesystemBrowseStart(Context context) { + SharedPreferences prefs = SharedPrefHelper.getSettings(context); + String folder = prefs.getString(PrefKeys.FILESYSTEM_BROWSE_START, PrefDefaults.FILESYSTEM_BROWSE_START); + + if (folder.equals("")) { + folder = Environment.getExternalStorageDirectory().getAbsolutePath(); + } + return new File(folder); + } + + /** + * Return the file extension for a given filename (including dot). + * Empty string is returned if there is no extension. + */ + public static String getFileExtension(String filename) { + int index = filename.lastIndexOf('.'); + return index > 0 ? filename.substring(index) : ""; + } + + /** + * Returns a list of directores contained in 'dir' which are very likely to exist, based + * on what Android told us about the existence of external media dirs. + * This is required as users otherwise may end up in folders they can not navigate out of. + */ + public static ArrayList<File> getFallbackDirectories(Context context, File dir) { + HashSet<File> result = new HashSet<>(); + + Path prefix = dir.toPath(); + for (File f : context.getExternalMediaDirs()) { + Path p = f.toPath(); + if (p.getNameCount() <= prefix.getNameCount()) + continue; + if (!p.startsWith(prefix)) + continue; + Path sp = p.subpath(prefix.getNameCount(), prefix.getNameCount()+1); + result.add(new File(dir, sp.toString())); + } + return new ArrayList<File>(result); + } + + /** + * Returns the ID which the media library uses for a file. + * + * @param the file to get the id for. + * @return the id this file would have in the library. + */ + public static long songIdFromFile(File file) { + return MediaLibrary.hash63(file.getAbsolutePath()); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FilebrowserStartActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FilebrowserStartActivity.java new file mode 100644 index 0000000..50c2fa5 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FilebrowserStartActivity.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.os.Bundle; +import android.content.SharedPreferences; + +import java.io.File; +import java.util.ArrayList; + +public class FilebrowserStartActivity extends FolderPickerActivity { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setTitle(R.string.filebrowser_start); + + // Make sure that we display the current selection + File startPath = FileUtils.getFilesystemBrowseStart(this); + setCurrentDir(startPath); + } + + + @Override + public void onFolderPicked(File directory, ArrayList<String> a, ArrayList<String> b) { + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(this).edit(); + editor.putString(PrefKeys.FILESYSTEM_BROWSE_START, directory.getAbsolutePath()); + editor.apply(); + finish(); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FolderPickerActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FolderPickerActivity.java new file mode 100644 index 0000000..b8e3773 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FolderPickerActivity.java @@ -0,0 +1,330 @@ +/* + * Copyright (C) 2013-2020 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import java.util.ArrayList; +import java.io.File; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.View; +import android.view.MenuItem; +import android.view.Menu; +import android.widget.AdapterView; +import android.widget.Button; +import android.widget.ListView; +import android.widget.EditText; +import android.widget.Toast; +import android.widget.Spinner; + +import com.mobeta.android.dslv.DragSortListView; + + +public abstract class FolderPickerActivity extends Activity + implements AdapterView.OnItemClickListener, + AdapterView.OnItemLongClickListener, + AdapterView.OnItemSelectedListener +{ + + /** + * Our listview + */ + private DragSortListView mListView; + /** + * View displaying the current path + */ + private EditText mPathDisplay; + /** + * Save button + */ + private Button mSaveButton; + /** + * Tristate spinner + */ + private Spinner mSpinner; + /** + * The array adapter of our listview + */ + private FolderPickerAdapter mListAdapter; + + @Override + public void onCreate(Bundle savedInstanceState) { + ThemeHelper.setTheme(this, R.style.BackActionBar); + super.onCreate(savedInstanceState); + + setContentView(R.layout.folderpicker_content); + + mListAdapter = new FolderPickerAdapter(this, 0); + mListView = (DragSortListView)findViewById(R.id.list); + mPathDisplay = (EditText) findViewById(R.id.path_display); + mSaveButton = (Button) findViewById(R.id.save_button); + mSpinner = (Spinner) findViewById(R.id.folder_picker_spinner); + + mListView.setAdapter(mListAdapter); + mListView.setOnItemClickListener(this); + + mPathDisplay.addTextChangedListener(mTextWatcher); + mSaveButton.setOnClickListener(mSaveButtonClickListener); + + mSpinner.setSelection(0); + mSpinner.setOnItemSelectedListener(this); + + // init defaults + enableTritasticSelect(false, null, null); + enableTritasticSpinner(false); + } + + /** + * Callback for Save button click events + */ + private final View.OnClickListener mSaveButtonClickListener = new View.OnClickListener() { + public void onClick(View v) { + onFolderPicked(mListAdapter.getCurrentDir(), + mListAdapter.getIncludedDirs(), + mListAdapter.getExcludedDirs()); + } + }; + + /** + * Callback for EditText change events + */ + private final TextWatcher mTextWatcher = new TextWatcher() { + @Override + public void afterTextChanged(Editable s) { + final File dir = new File(s.toString()); + setCurrentDir(dir); + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + }; + + /** + * Called after a folder was selected + * + * @param directory the selected directory + * @param included unique list of included directories in tristastic mode + * @param excluded unique list of excluded directories in triatastic mode + */ + public abstract void onFolderPicked(File directory, ArrayList<String> included, ArrayList<String> excluded); + + /** + * Enables tritastic selection, that is: user can select each + * directory to be in included, excluded or neutral state. + * + * @param enabled enables or disables this feature + * @param included initial list of included dirs + * @param excluded initial list of excluded dirs + */ + public void enableTritasticSelect(boolean enabled, ArrayList<String> included, ArrayList<String> excluded) { + if (enabled) { + Toast.makeText(this, R.string.hint_long_press_to_modify_folder, Toast.LENGTH_SHORT).show(); + mListAdapter.setIncludedDirs(included); + mListAdapter.setExcludedDirs(excluded); + } + mListView.setOnItemLongClickListener(enabled ? this : null); + mSaveButton.setText(enabled ? R.string.save : R.string.select); + } + + /** + * Whether or not to enable the tristate spinner. + */ + public void enableTritasticSpinner(boolean enabled) { + View view = findViewById(R.id.folder_picker_spinner_container); + view.setVisibility(enabled ? View.VISIBLE : View.GONE); + } + + /** + * Jumps to given directory + * + * @param dir the directory to jump to + */ + void setCurrentDir(File dir) { + mSaveButton.setEnabled(dir.isDirectory()); + mSpinner.setEnabled(dir.isDirectory()); + mListAdapter.setCurrentDir(dir); + mListView.setSelectionFromTop(0, 0); + + final File labelDir = new File(mPathDisplay.getText().toString()); + if (!dir.equals(labelDir)) { + // Only update the text field if the actual dir doesn't equal + // the currently displayed path, even if the text isn't exactly + // the same. We do this to avoid 'jumps' where we would replace + // '/storage/x/' with '/storage/x'. + final String label = dir.getAbsolutePath(); + mPathDisplay.setText(label); + mPathDisplay.setSelection(label.length()); + + // Since the folder changed, also update the spinner state. + if (mListAdapter.getIncludedDirs().contains(label)) { + mSpinner.setSelection(0); + } else if (mListAdapter.getExcludedDirs().contains(label)) { + mSpinner.setSelection(1); + } else { + mSpinner.setSelection(2); + } + } + } + + /** + * Create a bare-bones actionbar + */ + @Override + public boolean onCreateOptionsMenu(Menu menu) { + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) + { + if (item.getItemId() == android.R.id.home) { + finish(); + return true; + } else { + return super.onOptionsItemSelected(item); + } + } + + /** + * Called if user interacts with the spinner. + */ + @Override + public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { + FolderState state = FolderState.NEUTRAL; + switch(position) { + case 0: + state = FolderState.INCLUDE; + break; + case 1: + state = FolderState.EXCLUDE; + break; + } + setFolderState(mListAdapter.getCurrentDir().getAbsolutePath(), state); + } + + /** + * Called if user dismisses the spinner. + */ + @Override + public void onNothingSelected(AdapterView<?> parent) { + // noop. + } + + /** + * Called if user taps a row + */ + @Override + public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { + FolderPickerAdapter.Item item = mListAdapter.getItem(pos); + File curPath = mListAdapter.getCurrentDir(); + File newPath = null; + + if(item.file == null) { + // This is the '..' entry + newPath = curPath.getParentFile(); + } + else { + newPath = new File(curPath, item.name); + } + + if (newPath != null) + setCurrentDir(newPath); + } + + /** + * Called on long-click on a row + */ + @Override + public boolean onItemLongClick(AdapterView<?> parent, View view, int pos, long id) { + FolderPickerAdapter.Item item = mListAdapter.getItem(pos); + + if (item.file == null) + return false; + + final String path = item.file.getAbsolutePath(); + final CharSequence[] options = new CharSequence[]{ + getResources().getString(R.string.folder_include), + getResources().getString(R.string.folder_exclude), + getResources().getString(R.string.folder_neutral) + }; + + AlertDialog.Builder builder = new AlertDialog.Builder(this) + .setTitle(item.name) + .setItems(options, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case 0: + setFolderState(path, FolderState.INCLUDE); + break; + case 1: + setFolderState(path, FolderState.EXCLUDE); + break; + default: + setFolderState(path, FolderState.NEUTRAL); + } + } + }); + builder.create().show(); + return true; + } + + /** + * Enums to pass to setFolderState() + */ + enum FolderState { + NEUTRAL, + INCLUDE, + EXCLUDE, + } + + /** + * update included/excluded folders on the adapter. + * + * @param folder the folder to act on. + * @param state the state the passed in folder should have. + */ + private void setFolderState(String folder, FolderState state) { + ArrayList<String> includedDirs = mListAdapter.getIncludedDirs(); + ArrayList<String> excludedDirs = mListAdapter.getExcludedDirs(); + includedDirs.remove(folder); + excludedDirs.remove(folder); + switch (state) { + case INCLUDE: + includedDirs.add(folder); + break; + case EXCLUDE: + excludedDirs.add(folder); + break; + case NEUTRAL: + // noop. + break; + } + + mListAdapter.setIncludedDirs(includedDirs); + mListAdapter.setExcludedDirs(excludedDirs); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FolderPickerAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FolderPickerAdapter.java new file mode 100644 index 0000000..02671a3 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FolderPickerAdapter.java @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2013-2021 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.app.Activity; +import android.os.Environment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.LayoutInflater; +import android.widget.ArrayAdapter; +import android.widget.TextView; +import android.widget.ImageView; +import android.graphics.drawable.Drawable; + +import java.io.File; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + + +public class FolderPickerAdapter + extends ArrayAdapter<FolderPickerAdapter.Item> +{ + + public static class Item { + String name; + File file; + int color; + public Item(String name, File file, int color) { + this.name = name; + this.file = file; + this.color = color; + } + } + + /** + * The context we run in. + */ + private Context mContext; + /** + * Our layout inflater instance + */ + private final LayoutInflater mInflater; + /** + * The filesystem root + */ + final private File mFsRoot = new File("/"); + /** + * The currently set directory + */ + private File mCurrentDir; + /** + * A list of paths marked as 'included' + */ + private ArrayList<String> mIncludedDirs = new ArrayList<String>(); + /** + * A list of paths marked as 'excluded' + */ + private ArrayList<String> mExcludedDirs = new ArrayList<String>(); + + + public FolderPickerAdapter(Context context, int resource) { + super(context, resource); + mContext = context; + mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + mCurrentDir = Environment.getExternalStorageDirectory(); + } + + @Override + public View getView(int pos, View convertView, ViewGroup parent) { + DraggableRow row; + + if (convertView == null) { + row = (DraggableRow)mInflater.inflate(R.layout.draggable_row, parent, false); + row.setupLayout(DraggableRow.LAYOUT_LISTVIEW); + row.getCoverView().setImageResource(R.drawable.folder); + + } else { + row = (DraggableRow)convertView; + } + + Item item = (Item)getItem(pos); + int res = (item.file == null ? R.drawable.arrow_up : R.drawable.folder); + row.setText(item.name); + row.getCoverView().setImageResource(res); + row.getCoverView().setColorFilter(item.color); + return row; + } + + /** + * Returns the currently set directory + */ + public File getCurrentDir() { + return mCurrentDir; + } + + /** + * Changes the currently active directory + */ + public void setCurrentDir(File dir) { + mCurrentDir = dir; + refresh(); + } + + /** + * Returns the list of included directories + * + * @return arraylist - may be null + */ + public ArrayList<String> getIncludedDirs() { + return mIncludedDirs; + } + + /** + * Sets the included dirlist + * + * @param list the arraylist to use + */ + public void setIncludedDirs(ArrayList<String> list) { + mIncludedDirs = verifyDirs(list); + refresh(); + } + + /** + * Returns the list of excluded directories + * + * @return arraylist - may be null + */ + public ArrayList<String> getExcludedDirs() { + return mExcludedDirs; + } + + /** + * Sets the excluded dirlist + * + * @param list the arraylist to use + */ + public void setExcludedDirs(ArrayList<String> list) { + mExcludedDirs = verifyDirs(list); + refresh(); + } + + /** + * Returns list, weeding out non-existing or invalid dirs + * + * @param list the list to check + * @return list the checked list + */ + private ArrayList<String> verifyDirs(ArrayList<String> list) { + ArrayList<String> result = new ArrayList<String>(); + for (String path : list) { + File file = new File(path); + if (file.isDirectory()) + result.add(path); + } + return result; + } + + /** + * Refreshes the current ArrayList + */ + private void refresh() { + File path = mCurrentDir; + + clear(); + + if (!mFsRoot.equals(path)) + add(new FolderPickerAdapter.Item("..", null, 0)); + + List<File> dirs; + File []l = path.listFiles(); + if (l != null) { + dirs = Arrays.asList(l); + } else { + dirs = FileUtils.getFallbackDirectories(mContext, path); + } + + Collections.sort(dirs); + for(File fentry: dirs) { + if(fentry.isDirectory()) { + int color = 0; + if (mIncludedDirs.contains(fentry.getAbsolutePath())) + color = 0xff00c853; + if (mExcludedDirs.contains(fentry.getAbsolutePath())) + color = 0xffd50000; + Item item = new Item(fentry.getName(), fentry, color); + add(item); + } + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FourLongWidget.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FourLongWidget.java new file mode 100644 index 0000000..bbc88d5 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FourLongWidget.java @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.view.View; +import android.widget.RemoteViews; + +/** + * 1x4 widget that shows title, artist, album art, a play/pause button, and a + * next button. + */ +public class FourLongWidget extends AppWidgetProvider { + private static boolean sEnabled; + + @Override + public void onEnabled(Context context) + { + sEnabled = true; + } + + @Override + public void onDisabled(Context context) + { + sEnabled = false; + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) + { + Song song = null; + int state = 0; + + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + song = service.getSong(0); + state = service.getState(); + } + + sEnabled = true; + updateWidget(context, manager, song, state); + } + + /** + * Check if there are any instances of this widget placed. + */ + public static void checkEnabled(Context context, AppWidgetManager manager) + { + sEnabled = manager.getAppWidgetIds(new ComponentName(context, FourLongWidget.class)).length != 0; + } + + /** + * Populate the widgets with the given ids with the given info. + * + * @param context A Context to use. + * @param manager The AppWidgetManager that will be used to update the + * widget. + * @param song The current Song in PlaybackService. + * @param state The current PlaybackService state. + */ + public static void updateWidget(Context context, AppWidgetManager manager, Song song, int state) + { + if (!sEnabled) + return; + + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.four_long_widget); + + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + views.setViewVisibility(R.id.play_pause, View.GONE); + views.setViewVisibility(R.id.next, View.GONE); + views.setViewVisibility(R.id.title, View.GONE); + views.setInt(R.id.artist, "setText", R.string.no_songs); + views.setViewVisibility(R.id.album, View.GONE); + } else if (song == null) { + views.setViewVisibility(R.id.play_pause, View.VISIBLE); + views.setViewVisibility(R.id.next, View.VISIBLE); + views.setViewVisibility(R.id.title, View.GONE); + views.setInt(R.id.artist, "setText", R.string.app_name); + views.setViewVisibility(R.id.album, View.GONE); + } else { + views.setViewVisibility(R.id.play_pause, View.VISIBLE); + views.setViewVisibility(R.id.next, View.VISIBLE); + views.setViewVisibility(R.id.title, View.VISIBLE); + views.setViewVisibility(R.id.album, View.VISIBLE); + views.setTextViewText(R.id.title, song.title); + views.setTextViewText(R.id.artist, song.artist); + views.setTextViewText(R.id.album, song.album); + Bitmap cover = song.getMediumCover(context); + if (cover == null) { + views.setImageViewResource(R.id.cover, R.drawable.fallback_cover_large); + } else { + views.setImageViewBitmap(R.id.cover, cover); + } + } + + boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + views.setImageViewResource(R.id.play_pause, playing ? R.drawable.pause : R.drawable.play); + + Intent intent; + PendingIntent pendingIntent; + int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + intent = new Intent(context, LibraryActivity.class).setAction(Intent.ACTION_MAIN); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.cover, pendingIntent); + views.setOnClickPendingIntent(R.id.text_layout, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_TOGGLE_PLAYBACK); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.play_pause, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_NEXT_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.next, pendingIntent); + + manager.updateAppWidget(new ComponentName(context, FourLongWidget.class), views); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FourSquareWidget.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FourSquareWidget.java new file mode 100644 index 0000000..7e85fab --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FourSquareWidget.java @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.view.View; +import android.widget.RemoteViews; + +/** + * 2x2 widget that shows title, artist, a (hidden) play/pause button, a (hidden) + * next button, and cover art in the background. + */ +public class FourSquareWidget extends AppWidgetProvider { + private static boolean sEnabled; + + @Override + public void onEnabled(Context context) + { + sEnabled = true; + } + + @Override + public void onDisabled(Context context) + { + sEnabled = false; + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) + { + Song song = null; + int state = 0; + + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + song = service.getSong(0); + state = service.getState(); + } + + sEnabled = true; + updateWidget(context, manager, song, state); + } + + /** + * Check if there are any instances of this widget placed. + */ + public static void checkEnabled(Context context, AppWidgetManager manager) + { + sEnabled = manager.getAppWidgetIds(new ComponentName(context, FourSquareWidget.class)).length != 0; + } + + /** + * Populate the widgets with the given ids with the given info. + * + * @param context A Context to use. + * @param manager The AppWidgetManager that will be used to update the + * widget. + * @param song The current Song in PlaybackService. + * @param state The current PlaybackService state. + */ + public static void updateWidget(Context context, AppWidgetManager manager, Song song, int state) + { + if (!sEnabled) + return; + + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.four_square_widget); + + boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + int playResource = R.drawable.play; + int nextResource = R.drawable.next; + Bitmap cover = null; + + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + views.setViewVisibility(R.id.buttons, View.INVISIBLE); + views.setViewVisibility(R.id.title, View.INVISIBLE); + views.setInt(R.id.artist, "setText", R.string.no_songs); + } else if (song == null) { + views.setViewVisibility(R.id.buttons, View.VISIBLE); + views.setViewVisibility(R.id.title, View.INVISIBLE); + views.setInt(R.id.artist, "setText", R.string.app_name); + } else { + views.setViewVisibility(R.id.title, View.VISIBLE); + views.setViewVisibility(R.id.buttons, View.VISIBLE); + views.setTextViewText(R.id.title, song.title); + views.setTextViewText(R.id.artist, song.artist); + cover = song.getMediumCover(context); + playResource = playing ? R.drawable.hidden_pause : R.drawable.hidden_play; + nextResource = R.drawable.hidden_next; + } + + views.setImageViewResource(R.id.play_pause, playResource); + views.setImageViewResource(R.id.next, nextResource); + + if (cover == null) { + views.setImageViewResource(R.id.cover, R.drawable.fallback_cover_large); + } else { + views.setImageViewBitmap(R.id.cover, cover); + } + + + Intent intent; + PendingIntent pendingIntent; + int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + intent = new Intent(context, LibraryActivity.class).setAction(Intent.ACTION_MAIN); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.title, pendingIntent); + views.setOnClickPendingIntent(R.id.artist, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_TOGGLE_PLAYBACK); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.play_pause, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_NEXT_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.next, pendingIntent); + + manager.updateAppWidget(new ComponentName(context, FourSquareWidget.class), views); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FourWhiteWidget.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FourWhiteWidget.java new file mode 100644 index 0000000..edbd565 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FourWhiteWidget.java @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2012 Ferenc Nagy <nferenc@nferenc.com> + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.view.View; +import android.widget.RemoteViews; + +/** + * 1x4 widget that shows title, artist, album art, a play/pause button, and a + * previous/next button. + */ +public class FourWhiteWidget extends AppWidgetProvider { + private static boolean sEnabled; + + @Override + public void onEnabled(Context context) + { + sEnabled = true; + } + + @Override + public void onDisabled(Context context) + { + sEnabled = false; + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) + { + Song song = null; + int state = 0; + + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + song = service.getSong(0); + state = service.getState(); + } + + sEnabled = true; + updateWidget(context, manager, song, state); + } + + /** + * Check if there are any instances of this widget placed. + */ + public static void checkEnabled(Context context, AppWidgetManager manager) + { + sEnabled = manager.getAppWidgetIds(new ComponentName(context, FourWhiteWidget.class)).length != 0; + } + + /** + * Populate the widgets with the given ids with the given info. + * + * @param context A Context to use. + * @param manager The AppWidgetManager that will be used to update the + * widget. + * @param song The current Song in PlaybackService. + * @param state The current PlaybackService state. + */ + public static void updateWidget(Context context, AppWidgetManager manager, Song song, int state) + { + if (!sEnabled) + return; + + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.four_white_widget); + + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + views.setViewVisibility(R.id.play_pause, View.INVISIBLE); + views.setViewVisibility(R.id.previous, View.INVISIBLE); + views.setViewVisibility(R.id.next, View.INVISIBLE); + views.setViewVisibility(R.id.title, View.INVISIBLE); + views.setInt(R.id.artist, "setText", R.string.no_songs); + views.setViewVisibility(R.id.cover, View.INVISIBLE); + } else if (song == null) { + views.setViewVisibility(R.id.play_pause, View.VISIBLE); + views.setViewVisibility(R.id.previous, View.VISIBLE); + views.setViewVisibility(R.id.next, View.VISIBLE); + views.setViewVisibility(R.id.title, View.INVISIBLE); + views.setInt(R.id.artist, "setText", R.string.app_name); + views.setViewVisibility(R.id.cover, View.INVISIBLE); + } else { + views.setViewVisibility(R.id.play_pause, View.VISIBLE); + views.setViewVisibility(R.id.previous, View.VISIBLE); + views.setViewVisibility(R.id.next, View.VISIBLE); + views.setViewVisibility(R.id.title, View.VISIBLE); + views.setTextViewText(R.id.title, song.title); + views.setTextViewText(R.id.artist, song.artist); + Bitmap cover = song.getMediumCover(context); + if (cover == null) { + views.setViewVisibility(R.id.cover, View.INVISIBLE); + } else { + // Ensure that the cover is not longer than its height - we can deal with non-square images + // if the reverse is true, but w > h messes up the layout. + if (cover.getWidth() > cover.getHeight()) + cover = Bitmap.createScaledBitmap(cover, cover.getHeight(), cover.getHeight(), true); + views.setImageViewBitmap(R.id.cover, cover); + views.setViewVisibility(R.id.cover, View.VISIBLE); + } + } + + boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + views.setImageViewResource(R.id.play_pause, playing ? R.drawable.widget_pause : R.drawable.widget_play); + + Intent intent; + PendingIntent pendingIntent; + int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + intent = new Intent(context, LibraryActivity.class).setAction(Intent.ACTION_MAIN); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.coverFrame, pendingIntent); + views.setOnClickPendingIntent(R.id.text_layout, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_TOGGLE_PLAYBACK); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.play_pause, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_NEXT_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.next, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_PREVIOUS_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.previous, pendingIntent); + + manager.updateAppWidget(new ComponentName(context, FourWhiteWidget.class), views); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/FullPlaybackActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/FullPlaybackActivity.java new file mode 100644 index 0000000..2b8586a --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/FullPlaybackActivity.java @@ -0,0 +1,684 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2016-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaMetadataExtractor; + +import java.util.ArrayList; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.Message; +import android.util.Log; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.SubMenu; +import android.view.View; +import android.view.ViewGroup; +import android.widget.LinearLayout; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; +import android.app.AlertDialog; +import android.content.DialogInterface; + +/** + * The primary playback screen with playback controls and large cover display. + */ +public class FullPlaybackActivity extends SlidingPlaybackActivity + implements View.OnLongClickListener +{ + public static final int DISPLAY_INFO_OVERLAP = 0; + public static final int DISPLAY_INFO_BELOW = 1; + public static final int DISPLAY_INFO_WIDGETS = 2; + + private TextView mOverlayText; + + private TableLayout mInfoTable; + private TextView mQueuePosView; + + private TextView mTitle; + private TextView mAlbum; + private TextView mArtist; + + /** + * True if the controls are visible (play, next, seek bar, etc). + */ + private boolean mControlsVisible; + /** + * True if the extra info is visible. + */ + private boolean mExtraInfoVisible; + + /** + * The current display mode, which determines layout and cover render style. + */ + private int mDisplayMode; + + private Action mCoverPressAction; + private Action mCoverLongPressAction; + + /** + * The currently playing song. + */ + private Song mCurrentSong; + + private String mGenre; + private TextView mGenreView; + private String mTrack; + private TextView mTrackView; + private String mYear; + private TextView mYearView; + private String mComposer; + private TextView mComposerView; + private String mPath; + private TextView mPathView; + private String mFormat; + private TextView mFormatView; + private String mReplayGain; + private TextView mReplayGainView; + private MenuItem mFavorites; + + @Override + public void onCreate(Bundle icicle) + { + ThemeHelper.setTheme(this, R.style.Playback); + super.onCreate(icicle); + + setTitle(R.string.playback_view); + + SharedPreferences settings = SharedPrefHelper.getSettings(this); + int displayMode = Integer.parseInt(settings.getString(PrefKeys.DISPLAY_MODE, PrefDefaults.DISPLAY_MODE)); + mDisplayMode = displayMode; + + int layout = R.layout.full_playback; + int coverStyle; + + switch (displayMode) { + default: + Log.w("VanillaMusic", "Invalid display mode given. Defaulting to widget mode."); + // fall through + case DISPLAY_INFO_WIDGETS: + coverStyle = CoverBitmap.STYLE_NO_INFO; + layout = R.layout.full_playback_alt; + break; + case DISPLAY_INFO_OVERLAP: + coverStyle = CoverBitmap.STYLE_OVERLAPPING_BOX; + break; + case DISPLAY_INFO_BELOW: + coverStyle = CoverBitmap.STYLE_INFO_BELOW; + break; + } + + setContentView(layout); + + CoverView coverView = (CoverView)findViewById(R.id.cover_view); + coverView.setup(mLooper, this, coverStyle); + coverView.setOnClickListener(this); + coverView.setOnLongClickListener(this); + mCoverView = coverView; + + TableLayout table = (TableLayout)findViewById(R.id.info_table); + if (table != null) { + table.setOnClickListener(this); + table.setOnLongClickListener(this); + mInfoTable = table; + } + + mTitle = (TextView)findViewById(R.id.title); + mAlbum = (TextView)findViewById(R.id.album); + mArtist = (TextView)findViewById(R.id.artist); + + mQueuePosView = (TextView)findViewById(R.id.queue_pos); + + mGenreView = (TextView)findViewById(R.id.genre); + mTrackView = (TextView)findViewById(R.id.track); + mYearView = (TextView)findViewById(R.id.year); + mComposerView = (TextView)findViewById(R.id.composer); + mPathView = (TextView)findViewById(R.id.path); + mFormatView = (TextView)findViewById(R.id.format); + mReplayGainView = (TextView)findViewById(R.id.replaygain); + + bindControlButtons(); + + setControlsVisible(settings.getBoolean(PrefKeys.VISIBLE_CONTROLS, PrefDefaults.VISIBLE_CONTROLS)); + setExtraInfoVisible(settings.getBoolean(PrefKeys.VISIBLE_EXTRA_INFO, PrefDefaults.VISIBLE_EXTRA_INFO)); + } + + @Override + public void onStart() + { + super.onStart(); + + SharedPreferences settings = SharedPrefHelper.getSettings(this); + if (mDisplayMode != Integer.parseInt(settings.getString(PrefKeys.DISPLAY_MODE, PrefDefaults.DISPLAY_MODE))) { + finish(); + startActivity(new Intent(this, FullPlaybackActivity.class)); + } + + mCoverPressAction = Action.getAction(settings, PrefKeys.COVER_PRESS_ACTION, PrefDefaults.COVER_PRESS_ACTION); + mCoverLongPressAction = Action.getAction(settings, PrefKeys.COVER_LONGPRESS_ACTION, PrefDefaults.COVER_LONGPRESS_ACTION); + } + + /** + * Hide the message overlay, if it exists. + */ + private void hideMessageOverlay() + { + if (mOverlayText != null) + mOverlayText.setVisibility(View.GONE); + } + + /** + * Show some text in a message overlay. + * + * @param text Resource id of the text to show. + */ + private void showOverlayMessage(int text) + { + if (mOverlayText == null) { + TextView view = new TextView(this); + // This will be drawn on top of all other controls, so we flood this view + // with a non-alpha color + view.setBackgroundColor(ThemeHelper.fetchThemeColor(this, android.R.attr.colorBackground)); + view.setGravity(Gravity.CENTER); + view.setPadding(25, 25, 25, 25); + // Make the view clickable so it eats touch events + view.setClickable(true); + view.setOnClickListener(this); + addContentView(view, + new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT)); + mOverlayText = view; + } else { + mOverlayText.setVisibility(View.VISIBLE); + } + + mOverlayText.setText(text); + } + + @Override + protected void onStateChange(int state, int toggled) + { + super.onStateChange(state, toggled); + + if ((toggled & (PlaybackService.FLAG_NO_MEDIA|PlaybackService.FLAG_EMPTY_QUEUE)) != 0) { + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + showOverlayMessage(R.string.no_songs); + } else if ((state & PlaybackService.FLAG_EMPTY_QUEUE) != 0) { + showOverlayMessage(R.string.empty_queue); + } else { + hideMessageOverlay(); + } + } + + if (mQueuePosView != null) + updateQueuePosition(); + } + + @Override + protected void onSongChange(Song song) { + if (mTitle != null) { + if (song == null) { + mTitle.setText(null); + mAlbum.setText(null); + mArtist.setText(null); + } else { + mTitle.setText(song.title); + mAlbum.setText(song.album); + mArtist.setText(song.artist); + } + updateQueuePosition(); + } + + mCurrentSong = song; + + mHandler.sendEmptyMessage(MSG_LOAD_FAVOURITE_INFO); + + // All quick UI updates are done: Time to update the cover + // and parse additional info + if (mExtraInfoVisible) { + mHandler.sendEmptyMessage(MSG_LOAD_EXTRA_INFO); + } + super.onSongChange(song); + } + + /** + * Update the queue position display. mQueuePos must not be null. + */ + private void updateQueuePosition() + { + if (PlaybackService.finishAction(mState) == SongTimeline.FINISH_RANDOM) { + // Not very useful in random mode; it will always show something + // like 11/13 since the timeline is trimmed to 10 previous songs. + // So just hide it. + mQueuePosView.setText(null); + } else { + PlaybackService service = PlaybackService.get(this); + mQueuePosView.setText((service.getTimelinePosition() + 1) + "/" + service.getTimelineLength()); + } + mQueuePosView.requestLayout(); // ensure queue pos column has enough room + } + + @Override + public void onPositionInfoChanged() + { + if (mQueuePosView != null) + mUiHandler.sendEmptyMessage(MSG_UPDATE_POSITION); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) + { + super.onCreateOptionsMenu(menu); + menu.add(0, MENU_DELETE, 30, R.string.delete); + SubMenu enqueueMenu = menu.addSubMenu(0, MENU_ENQUEUE, 30, R.string.enqueue_current); + SubMenu moreMenu = menu.addSubMenu(0, MENU_MORE, 30, R.string.more_from_current); + menu.addSubMenu(0, MENU_ADD_TO_PLAYLIST, 30, R.string.add_to_playlist); + menu.add(0, MENU_SHARE, 30, R.string.share); + + if (PluginUtils.checkPlugins(this)) { + menu.add(0, MENU_PLUGINS, 30, R.string.plugins) + .setIcon(R.drawable.plugin) + .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM); + } + + mFavorites = menu.add(0, MENU_SONG_FAVORITE, 0, R.string.add_to_favorites) + .setIcon(R.drawable.btn_rating_star_off_mtrl_alpha) + .setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM); + + // Subitems of 'enqueue...' + enqueueMenu.add(0, MENU_ENQUEUE_ALBUM, 30, R.string.album); + enqueueMenu.add(0, MENU_ENQUEUE_ARTIST, 30, R.string.artist); + enqueueMenu.add(0, MENU_ENQUEUE_GENRE, 30, R.string.genre); + + // Subitems of 'more from...' + moreMenu.add(0, MENU_MORE_ALBUM, 30, R.string.album); + moreMenu.add(0, MENU_MORE_ARTIST, 30, R.string.artist); + moreMenu.add(0, MENU_MORE_GENRE, 30, R.string.genre); + moreMenu.add(0, MENU_MORE_FOLDER, 30, R.string.folder); + + // ensure that mFavorites is updated + mHandler.sendEmptyMessage(MSG_LOAD_FAVOURITE_INFO); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) + { + final Song song = mCurrentSong; + + switch (item.getItemId()) { + case android.R.id.home: + openLibrary(null, -1); + break; + case MENU_MORE_ALBUM: + openLibrary(song, MediaUtils.TYPE_ALBUM); + break; + case MENU_MORE_ARTIST: + openLibrary(song, MediaUtils.TYPE_ARTIST); + break; + case MENU_MORE_GENRE: + openLibrary(song, MediaUtils.TYPE_GENRE); + break; + case MENU_MORE_FOLDER: + openLibrary(song, MediaUtils.TYPE_FILE); + break; + case MENU_ENQUEUE_ALBUM: + PlaybackService.get(this).enqueueFromSong(song, MediaUtils.TYPE_ALBUM); + break; + case MENU_ENQUEUE_ARTIST: + PlaybackService.get(this).enqueueFromSong(song, MediaUtils.TYPE_ARTIST); + break; + case MENU_ENQUEUE_GENRE: + PlaybackService.get(this).enqueueFromSong(song, MediaUtils.TYPE_GENRE); + break; + case MENU_SONG_FAVORITE: + long playlistId = Playlist.getFavoritesId(this, true); + if (song != null) { + PlaylistTask playlistTask = new PlaylistTask(playlistId, getString(R.string.playlist_favorites)); + playlistTask.audioIds = new ArrayList<Long>(); + playlistTask.audioIds.add(song.id); + int action = Playlist.isInPlaylist(this, playlistId, song) ? MSG_REMOVE_FROM_PLAYLIST : MSG_ADD_TO_PLAYLIST; + mHandler.sendMessage(mHandler.obtainMessage(action, playlistTask)); + } + break; + case MENU_ADD_TO_PLAYLIST: + if (song != null) { + Intent intent = new Intent(); + intent.putExtra("type", MediaUtils.TYPE_SONG); + intent.putExtra("id", song.id); + PlaylistDialog dialog = PlaylistDialog.newInstance(this, intent, null, song); + dialog.show(getFragmentManager(), "PlaylistDialog"); + } + break; + case MENU_SHARE: + if (song != null) + MediaUtils.shareMedia(this, song); + break; + case MENU_DELETE: + final PlaybackService playbackService = PlaybackService.get(this); + final PlaybackActivity activity = this; + + if (song != null) { + String delete_message = getString(R.string.delete_file, song.title); + AlertDialog.Builder dialog = new AlertDialog.Builder(this); + dialog.setTitle(R.string.delete); + dialog + .setMessage(delete_message) + .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + // MSG_DELETE expects an intent (usually called from listview) + Intent intent = new Intent(); + intent.putExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_SONG); + intent.putExtra(LibraryAdapter.DATA_ID, song.id); + mHandler.sendMessage(mHandler.obtainMessage(MSG_DELETE, intent)); + } + }) + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + } + }); + dialog.create().show(); + } + break; + case MENU_PLUGINS: + if (song != null) { + Intent songIntent = new Intent(); + songIntent.putExtra("id", song.id); + showPluginMenu(songIntent); + } + break; + default: + return super.onOptionsItemSelected(item); + } + + return true; + } + + @Override + public boolean onSearchRequested() + { + openLibrary(null, -1); + return false; + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) + { + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_RIGHT: + shiftCurrentSong(SongTimeline.SHIFT_NEXT_SONG); + findViewById(R.id.next).requestFocus(); + break; + case KeyEvent.KEYCODE_DPAD_LEFT: + shiftCurrentSong(SongTimeline.SHIFT_PREVIOUS_SONG); + findViewById(R.id.previous).requestFocus(); + break; + case KeyEvent.KEYCODE_SEARCH: + Intent librarySearch = new Intent(this, LibraryActivity.class); + librarySearch.putExtra("launch_search", true); + startActivity(librarySearch); + break; + default: + return super.onKeyDown(keyCode, event); + } + return true; + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) + { + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_CENTER: + case KeyEvent.KEYCODE_ENTER: + setControlsVisible(!mControlsVisible); + mHandler.sendEmptyMessage(MSG_SAVE_CONTROLS); + return true; + case KeyEvent.KEYCODE_BACK: + if (mSlidingView.isShrinkable()) { + mSlidingView.hideSlide(); + return true; + } + } + + return super.onKeyUp(keyCode, event); + } + + /** + * Set the visibility of the controls views. + * + * @param visible True to show, false to hide + */ + private void setControlsVisible(boolean visible) + { + int mode = visible ? View.VISIBLE : View.GONE; + mSlidingView.setVisibility(mode); + mControlsVisible = visible; + + if (visible) { + mPlayPauseButton.requestFocus(); + } + } + + /** + * Set the visibility of the extra metadata view. + * + * @param visible True to show, false to hide + */ + private void setExtraInfoVisible(boolean visible) + { + TableLayout table = mInfoTable; + if (table == null) + return; + + table.setColumnCollapsed(0, !visible); + // Make title, album, and artist multi-line when extra info is visible + boolean singleLine = !visible; + for (int i = 0; i != 3; ++i) { + TableRow row = (TableRow)table.getChildAt(i); + ((TextView)row.getChildAt(1)).setSingleLine(singleLine); + } + // toggle visibility of all but the first three rows (the title/artist/ + // album rows) + int visibility = visible ? View.VISIBLE : View.GONE; + for (int i = table.getChildCount() - 1; i > 2 ; i--) { + table.getChildAt(i).setVisibility(visibility); + } + mExtraInfoVisible = visible; + if (visible && !mHandler.hasMessages(MSG_LOAD_EXTRA_INFO)) { + mHandler.sendEmptyMessage(MSG_LOAD_EXTRA_INFO); + } + } + + /** + * Retrieve the extra metadata for the current song. + */ + private void loadExtraInfo() + { + Song song = mCurrentSong; + + mGenre = null; + mTrack = null; + mYear = null; + mComposer = null; + mPath = null; + mFormat = null; + mReplayGain = null; + + if(song != null) { + MediaMetadataExtractor data = new MediaMetadataExtractor(song.path); + + mGenre = data.getFirst(MediaMetadataExtractor.GENRE); + mTrack = song.getTrackAndDiscNumber(); + mComposer = data.getFirst(MediaMetadataExtractor.COMPOSER); + mYear = data.getFirst(MediaMetadataExtractor.YEAR); + mPath = song.path; + + mFormat = data.getFormat(); + + BastpUtil.GainValues rg = PlaybackService.get(this).getReplayGainValues(song.path); + mReplayGain = String.format("found=%s, track=%.2f, album=%.2f", rg.found, rg.track, rg.album); + } + + mUiHandler.sendEmptyMessage(MSG_COMMIT_INFO); + } + + /** + * Save the hidden_controls preference to storage. + */ + private static final int MSG_SAVE_CONTROLS = 10; + /** + * Call {@link #loadExtraInfo()}. + */ + private static final int MSG_LOAD_EXTRA_INFO = 11; + /** + * Pass obj to mExtraInfo.setText() + */ + private static final int MSG_COMMIT_INFO = 12; + /** + * Calls {@link #updateQueuePosition()}. + */ + private static final int MSG_UPDATE_POSITION = 13; + /** + * Check if passed song is a favorite + */ + private static final int MSG_LOAD_FAVOURITE_INFO = 14; + /** + * Updates the favorites state + */ + private static final int MSG_COMMIT_FAVOURITE_INFO = 15; + + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_SAVE_CONTROLS: { + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(this).edit(); + editor.putBoolean(PrefKeys.VISIBLE_CONTROLS, mControlsVisible); + editor.putBoolean(PrefKeys.VISIBLE_EXTRA_INFO, mExtraInfoVisible); + editor.apply(); + break; + } + case MSG_LOAD_EXTRA_INFO: + loadExtraInfo(); + break; + case MSG_COMMIT_INFO: { + mGenreView.setText(mGenre); + mTrackView.setText(mTrack); + mYearView.setText(mYear); + mComposerView.setText(mComposer); + mPathView.setText(mPath); + mFormatView.setText(mFormat); + mReplayGainView.setText(mReplayGain); + break; + } + case MSG_UPDATE_POSITION: + updateQueuePosition(); + break; + case MSG_NOTIFY_PLAYLIST_CHANGED: // triggers a fav-refresh + case MSG_LOAD_FAVOURITE_INFO: + if (mCurrentSong != null) { + boolean found = Playlist.isInPlaylist(this, Playlist.getFavoritesId(this, false), mCurrentSong); + mUiHandler.sendMessage(mUiHandler.obtainMessage(MSG_COMMIT_FAVOURITE_INFO, found)); + } + break; + case MSG_COMMIT_FAVOURITE_INFO: + if (mFavorites != null) { + boolean found = (boolean)message.obj; + mFavorites.setIcon(found ? R.drawable.btn_rating_star_on_mtrl_alpha: R.drawable.btn_rating_star_off_mtrl_alpha); + mFavorites.setTitle(found ? R.string.remove_from_favorites : R.string.add_to_favorites); + } + break; + default: + return super.handleMessage(message); + } + + return true; + } + + @Override + protected void performAction(Action action) { + switch (action) { + case ToggleControls: + setControlsVisible(!mControlsVisible); + mHandler.sendEmptyMessage(MSG_SAVE_CONTROLS); + break; + case ShowQueue: + mSlidingView.expandSlide(); + break; + default: + super.performAction(action); + } + } + + @Override + public void onClick(View view) + { + if (view == mOverlayText && (mState & PlaybackService.FLAG_EMPTY_QUEUE) != 0) { + setState(PlaybackService.get(this).setFinishAction(SongTimeline.FINISH_RANDOM)); + } else if (view == mCoverView) { + performAction(mCoverPressAction); + } else if (view.getId() == R.id.info_table) { + openLibrary(mCurrentSong, MediaUtils.TYPE_ALBUM); + } else { + super.onClick(view); + } + } + + @Override + public boolean onLongClick(View view) + { + switch (view.getId()) { + case R.id.cover_view: + performAction(mCoverLongPressAction); + break; + case R.id.info_table: + setExtraInfoVisible(!mExtraInfoVisible); + mHandler.sendEmptyMessage(MSG_SAVE_CONTROLS); + break; + default: + return false; + } + + return true; + } + + @Override + public void onSlideExpansionChanged(int expansion) { + super.onSlideExpansionChanged(expansion); + + setControlsVisible(true); + if (expansion != SlidingView.EXPANSION_PARTIAL) { + setExtraInfoVisible(false); + } else { + SharedPreferences settings = SharedPrefHelper.getSettings(this); + setExtraInfoVisible(settings.getBoolean(PrefKeys.VISIBLE_EXTRA_INFO, PrefDefaults.VISIBLE_EXTRA_INFO)); + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/IdlePreference.java b/app/src/main/java/ch/blinkenlights/android/vanilla/IdlePreference.java new file mode 100644 index 0000000..58fc09d --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/IdlePreference.java @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +//import android.app.AlertDialog.Builder; +import android.content.Context; +import android.content.res.Resources; +import android.preference.DialogPreference; +import android.util.AttributeSet; +import android.view.View; +import android.widget.SeekBar; +import android.widget.TextView; + +/** + * A preference that provides a dialog with a slider for idle time. + * + * The slider produces a value in seconds from 60 (1 minute) to 21600 + * (6 hours). The values range on an approximately exponential scale. + */ +public class IdlePreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener { + private static final int DEFAULT_VALUE = 3600; + private static final int MIN = 60; + private static final int MAX = 21600; + + /** + * The current idle timeout displayed on the slider. Will not be persisted + * until the dialog is closed. + */ + private int mValue; + /** + * The view in which the value is displayed. + */ + private TextView mValueText; + + public IdlePreference(Context context, AttributeSet attrs) + { + super(context, attrs); + } + + @Override + public CharSequence getSummary() + { + return formatTime(getPersistedInt(DEFAULT_VALUE)); + } + + + @Override + protected View onCreateDialogView() + { + View view = super.onCreateDialogView(); + + mValue = getPersistedInt(DEFAULT_VALUE); + + mValueText = (TextView)view.findViewById(R.id.value); + + SeekBar seekBar = (SeekBar)view.findViewById(R.id.seek_bar); + seekBar.setMax(1000); + seekBar.setProgress((int)(Math.pow((float)(mValue - MIN) / (MAX - MIN), 0.25f) * 1000)); + seekBar.setOnSeekBarChangeListener(this); + + updateText(); + + return view; + } + + + /** + * Format seconds into a human-readable time description. + * + * @param value The time, in seconds. + * @return A human-readable string, such as "1 hour, 21 minutes" + */ + private String formatTime(int value) + { + Resources res = getContext().getResources(); + StringBuilder text = new StringBuilder(); + if (value >= 3600) { + int hours = value / 3600; + text.append(res.getQuantityString(R.plurals.hours, hours, hours)); + text.append(", "); + int minutes = value / 60 - hours * 60; + text.append(res.getQuantityString(R.plurals.minutes, minutes, minutes)); + } else { + int minutes = value / 60; + text.append(res.getQuantityString(R.plurals.minutes, minutes, minutes)); + text.append(", "); + int seconds = value - minutes * 60; + text.append(res.getQuantityString(R.plurals.seconds, seconds, seconds)); + } + return text.toString(); + } + + /** + * Update the text view with the current value. + */ + private void updateText() + { + mValueText.setText(formatTime(mValue)); + } + + @Override + protected void onDialogClosed(boolean positiveResult) + { + if (positiveResult && shouldPersist()) { + persistInt(mValue); + notifyChanged(); + } + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) + { + // Approximate an exponential curve with x^4. Produces a value from MIN-MAX. + if (fromUser) { + float value = seekBar.getProgress() / 1000.0f; + value *= value; + value *= value; + mValue = (int)(value * (MAX - MIN)) + MIN; + updateText(); + } + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) + { + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) + { + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/JumpToTimeDialog.java b/app/src/main/java/ch/blinkenlights/android/vanilla/JumpToTimeDialog.java new file mode 100644 index 0000000..2d77b7e --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/JumpToTimeDialog.java @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2018 Toby Hsieh + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.app.FragmentManager; +import android.content.DialogInterface; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.LayoutInflater; +import android.view.View; +import android.view.WindowManager; +import android.widget.EditText; +import android.widget.Toast; + +/** + * A dialog for the user to input a specific time to jump to for the current song + */ +public class JumpToTimeDialog extends DialogFragment implements DialogInterface.OnClickListener { + private EditText hoursView; + private EditText minutesView; + private EditText secondsView; + + /** + * Callback interface for an activity that shows JumpToTimeDialog + */ + public interface OnPositionSubmitListener { + /** + * Called when the user submits a position to jump/seek to for the current song. + * + * @param position position to seek/jump to in milliseconds + */ + void onPositionSubmit(int position); + } + + /** + * Creates and shows the dialog + * + * @param manager the FragmentManager to add the newly created dialog to + */ + public static void show(FragmentManager manager) { + new JumpToTimeDialog().show(manager, "JumpToTimeDialog"); + } + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + // Watcher that moves to the next EditText when 2 digits are inserted + TextWatcher textWatcher = new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + EditText editText = (EditText) getDialog().getCurrentFocus(); + if (editText.length() == 2) { + View view = editText.focusSearch(View.FOCUS_RIGHT); + if (view != null) { + view.requestFocus(); + } + } + } + + @Override + public void afterTextChanged(Editable s) { + } + }; + + View view = LayoutInflater.from(getActivity()).inflate(R.layout.duration_input, null); + hoursView = view.findViewById(R.id.hours); + hoursView.addTextChangedListener(textWatcher); + minutesView = view.findViewById(R.id.minutes); + minutesView.addTextChangedListener(textWatcher); + secondsView = view.findViewById(R.id.seconds); + secondsView.addTextChangedListener(textWatcher); + + Dialog dialog = new AlertDialog.Builder(getActivity()) + .setTitle(R.string.jump_to_time) + .setView(view) + .setPositiveButton(android.R.string.ok, this) + .setNegativeButton(android.R.string.cancel, null) + .create(); + hoursView.requestFocus(); + dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + return dialog; + } + + @Override + public void onClick(DialogInterface dialog, int which) { + if (which == DialogInterface.BUTTON_POSITIVE) { + Activity activity = getActivity(); + try { + int hours = parseInteger(hoursView.getText().toString()); + int minutes = parseInteger(minutesView.getText().toString()); + int seconds = parseInteger(secondsView.getText().toString()); + int position = (hours * 3600 + minutes * 60 + seconds) * 1000; + ((OnPositionSubmitListener) activity).onPositionSubmit(position); + } catch (NumberFormatException e) { + Toast.makeText(activity, R.string.error_invalid_position, Toast.LENGTH_SHORT).show(); + } + } + } + + /** + * Parses the given string as an integer. This returns 0 if the given string is empty. + * + * @param s the string to parse + * @return the integer result + */ + static int parseInteger(String s) { + if (s.length() == 0) { + return 0; + } + return Integer.parseInt(s); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/LazyCoverView.java b/app/src/main/java/ch/blinkenlights/android/vanilla/LazyCoverView.java new file mode 100644 index 0000000..e393eb3 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/LazyCoverView.java @@ -0,0 +1,236 @@ +/* + * Copyright (C) 2015-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.ActivityManager; +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.TransitionDrawable; +import android.graphics.drawable.BitmapDrawable; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Message; +import android.util.AttributeSet; +import android.util.LruCache; +import android.widget.ImageView; + +/** + * LazyCoverView implements a 'song-aware' ImageView + * + * View updates should be triggered via setCover(type, id) to + * instruct the view to load the cover from its own LRU cache. + * + * The cover will automatically be fetched & scaled in a background + * thread on cache miss + */ +public class LazyCoverView extends ImageView + implements Handler.Callback +{ + /** + * Context of constructor + */ + private Context mContext; + /** + * UI Thread handler + */ + private static Handler sUiHandler; + /** + * Worker thread handler + */ + private static Handler sHandler; + /** + * The fallback cover image resource encoded as bitmap + */ + private static Bitmap sFallbackBitmap; + /** + * Our private LRU cache + */ + private static BitmapLruCache sBitmapLruCache; + /** + * The cover key we are expected to draw + */ + private CoverCache.CoverKey mExpectedKey; + + /** + * Cover message we are passing around using mHandler + */ + private static class CoverMsg { + public CoverCache.CoverKey key; // A cache key identifying this RPC + public LazyCoverView view; // The view we are updating + public String title; // The title of this view, used for Initial-Covers + CoverMsg(CoverCache.CoverKey key, LazyCoverView view, String title) { + this.key = key; + this.view = view; + this.title = title; + } + /** + * Returns true if the view still requires updating + */ + public boolean isRecent() { + return this.key.equals(this.view.mExpectedKey); + } + } + + /** + * Constructor of class inflated from XML + * + * @param context The context of the calling activity + * @param attributes attributes passed by the xml inflater + */ + public LazyCoverView(Context context, AttributeSet attributes) { + super(context, attributes); + mContext = context; + if (sBitmapLruCache == null) { + ActivityManager am = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE); + int lruSize = am.getMemoryClass() / 10; // use ~10% for LRU + lruSize = lruSize < 2 ? 2 : lruSize; // LRU will always be at least 2MiB + sBitmapLruCache = new BitmapLruCache(lruSize*1024*1024); + } + if (sFallbackBitmap == null) { + sFallbackBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover); + } + if (sUiHandler == null) { + sUiHandler = new Handler(this); + } + if (sHandler == null) { + HandlerThread thread = new HandlerThread("LazyCoverRpc"); + thread.start(); + sHandler = new Handler(thread.getLooper(), this); + } + } + + /** + * mHandler and mUiHandler callbacks + */ + private static final int MSG_CREATE_COVER = 61; + private static final int MSG_DRAW_COVER = 62; + + @Override + public boolean handleMessage(Message message) { + CoverMsg payload = (CoverMsg)message.obj; + + if (payload.isRecent() == false) { + return false; // this rpc is obsolete + } + + switch (message.what) { + case MSG_CREATE_COVER: { + // This message was sent due to a cache miss, but the cover might got cached in the meantime + Bitmap bitmap = sBitmapLruCache.get(payload.key); + if (bitmap == null) { + if (payload.key.mediaType == MediaUtils.TYPE_ALBUM) { + // We only display real covers for queries using the album id as key + Song song = MediaUtils.getSongByTypeId(mContext, payload.key.mediaType, payload.key.mediaId); + if (song != null) { + bitmap = song.getSmallCover(mContext); + } + } else { + bitmap = CoverBitmap.generatePlaceholderCover(mContext, CoverCache.SIZE_SMALL, CoverCache.SIZE_SMALL, payload.title); + } + if (bitmap == null) { + // item has no cover: return a failback + bitmap = sFallbackBitmap; + } + } + // bitmap is non null: store in LRU cache and draw it + sBitmapLruCache.put(payload.key, bitmap); + sUiHandler.sendMessage(sUiHandler.obtainMessage(MSG_DRAW_COVER, payload)); + break; + } + case MSG_DRAW_COVER: { + // draw the cover into view. must be called from ui thread handler + payload.view.drawFromCache(payload.key, true); + break; + } + default: + return false; + } + return true; + } + + /** + * Attempts to set the image of this cover + * Must be called from an UI thread + * + * @param type The Media type + * @param id The id of this media type to query + */ + public void setCover(int type, long id, String title) { + mExpectedKey = new CoverCache.CoverKey(type, id, CoverCache.SIZE_SMALL); + if (drawFromCache(mExpectedKey, false) == false) { + CoverMsg payload = new CoverMsg(mExpectedKey, this, title); + sHandler.sendMessage(sHandler.obtainMessage(MSG_CREATE_COVER, payload)); + } + } + + /** + * Updates the view with a cached bitmap + * A fallback image will be used on cache miss + * + * @param key The cover message containing the cache key and view to use + */ + public boolean drawFromCache(CoverCache.CoverKey key, boolean fadeIn) { + boolean cacheHit = true; + Bitmap bitmap = sBitmapLruCache.get(key); + if (bitmap == null) { + cacheHit = false; + } + + if (fadeIn) { + TransitionDrawable td = new TransitionDrawable(new Drawable[] { + getDrawable(), + (new BitmapDrawable(getResources(), bitmap)) + }); + setImageDrawable(td); + td.startTransition(120); + } else { + setImageBitmap(bitmap); + } + + return cacheHit; + } + + /** + * A LRU cache implementation, using the CoverKey as key to store Bitmap objects + * + * Note that the implementation does not override create() in order to enable + * the use of fetch-if-cached functions: createBitmap() is therefore called + * by CoverCache itself. + */ + private static class BitmapLruCache extends LruCache<CoverCache.CoverKey, Bitmap> { + /** + * Creates a new in-memory LRU cache + * + * @param size the lru cache size in bytes + */ + public BitmapLruCache(int size) { + super(size); + } + + /** + * Returns the cache size in bytes, not objects + */ + @Override + protected int sizeOf(CoverCache.CoverKey key, Bitmap value) { + return value.getByteCount(); + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryActivity.java new file mode 100644 index 0000000..442bd28 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryActivity.java @@ -0,0 +1,1041 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2015-2020 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; +import ch.blinkenlights.android.vanilla.ui.FancyMenu; +import ch.blinkenlights.android.vanilla.ui.FancyMenuItem; +import ch.blinkenlights.android.vanilla.ui.ArrowedText; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.support.iosched.tabs.VanillaTabLayout; +import android.text.TextUtils; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.HorizontalScrollView; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.SearchView; +import android.widget.Toast; + +import androidx.viewpager.widget.ViewPager; + +import java.io.File; + +import junit.framework.Assert; + +/** + * The library activity where songs to play can be selected from the library. + */ +public class LibraryActivity + extends SlidingPlaybackActivity + implements DialogInterface.OnClickListener + , DialogInterface.OnDismissListener + , SearchView.OnQueryTextListener + , FancyMenu.Callback +{ + + + /** + * NOTE: ACTION_* must be in sync with default_action_entries + */ + + /** + * Action for row click: play the row. + */ + public static final int ACTION_PLAY = 0; + /** + * Action for row click: enqueue the row. + */ + public static final int ACTION_ENQUEUE = 1; + /** + * Action for row click: perform the last used action. + */ + public static final int ACTION_LAST_USED = 2; + /** + * Action for row click: play all the songs in the adapter, starting with + * the current row. + */ + public static final int ACTION_PLAY_ALL = 3; + /** + * Action for row click: enqueue all the songs in the adapter, starting with + * the current row. + */ + public static final int ACTION_ENQUEUE_ALL = 4; + /** + * Action for row click: do nothing. + */ + public static final int ACTION_DO_NOTHING = 5; + /** + * Action for row click: expand the row. + */ + public static final int ACTION_EXPAND = 6; + /** + * Action for row click: play if paused or enqueue if playing. + */ + public static final int ACTION_PLAY_OR_ENQUEUE = 7; + /** + * Action for row click: queue selection as next item. + */ + public static final int ACTION_ENQUEUE_AS_NEXT = 8; + /** + * Action for row click: expand or play all. + */ + public static final int ACTION_EXPAND_OR_PLAY_ALL = 9; + /** + * The SongTimeline add song modes corresponding to each relevant action. + */ + private static final int[] modeForAction = + { SongTimeline.MODE_PLAY, SongTimeline.MODE_ENQUEUE, -1, + SongTimeline.MODE_PLAY_ID_FIRST, SongTimeline.MODE_ENQUEUE_ID_FIRST, + -1, -1, -1, SongTimeline.MODE_ENQUEUE_AS_NEXT }; + + public ViewPager mViewPager; + + private BottomBarControls mBottomBarControls; + + private HorizontalScrollView mLimiterScroller; + private ViewGroup mLimiterViews; + private VanillaTabLayout mVanillaTabLayout; + /** + * The action to execute when a row is tapped. + */ + private int mDefaultAction; + /** + * Whether or not to jump to songs if the are in the queue + */ + private boolean mJumpToEnqueuedOnPlay; + /** + * The last used action from the menu. Used with ACTION_LAST_USED. + */ + private int mLastAction = ACTION_PLAY; + /** + * The pager adapter that manages each media ListView. + */ + public LibraryPagerAdapter mPagerAdapter; + /** + * The adapter for the currently visible list. + */ + private LibraryAdapter mCurrentAdapter; + + + @Override + public void onCreate(Bundle state) + { + ThemeHelper.setTheme(this, R.style.Library); + super.onCreate(state); + + if (state == null) { + checkForLaunch(getIntent()); + } + + setContentView(R.layout.library_content); + + mLimiterScroller = (HorizontalScrollView)findViewById(R.id.limiter_scroller); + mLimiterViews = (ViewGroup)findViewById(R.id.limiter_layout); + + LibraryPagerAdapter pagerAdapter = new LibraryPagerAdapter(this, mLooper); + mPagerAdapter = pagerAdapter; + + ViewPager pager = (ViewPager)findViewById(R.id.pager); + pager.setAdapter(pagerAdapter); + mViewPager = pager; + + SharedPreferences settings = SharedPrefHelper.getSettings(this); + + mBottomBarControls = (BottomBarControls)findViewById(R.id.bottombar_controls); + mBottomBarControls.setOnClickListener(this); + mBottomBarControls.setOnQueryTextListener(this); + mBottomBarControls.enableOptionsMenu(this); + + if(PermissionRequestActivity.havePermissions(this) == false) { + PermissionRequestActivity.showWarning(this, getIntent()); + } + + mVanillaTabLayout = (VanillaTabLayout)findViewById(R.id.sliding_tabs); + mVanillaTabLayout.setOnPageChangeListener(pagerAdapter); + + loadTabOrder(); + int page = settings.getInt(PrefKeys.LIBRARY_PAGE, PrefDefaults.LIBRARY_PAGE); + if (page != 0) { + pager.setCurrentItem(page); + } + + loadLimiterIntent(getIntent()); + bindControlButtons(); + + if (state != null && state.getBoolean("launch_search")) { + mBottomBarControls.showSearch(true); + } + } + + @Override + public void onStart() + { + super.onStart(); + + loadPreferences(); + loadTabOrder(); + updateHeaders(); + } + + /** + * Load settings and cache them. + */ + private void loadPreferences() { + SharedPreferences settings = SharedPrefHelper.getSettings(this); + mDefaultAction = Integer.parseInt(settings.getString(PrefKeys.DEFAULT_ACTION_INT, PrefDefaults.DEFAULT_ACTION_INT)); + mJumpToEnqueuedOnPlay = settings.getBoolean(PrefKeys.JUMP_TO_ENQUEUED_ON_PLAY, PrefDefaults.JUMP_TO_ENQUEUED_ON_PLAY); + } + + /** + * Load the tab order and update the tab bars if needed. + */ + private void loadTabOrder() + { + if (mPagerAdapter.loadTabOrder()) { + // Reinitializes all tabs + mVanillaTabLayout.setViewPager(mViewPager); + } + } + + /** + * If this intent looks like a launch from icon/widget/etc, perform + * launch actions. + */ + private void checkForLaunch(Intent intent) + { + SharedPreferences settings = SharedPrefHelper.getSettings(this); + if (settings.getBoolean(PrefKeys.PLAYBACK_ON_STARTUP, PrefDefaults.PLAYBACK_ON_STARTUP) && Intent.ACTION_MAIN.equals(intent.getAction())) { + startActivity(new Intent(this, FullPlaybackActivity.class)); + } + } + + /** + * If the given intent has type data, set a limiter built from that + * data. + */ + private void loadLimiterIntent(Intent intent) + { + Limiter limiter = null; + + int type = intent.getIntExtra("type", -1); + long id = intent.getLongExtra("id", -1); + String folder = intent.getStringExtra("folder"); + + if (type == MediaUtils.TYPE_FILE && folder != null) { + limiter = FileSystemAdapter.buildLimiter(new File(folder)); + } else if (type != -1 && id != -1) { + MediaAdapter adapter = new MediaAdapter(this, type, null, null); + adapter.commitQuery(adapter.query()); + limiter = adapter.buildLimiter(id); + } + + if (limiter != null) { + int tab = mPagerAdapter.setLimiter(limiter); + if (tab == -1 || tab == mViewPager.getCurrentItem()) + updateLimiterViews(); + else + mViewPager.setCurrentItem(tab); + } + } + + @Override + public void onNewIntent(Intent intent) + { + if (intent == null) + return; + + checkForLaunch(intent); + loadLimiterIntent(intent); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) + { + switch (keyCode) { + case KeyEvent.KEYCODE_BACK: + Limiter limiter = mPagerAdapter.getCurrentLimiter(); + + if (mSlidingView.isShrinkable()) { + mSlidingView.hideSlide(); + break; + } + + if (mBottomBarControls.showSearch(false)) { + break; + } + + if (limiter != null) { + int pos = -1; + switch (limiter.type) { + case MediaUtils.TYPE_ALBUM: + setLimiter(MediaUtils.TYPE_ARTIST, limiter.data.toString()); + pos = mPagerAdapter.getMediaTypePosition(limiter.type); + break; + case MediaUtils.TYPE_ARTIST: + case MediaUtils.TYPE_ALBARTIST: + case MediaUtils.TYPE_COMPOSER: + case MediaUtils.TYPE_GENRE: + mPagerAdapter.clearLimiter(limiter.type); + pos = mPagerAdapter.getMediaTypePosition(limiter.type); + break; + case MediaUtils.TYPE_FILE: + File parentFile = ((File)limiter.data).getParentFile(); + mPagerAdapter.setLimiter(FileSystemAdapter.buildLimiter(parentFile)); + break; + } + if (pos == -1) { + updateLimiterViews(); + } else { + mViewPager.setCurrentItem(pos); + } + } else { + finish(); + } + break; + case KeyEvent.KEYCODE_MENU: + // We intercept these to avoid showing the activity-default menu + mBottomBarControls.openMenu(); + break; + case KeyEvent.KEYCODE_SEARCH: + mBottomBarControls.showSearch(true); + break; + default: + return false; + } + + return true; + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) + { + if (keyCode == KeyEvent.KEYCODE_DEL || keyCode == KeyEvent.KEYCODE_FORWARD_DEL) + // On ICS, EditText reports backspace events as unhandled despite + // actually handling them. To workaround, just assume the event was + // handled if we get here. + return true; + + if (super.onKeyDown(keyCode, event)) + return true; + + return false; + } + + /** + * Update the first row of the lists with the appropriate action (play all + * or enqueue all). + */ + private void updateHeaders() + { + int action = mDefaultAction; + if (action == ACTION_LAST_USED) + action = mLastAction; + boolean isEnqueue = action == ACTION_ENQUEUE || action == ACTION_ENQUEUE_ALL; + String text = getString(isEnqueue ? R.string.enqueue_all : R.string.play_all); + mPagerAdapter.setHeaderText(text); + } + + /** + * Adds songs matching the data from the given intent to the song timeline. + * + * @param intent An intent created with + * {@link LibraryAdapter#createData(View)}. + * @param action One of LibraryActivity.ACTION_* + */ + private void pickSongs(Intent intent, final int action) + { + int effectiveAction = action; // mutable copy + long id = intent.getLongExtra("id", LibraryAdapter.INVALID_ID); + int type = mCurrentAdapter.getMediaType(); + + // special handling if we pick one song to be played that is already in queue + boolean songPicked = (id >= 0 && type == MediaUtils.TYPE_SONG); // not invalid, not play all + if (songPicked && effectiveAction == ACTION_PLAY && mJumpToEnqueuedOnPlay) { + int songPosInQueue = PlaybackService.get(this).getQueuePositionForSongId(id); + if (songPosInQueue > -1) { + // we picked for play one song that is already present in the queue, just jump to it + PlaybackService.get(this).jumpToQueuePosition(songPosInQueue); + Toast.makeText(this, R.string.jumping_to_song, Toast.LENGTH_SHORT).show(); + return; + } + } + + boolean all = false; + if (action == ACTION_PLAY_ALL || action == ACTION_ENQUEUE_ALL) { + boolean notPlayAllAdapter = + (id == LibraryAdapter.HEADER_ID) + || !(type <= MediaUtils.TYPE_SONG || type == MediaUtils.TYPE_FILE); + if (effectiveAction == ACTION_ENQUEUE_ALL && notPlayAllAdapter) { + effectiveAction = ACTION_ENQUEUE; + } else if (effectiveAction == ACTION_PLAY_ALL && notPlayAllAdapter) { + effectiveAction = ACTION_PLAY; + } else { + all = true; + } + } + + if (id == LibraryAdapter.HEADER_ID) + all = true; // page header was clicked -> force all mode + + QueryTask query = buildQueryFromIntent(intent, false, (all ? mCurrentAdapter : null)); + query.mode = modeForAction[effectiveAction]; + PlaybackService.get(this).addSongs(query); + + if (mDefaultAction == ACTION_LAST_USED && mLastAction != action) { + mLastAction = action; + updateHeaders(); + } + } + + /** + * "Expand" the view represented by the given intent by setting the limiter + * from the view and switching to the appropriate tab. + * + * @param intent An intent created with + * {@link LibraryAdapter#createData(View)}. + */ + private void expand(Intent intent) + { + mBottomBarControls.showSearch(false); + int type = intent.getIntExtra("type", MediaUtils.TYPE_INVALID); + long id = intent.getLongExtra("id", LibraryAdapter.INVALID_ID); + int tab = mPagerAdapter.setLimiter(mPagerAdapter.mAdapters[type].buildLimiter(id)); + if (tab == -1 || tab == mViewPager.getCurrentItem()) + updateLimiterViews(); + else + mViewPager.setCurrentItem(tab); + } + + /** + * Open the playback activity and close any activities above it in the + * stack. + */ + public void openPlaybackActivity() + { + if (mSlidingView.isShrinkable()) + mSlidingView.hideSlideDelayed(); + startActivity(new Intent(this, FullPlaybackActivity.class)); + } + + /** + * Called by LibraryAdapters when a row has been clicked. + * + * @param rowData The data for the row that was clicked. + */ + public void onItemClicked(Intent rowData) + { + int action = mDefaultAction; + if (action == ACTION_LAST_USED) + action = mLastAction; + + boolean tryExpand = action == ACTION_EXPAND || action == ACTION_EXPAND_OR_PLAY_ALL; + if (tryExpand && rowData.getBooleanExtra(LibraryAdapter.DATA_EXPANDABLE, false)) { + onItemExpanded(rowData); + } else if (action != ACTION_DO_NOTHING) { + if (action == ACTION_EXPAND) { + // default to playing when trying to expand something that can't + // be expanded + action = ACTION_PLAY; + } else if (action == ACTION_EXPAND_OR_PLAY_ALL) { + action = ACTION_PLAY_ALL; + } else if (action == ACTION_PLAY_OR_ENQUEUE) { + action = (mState & PlaybackService.FLAG_PLAYING) == 0 ? ACTION_PLAY : ACTION_ENQUEUE; + } + pickSongs(rowData, action); + } + } + + /** + * Called by LibraryAdapters when a row's expand arrow has been clicked. + * + * @param rowData The data for the row that was clicked. + */ + public void onItemExpanded(Intent rowData) + { + int type = rowData.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID); + if (type == MediaUtils.TYPE_PLAYLIST) + editPlaylist(rowData); + else + expand(rowData); + } + + /** + * Create or recreate the limiter breadcrumbs. + */ + public void updateLimiterViews() + { + mLimiterViews.removeAllViews(); + + Limiter limiterData = mPagerAdapter.getCurrentLimiter(); + if (limiterData != null) { + final int arrowWidth = 8; + String[] limiter = limiterData.names; + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); + for (int i = 0; i != limiter.length; ++i) { + final boolean last = i+1 == limiter.length; + final boolean first = i == 0; + + String txt = limiter[i]; + ArrowedText view = new ArrowedText(this); + int[] colors = {0xFF606060, 0xFF707070}; + + if (i%2 == 0) { + int tmp = colors[0]; + colors[0] = colors[1]; + colors[1] = tmp; + } + + if (last) { + colors[1] = 0xFF404040; + } + + int leftPadding = 14; + if (first) { + leftPadding = 6; + colors[0] = colors[1]; + } + + view.setSingleLine(); + view.setEllipsize(TextUtils.TruncateAt.MARQUEE); + view.setText(txt); + view.setTextColor(Color.WHITE); + view.setLayoutParams(params); + view.setPaddingDIP(leftPadding, 2, 6, 2); + view.setArrowWidthDIP(arrowWidth); + view.setTag(i); + view.setColors(colors[0], colors[1]); + view.setOnClickListener(this); + mLimiterViews.addView(view); + + if (last) { + final int ap = 10; + ArrowedText end = new ArrowedText(this); + end.setOnClickListener(this); + end.setText("×"); + end.setTextColor(0xFFB0B0B0); + end.setLayoutParams(params); + end.setPaddingDIP(0, 2, 0, 2); + end.setArrowWidthDIP(arrowWidth); + end.setArrowPaddingDIP(ap); + end.setMinWidthDIP(arrowWidth+ap); + end.setTag(i); + end.setColors(colors[1], 0); + mLimiterViews.addView(end); + } + } + mLimiterScroller.setVisibility(View.VISIBLE); + } else { + mLimiterScroller.setVisibility(View.GONE); + } + } + + /** + * Updates mCover with the new bitmap, running in the UI thread + * + * @param cover the cover to set, will use a fallback drawable if null + */ + private void updateCover(final Bitmap cover) { + runOnUiThread(new Runnable() { + @Override + public void run() { + mBottomBarControls.setCover(cover); + } + }); + } + + @Override + public void onClick(View view) + { + if (view == mBottomBarControls) { + openPlaybackActivity(); + } else if (view.getTag() != null) { + // a limiter view was clicked + int i = (Integer)view.getTag(); + + Limiter limiter = mPagerAdapter.getCurrentLimiter(); + int type = limiter.type; + if (i == 1 && type == MediaUtils.TYPE_ALBUM) { + setLimiter(MediaUtils.TYPE_ARTIST, limiter.data.toString()); + } else if (i > 0) { + Assert.assertEquals(MediaUtils.TYPE_FILE, limiter.type); + File file = (File)limiter.data; + int diff = limiter.names.length - i; + while (--diff != -1) { + file = file.getParentFile(); + } + mPagerAdapter.setLimiter(FileSystemAdapter.buildLimiter(file)); + } else { + mPagerAdapter.clearLimiter(type); + } + updateLimiterViews(); + } else { + super.onClick(view); + } + } + + /** + * Set a new limiter of the given type built from the first + * MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS row that matches the selection. + * + * @param limiterType The type of limiter to create. Must be either + * MediaUtils.TYPE_ARTIST or MediaUtils.TYPE_ALBUM. + * @param selection Selection to pass to the query. + */ + private void setLimiter(int limiterType, String selection) + { + String[] projection = new String[] { MediaLibrary.ContributorColumns.ARTIST_ID, MediaLibrary.SongColumns.ALBUM_ID, MediaLibrary.ContributorColumns.ARTIST, MediaLibrary.AlbumColumns.ALBUM }; + QueryTask query = new QueryTask(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, projection, selection, null, null); + Cursor cursor = query.runQuery(getApplicationContext()); + + if (cursor != null) { + if (cursor.moveToNext()) { + String[] fields; + String data; + switch (limiterType) { + case MediaUtils.TYPE_ARTIST: + fields = new String[] { cursor.getString(2) }; + data = String.format(MediaLibrary.ContributorColumns.ARTIST_ID+"=%d", cursor.getLong(0)); + break; + case MediaUtils.TYPE_ALBUM: + fields = new String[] { cursor.getString(2), cursor.getString(3) }; + data = String.format(MediaLibrary.SongColumns.ALBUM_ID+"=%d", cursor.getLong(1)); + break; + default: + throw new IllegalArgumentException("setLimiter() does not support limiter type " + limiterType); + } + mPagerAdapter.setLimiter(new Limiter(limiterType, fields, data)); + } + cursor.close(); + } + } + + private static final int CTX_MENU_NOOP = -1; + private static final int CTX_MENU_PLAY = 0; + private static final int CTX_MENU_ENQUEUE = 1; + private static final int CTX_MENU_EXPAND = 2; + private static final int CTX_MENU_ENQUEUE_AS_NEXT = 3; + private static final int CTX_MENU_DELETE = 4; + private static final int CTX_MENU_RENAME_PLAYLIST = 5; + private static final int CTX_MENU_PLAY_ALL = 6; + private static final int CTX_MENU_ENQUEUE_ALL = 7; + private static final int CTX_MENU_MORE_FROM_ALBUM = 8; + private static final int CTX_MENU_MORE_FROM_ARTIST = 9; + private static final int CTX_MENU_OPEN_EXTERNAL = 10; + private static final int CTX_MENU_PLUGINS = 11; + private static final int CTX_MENU_SHOW_DETAILS = 12; + private static final int CTX_MENU_ADD_TO_HOMESCREEN = 13; + private static final int CTX_MENU_ADD_TO_PLAYLIST = 14; + + /** + * Creates a context menu for an adapter row. + * + * @param rowData Data for the adapter row. + * @param view the view which was clicked. + * @param x x-coords of event + * @param y y-coords of event + */ + public boolean onCreateFancyMenu(Intent rowData, View view, float x, float y) { + FancyMenu fm = new FancyMenu(this, this); + // Add to playlist is always available. + fm.addSpacer(20); + fm.add(CTX_MENU_ADD_TO_PLAYLIST, 20, R.drawable.menu_add_to_playlist, R.string.add_to_playlist).setIntent(rowData); + + if (rowData.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID) == LibraryAdapter.HEADER_ID) { + fm.setHeaderTitle(getString(R.string.all_songs)); + fm.add(CTX_MENU_PLAY_ALL, 10, R.drawable.menu_play_all, R.string.play_all).setIntent(rowData); + fm.add(CTX_MENU_ENQUEUE_ALL, 10, R.drawable.menu_enqueue, R.string.enqueue_all).setIntent(rowData); + } else { + int type = rowData.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID); + + fm.setHeaderTitle(rowData.getStringExtra(LibraryAdapter.DATA_TITLE)); + + if (type != MediaUtils.TYPE_FILE) + fm.add(CTX_MENU_ADD_TO_HOMESCREEN, 20, R.drawable.menu_add_to_homescreen, R.string.add_to_homescreen).setIntent(rowData); + + if (FileUtils.canDispatchIntent(rowData)) + fm.add(CTX_MENU_OPEN_EXTERNAL, 10, R.drawable.menu_launch, R.string.open).setIntent(rowData); + + fm.add(CTX_MENU_PLAY, 0, R.drawable.menu_play, R.string.play).setIntent(rowData); + if (type <= MediaUtils.TYPE_SONG || type == MediaUtils.TYPE_FILE) + fm.add(CTX_MENU_PLAY_ALL, 1, R.drawable.menu_play_all, R.string.play_all).setIntent(rowData); + + fm.add(CTX_MENU_ENQUEUE_AS_NEXT, 1, R.drawable.menu_enqueue_as_next, R.string.enqueue_as_next).setIntent(rowData); + fm.add(CTX_MENU_ENQUEUE, 1, R.drawable.menu_enqueue, R.string.enqueue).setIntent(rowData); + + if (type == MediaUtils.TYPE_PLAYLIST) { + fm.add(CTX_MENU_RENAME_PLAYLIST, 0, R.drawable.menu_edit, R.string.rename).setIntent(rowData); + } else if (rowData.getBooleanExtra(LibraryAdapter.DATA_EXPANDABLE, false)) { + fm.add(CTX_MENU_EXPAND, 2, R.drawable.menu_expand, R.string.expand).setIntent(rowData); + } + + if (type == MediaUtils.TYPE_SONG || type == MediaUtils.TYPE_ALBUM) { + fm.addSpacer(30); + fm.add(CTX_MENU_MORE_FROM_ARTIST, 30, R.drawable.menu_artist, R.string.more_from_artist).setIntent(rowData); + + if (type == MediaUtils.TYPE_SONG) { + fm.add(CTX_MENU_MORE_FROM_ALBUM, 30, R.drawable.menu_album, R.string.more_from_album).setIntent(rowData); + fm.add(CTX_MENU_SHOW_DETAILS, 91, R.drawable.menu_details, R.string.details).setIntent(rowData); + if (PluginUtils.checkPlugins(this)) { + // not part of submenu: just last item in normal menu. + fm.add(CTX_MENU_PLUGINS, 99, R.drawable.menu_plugins, R.string.plugins).setIntent(rowData); + } + } + } + fm.addSpacer(90); + fm.add(CTX_MENU_DELETE, 91, R.drawable.menu_delete, R.string.delete).setIntent(rowData); + } + fm.show(view, x, y); + return true; + } + + /** + * Open the playlist editor for the playlist with the given id. + */ + private void editPlaylist(Intent rowData) + { + Intent launch = new Intent(this, PlaylistActivity.class); + launch.putExtra("playlist", rowData.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID)); + launch.putExtra("title", rowData.getStringExtra(LibraryAdapter.DATA_TITLE)); + startActivity(launch); + } + + @Override + public boolean onFancyItemSelected(FancyMenuItem item) { + final Intent intent = item.getIntent(); + switch (item.getItemId()) { + case CTX_MENU_NOOP: + break; + case CTX_MENU_EXPAND: + expand(intent); + if (mDefaultAction == ACTION_LAST_USED && mLastAction != ACTION_EXPAND) { + mLastAction = ACTION_EXPAND; + updateHeaders(); + } + break; + case CTX_MENU_ENQUEUE: + pickSongs(intent, ACTION_ENQUEUE); + break; + case CTX_MENU_PLAY: + pickSongs(intent, ACTION_PLAY); + break; + case CTX_MENU_PLAY_ALL: + pickSongs(intent, ACTION_PLAY_ALL); + break; + case CTX_MENU_ENQUEUE_ALL: + pickSongs(intent, ACTION_ENQUEUE_ALL); + break; + case CTX_MENU_ENQUEUE_AS_NEXT: + pickSongs(intent, ACTION_ENQUEUE_AS_NEXT); + break; + case CTX_MENU_RENAME_PLAYLIST: { + final String playlistName = intent.getStringExtra("title"); + final long playlistId = intent.getLongExtra("id", -1); + PlaylistInputDialog dialog = PlaylistInputDialog.newInstance(new PlaylistInputDialog.Callback() { + @Override + public void onSuccess(String input) { + PlaylistTask playlistTask = new PlaylistTask(playlistId, input); + mHandler.sendMessage(mHandler.obtainMessage(MSG_RENAME_PLAYLIST, playlistTask)); + } + }, playlistName, R.string.rename); + dialog.show(getFragmentManager(), "RenamePlaylistInputDialog"); + break; + } + case CTX_MENU_DELETE: + String delete_message = getString(R.string.delete_item, intent.getStringExtra("title")); + AlertDialog.Builder dialog = new AlertDialog.Builder(this); + dialog.setTitle(R.string.delete); + dialog + .setMessage(delete_message) + .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_DELETE, intent)); + } + }) + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + } + }); + dialog.create().show(); + break; + case CTX_MENU_OPEN_EXTERNAL: { + FileUtils.dispatchIntent(this, intent); + break; + } + case CTX_MENU_SHOW_DETAILS: { + long songId = intent.getLongExtra(LibraryAdapter.DATA_ID, -1); + TrackDetailsDialog.show(getFragmentManager(), songId); + break; + } + case CTX_MENU_PLUGINS: { + showPluginMenu(intent); + break; + } + case CTX_MENU_MORE_FROM_ARTIST: { + String selection; + if (intent.getIntExtra(LibraryAdapter.DATA_TYPE, -1) == MediaUtils.TYPE_ALBUM) { + selection = "album_id="; + } else { + selection = "_id="; + } + selection += intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID); + setLimiter(MediaUtils.TYPE_ARTIST, selection); + updateLimiterViews(); + break; + } + case CTX_MENU_MORE_FROM_ALBUM: + setLimiter(MediaUtils.TYPE_ALBUM, "_id=" + intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID)); + updateLimiterViews(); + break; + case CTX_MENU_ADD_TO_PLAYLIST: { + long id = intent.getLongExtra("id", LibraryAdapter.INVALID_ID); + long songId = intent.getLongExtra(LibraryAdapter.DATA_ID, -1); + Song song = null; + if(songId!=-1) { + song = new Song(songId); + } + PlaylistDialog plDialog = PlaylistDialog.newInstance(this, intent, (id == LibraryAdapter.HEADER_ID ? mCurrentAdapter : null), song); + plDialog.show(getFragmentManager(), "PlaylistDialog"); + break; + } + case CTX_MENU_ADD_TO_HOMESCREEN: { + int type = intent.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID); + long id = intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID); + String label = intent.getStringExtra(LibraryAdapter.DATA_TITLE); + SystemUtils.installLauncherShortcut(this, label, type, id); + break; + } + default: + return super.onContextItemSelected(item); + } + return true; + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) + { + super.onCreateOptionsMenu(menu); + menu.add(0, MENU_PLAYBACK, 0, R.string.playback_view); + menu.add(0, MENU_SEARCH, 0, R.string.search).setIcon(R.drawable.ic_menu_search).setVisible(false); + menu.add(0, MENU_GO_HOME, 30, R.string.go_home); + menu.add(0, MENU_SORT, 30, R.string.sort_by).setIcon(R.drawable.ic_menu_sort_alphabetically); + return true; + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) + { + LibraryAdapter adapter = mCurrentAdapter; + menu.findItem(MENU_GO_HOME).setVisible( + adapter != null && + adapter.getMediaType() == MediaUtils.TYPE_FILE && + (!mSlidingView.isShrinkable() || !mSlidingView.isFullyExpanded())); + return super.onPrepareOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) + { + switch (item.getItemId()) { + case MENU_SEARCH: + mBottomBarControls.showSearch(true); + break; + case MENU_PLAYBACK: + openPlaybackActivity(); + break; + case MENU_GO_HOME: + mPagerAdapter.setLimiter(FileSystemAdapter.buildHomeLimiter(getApplicationContext())); + updateLimiterViews(); + break; + case MENU_SORT: { + SortableAdapter adapter = (SortableAdapter)mCurrentAdapter; + LinearLayout list = (LinearLayout)getLayoutInflater().inflate(R.layout.sort_dialog, null); + CheckBox reverseSort = (CheckBox)list.findViewById(R.id.reverse_sort); + + int[] itemIds = adapter.getSortEntries(); + String[] items = new String[itemIds.length]; + Resources res = getResources(); + for (int i = 0; i < itemIds.length; i++) { + items[i] = res.getString(itemIds[i]); + } + + int mode = adapter.getSortModeIndex(); + reverseSort.setChecked(adapter.isSortDescending()); + + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.sort_by); + builder.setSingleChoiceItems(items, mode, this); + builder.setPositiveButton(R.string.done, null); + + AlertDialog dialog = builder.create(); + dialog.getListView().addFooterView(list); + dialog.setOnDismissListener(this); + dialog.show(); + break; + } + default: + return super.onOptionsItemSelected(item); + } + return true; + } + + /** + * Callback of mSearchView while user types in text + */ + @Override + public boolean onQueryTextChange (String newText) { + mPagerAdapter.setFilter(newText); + return true; + } + + /** + * Callback of mSearchViews submit action + */ + @Override + public boolean onQueryTextSubmit (String query) { + mPagerAdapter.setFilter(query); + return true; + } + + /** + * Save the current page, passed in arg1, to SharedPreferences. + */ + private static final int MSG_SAVE_PAGE = 40; + /** + * Updates mCover using a background thread + */ + private static final int MSG_UPDATE_COVER = 41; + + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_SAVE_PAGE: { + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(this).edit(); + editor.putInt("library_page", message.arg1); + editor.apply(); + super.adjustSpines(); + break; + } + case MSG_UPDATE_COVER: { + Bitmap cover = null; + Song song = (Song)message.obj; + if (song != null) { + cover = song.getSmallCover(this); + } + // Dispatch view update to UI thread + updateCover(cover); + break; + } + default: + return super.handleMessage(message); + } + + return true; + } + + @Override + public void onMediaChange() + { + if (mPagerAdapter != null) + mPagerAdapter.invalidateData(); + } + + @Override + protected void onStateChange(int state, int toggled) + { + super.onStateChange(state, toggled); + + if ((state & PlaybackService.FLAG_EMPTY_QUEUE) != 0) + mBottomBarControls.setSong(null); + } + + @Override + protected void onSongChange(Song song) + { + super.onSongChange(song); + + mBottomBarControls.setSong(song); + if (song != null) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_COVER, song)); + mPagerAdapter.onSongChange(song); + } + } + + @Override + public void onClick(DialogInterface dialog, int which) + { + dialog.dismiss(); + } + + @Override + public void onDismiss(DialogInterface dialog) + { + ListView list = ((AlertDialog)dialog).getListView(); + int which = list.getCheckedItemPosition(); + + CheckBox reverseSort = (CheckBox)list.findViewById(R.id.reverse_sort); + if (reverseSort.isChecked()) { + which = ~which; + } + + mPagerAdapter.setSortMode(which); + } + + /** + * Called when a new page becomes visible. + * + * @param position The position of the new page. + * @param adapter The new visible adapter. + */ + public void onPageChanged(int position, LibraryAdapter adapter) + { + mCurrentAdapter = adapter; + updateLimiterViews(); + if (adapter != null && (adapter.getLimiter() == null || adapter.getMediaType() == MediaUtils.TYPE_FILE)) { + // Save current page so it is opened on next startup. Don't save if + // the page was expanded to, as the expanded page isn't the starting + // point. This limitation does not affect the files tab as the limiter + // (the files almost always have a limiter) + Handler handler = mHandler; + handler.sendMessage(mHandler.obtainMessage(MSG_SAVE_PAGE, position, 0)); + } + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryAdapter.java new file mode 100644 index 0000000..67bd70e --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryAdapter.java @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Intent; +import android.view.View; +import android.widget.ListAdapter; + +/** + * Provides support for limiters and a few other methods LibraryActivity uses + * for its adapters. + */ +public interface LibraryAdapter extends ListAdapter { + /** + * Return the type of media represented by this adapter. One of + * MediaUtils.TYPE_*. + */ + int getMediaType(); + + /** + * Set the limiter for the adapter. + * + * A limiter is intended to restrict displayed media to only those that are + * children of a given parent media item. + * + * @param limiter The limiter, created by + * {@link LibraryAdapter#buildLimiter(long)}. + */ + void setLimiter(Limiter limiter); + + /** + * Returns the limiter currently active on this adapter or null if none are + * active. + */ + Limiter getLimiter(); + + /** + * Builds a limiter based off of the media represented by the given row. + * + * @param id The id of the row. + * @see LibraryAdapter#getLimiter() + * @see LibraryAdapter#setLimiter(Limiter) + */ + Limiter buildLimiter(long id); + + /** + * Set a new filter. + * + * The data should be requeried after calling this. + * + * @param filter The terms to filter on, separated by spaces. Only + * media that contain all of the terms (in any order) will be displayed + * after filtering is complete. + */ + void setFilter(String filter); + + /** + * Retrieve the data for this adapter. The data must be set with + * {@link LibraryAdapter#commitQuery(Object)} before it takes effect. + * + * This should be called on a worker thread. + * + * @return The data. Contents depend on the sub-class. + */ + Object query(); + + /** + * Retrieve a query which will fetch all songs represented by + * this adapter. + * + * @return a query task. + */ + QueryTask buildSongQuery(String[] projection); + + /** + * Update the adapter with the given data. + * + * Must be called on the UI thread. + * + * @param data Data from {@link LibraryAdapter#query()}. + */ + void commitQuery(Object data); + + /** + * Clear the data for this adapter. + * + * Must be called on the UI thread. + */ + void clear(); + + /** + * Creates the row data used by LibraryActivity. + */ + Intent createData(View row); + + /** + * Extra for row data: media id. type: long. + */ + String DATA_ID = "id"; + /** + * Special id for {@link #DATA_ID}: the row represented is a header view. + */ + long HEADER_ID = -1; + /** + * Special id for {@link #DATA_ID}: invalid id. + */ + long INVALID_ID = -2; + /** + * Extra for row data: media title. type: String. + */ + String DATA_TITLE = "title"; + /** + * Extra for row data: media type. type: int. One of MediaUtils.TYPE_*. + */ + String DATA_TYPE = "type"; + /** + * Extra for row data: canonical file path. type: String. Only present if + * type is {@link MediaUtils#TYPE_FILE}. + */ + String DATA_FILE = "file"; + /** + * Extra for row data: if true, row has expander arrow. type: boolean. + */ + String DATA_EXPANDABLE = "expandable"; +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryPagerAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryPagerAdapter.java new file mode 100644 index 0000000..98c7972 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/LibraryPagerAdapter.java @@ -0,0 +1,974 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2015-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.vanilla.ext.CoordClickListener; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.os.Parcelable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.util.LruCache; +import android.widget.AdapterView; +import android.widget.ListView; +import java.util.Arrays; +import java.util.ArrayList; + +import androidx.viewpager.widget.PagerAdapter; +import androidx.viewpager.widget.ViewPager; + + +/** + * PagerAdapter that manages the library media ListViews. + */ +public class LibraryPagerAdapter + extends PagerAdapter + implements Handler.Callback + , ViewPager.OnPageChangeListener + , CoordClickListener.Callback + , AdapterView.OnItemClickListener +{ + /** + * The number of unique list types. The number of visible lists may be + * smaller. + */ + public static final int MAX_ADAPTER_COUNT = MediaUtils.TYPE_COUNT; + /** + * The human-readable title for each list. The positions correspond to the + * MediaUtils ids, so e.g. TITLES[MediaUtils.TYPE_SONG] = R.string.songs + */ + public static final int[] TITLES = { R.string.artists, R.string.albums, R.string.songs, R.string.playlists, + R.string.genres, R.string.albumartists, R.string.composers, R.string.files }; + /** + * Default tab order. + */ + public static final int[] DEFAULT_TAB_ORDER = { MediaUtils.TYPE_ARTIST, MediaUtils.TYPE_ALBARTIST, MediaUtils.TYPE_COMPOSER, + MediaUtils.TYPE_ALBUM, MediaUtils.TYPE_SONG, MediaUtils.TYPE_PLAYLIST, + MediaUtils.TYPE_GENRE, MediaUtils.TYPE_FILE }; + /** + * The default visibility of tabs + */ + public static final boolean[] DEFAULT_TAB_VISIBILITY = { true, false, false, true, true, true, true, true }; + + /** + * The user-chosen tab order. + */ + int[] mTabOrder; + /** + * The number of visible tabs. + */ + private int mTabCount; + /** + * The ListView for each adapter. Each index corresponds to that list's + * MediaUtils id. + */ + private final ListView[] mLists = new ListView[MAX_ADAPTER_COUNT]; + /** + * The adapters. Each index corresponds to that adapter's MediaUtils id. + */ + public LibraryAdapter[] mAdapters = new LibraryAdapter[MAX_ADAPTER_COUNT]; + /** + * Whether the adapter corresponding to each index has stale data. + */ + private final boolean[] mRequeryNeeded = new boolean[MAX_ADAPTER_COUNT]; + /** + * The artist adapter instance, also stored at mAdapters[MediaUtils.TYPE_ARTIST]. + */ + private MediaAdapter mArtistAdapter; + /** + * The albumartist adapter instance, also stored at mAdapters[MediaUtils.TYPE_ALBART]. + */ + private MediaAdapter mAlbArtAdapter; + /** + * The composer adapter instance, also stored at mAdapters[MediaUtils.TYPE_COMPOSER]. + */ + private MediaAdapter mComposerAdapter; + /** + * The album adapter instance, also stored at mAdapters[MediaUtils.TYPE_ALBUM]. + */ + private MediaAdapter mAlbumAdapter; + /** + * The song adapter instance, also stored at mAdapters[MediaUtils.TYPE_SONG]. + */ + private MediaAdapter mSongAdapter; + /** + * The playlist adapter instance, also stored at mAdapters[MediaUtils.TYPE_PLAYLIST]. + */ + MediaAdapter mPlaylistAdapter; + /** + * The genre adapter instance, also stored at mAdapters[MediaUtils.TYPE_GENRE]. + */ + private MediaAdapter mGenreAdapter; + /** + * The file adapter instance, also stored at mAdapters[MediaUtils.TYPE_FILE]. + */ + private FileSystemAdapter mFilesAdapter; + /** + * LRU cache holding the last scrolling position of all adapter views + */ + private static AdaperPositionLruCache sLruAdapterPos; + /** + * The adapter of the currently visible list. + */ + private LibraryAdapter mCurrentAdapter; + /** + * The index of the current page. + */ + private int mCurrentPage; + /** + * A limiter that should be set when the album adapter is created. + */ + private Limiter mPendingArtistLimiter; + /** + * A limiter that should be set when the albumartist adapter is created. + */ + private Limiter mPendingAlbArtLimiter; + /** + * A limiter that should be set when the composer adapter is created. + */ + private Limiter mPendingComposerLimiter; + /** + * A limiter that should be set when the album adapter is created. + */ + private Limiter mPendingAlbumLimiter; + /** + * A limiter that should be set when the song adapter is created. + */ + private Limiter mPendingSongLimiter; + /** + * A limiter that should be set when the files adapter is created. + */ + private Limiter mPendingFileLimiter; + /** + * The LibraryActivity that owns this adapter. The adapter will be notified + * of changes in the current page. + */ + private final LibraryActivity mActivity; + /** + * A Handler running on the UI thread. + */ + private final Handler mUiHandler; + /** + * A Handler running on a worker thread. + */ + private final Handler mWorkerHandler; + /** + * The text to be displayed in the first row of the artist, album, and + * song limiters. + */ + private String mHeaderText; + /** + * A list of header rows which require test updates + */ + private ArrayList<DraggableRow> mHeaderViews = new ArrayList(); + /** + * The current filter text, or null if none. + */ + private String mFilter; + + /** + * Create the LibraryPager. + * + * @param activity The LibraryActivity that will own this adapter. The activity + * will receive callbacks from the ListViews. + * @param workerLooper A Looper running on a worker thread. + */ + public LibraryPagerAdapter(LibraryActivity activity, Looper workerLooper) + { + if (sLruAdapterPos == null) + sLruAdapterPos = new AdaperPositionLruCache(32); + mActivity = activity; + mUiHandler = new Handler(this); + mWorkerHandler = new Handler(workerLooper, this); + mCurrentPage = -1; + } + + /** + * Load the tab order from SharedPreferences. + * + * @return True if order has changed. + */ + public boolean loadTabOrder() + { + String in = SharedPrefHelper.getSettings(mActivity).getString(PrefKeys.TAB_ORDER, PrefDefaults.TAB_ORDER); + int[] order = new int[MAX_ADAPTER_COUNT]; + int count = 0; + if (in != null && in.length() == MAX_ADAPTER_COUNT) { + char[] chars = in.toCharArray(); + order = new int[MAX_ADAPTER_COUNT]; + for (int i = 0; i != MAX_ADAPTER_COUNT; ++i) { + char v = chars[i]; + if (v >= 128) { + v -= 128; + if (v >= MediaUtils.TYPE_COUNT) { + // invalid media type, ignore all data + count = 0; + break; + } + order[count++] = v; + } + } + } + + // set default tabs if none were loaded + if (count == 0) { + for (int i=0; i != MAX_ADAPTER_COUNT; i++) { + if (DEFAULT_TAB_VISIBILITY[i]) + order[count++] = DEFAULT_TAB_ORDER[i]; + } + } + + if (count != mTabCount || !Arrays.equals(order, mTabOrder)) { + mTabOrder = order; + mTabCount = count; + notifyDataSetChanged(); + computeExpansions(); + return true; + } + + return false; + } + + /** + * Determines whether adapters should be expandable from the visibility of + * the adapters each expands to. Also updates mSongsPosition/mAlbumsPositions. + */ + public void computeExpansions() + { + if (mGenreAdapter != null) + mGenreAdapter.setExpandable( + getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 || + getMediaTypePosition(MediaUtils.TYPE_ALBUM) != -1 || + getMediaTypePosition(MediaUtils.TYPE_ARTIST) != -1 + ); + if (mArtistAdapter != null) + mArtistAdapter.setExpandable( + getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 || + getMediaTypePosition(MediaUtils.TYPE_ALBUM) != -1 + ); + if (mAlbumAdapter != null) + mAlbumAdapter.setExpandable( + getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 + ); + } + + @Override + public Object instantiateItem(ViewGroup container, int position) + { + int type = mTabOrder[position]; + ListView view = mLists[type]; + + if (view == null) { + LibraryActivity activity = mActivity; + LayoutInflater inflater = activity.getLayoutInflater(); + LibraryAdapter adapter; + DraggableRow header = null; + + switch (type) { + case MediaUtils.TYPE_ARTIST: + adapter = mArtistAdapter = new MediaAdapter(activity, MediaUtils.TYPE_ARTIST, mPendingArtistLimiter, activity); + mArtistAdapter.setExpandable(getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 || getMediaTypePosition(MediaUtils.TYPE_ALBUM) != -1); + header = (DraggableRow)inflater.inflate(R.layout.draggable_row, null); + break; + case MediaUtils.TYPE_ALBARTIST: + adapter = mAlbArtAdapter = new MediaAdapter(activity, MediaUtils.TYPE_ALBARTIST, mPendingAlbArtLimiter, activity); + mAlbArtAdapter.setExpandable(getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 || getMediaTypePosition(MediaUtils.TYPE_ALBUM) != -1); + header = (DraggableRow)inflater.inflate(R.layout.draggable_row, null); + break; + case MediaUtils.TYPE_COMPOSER: + adapter = mComposerAdapter = new MediaAdapter(activity, MediaUtils.TYPE_COMPOSER, mPendingComposerLimiter, activity); + mComposerAdapter.setExpandable(getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 || getMediaTypePosition(MediaUtils.TYPE_ALBUM) != -1); + header = (DraggableRow)inflater.inflate(R.layout.draggable_row, null); + break; + case MediaUtils.TYPE_ALBUM: + adapter = mAlbumAdapter = new MediaAdapter(activity, MediaUtils.TYPE_ALBUM, mPendingAlbumLimiter, activity); + mAlbumAdapter.setExpandable(getMediaTypePosition(MediaUtils.TYPE_SONG) != -1); + mPendingAlbumLimiter = null; + header = (DraggableRow)inflater.inflate(R.layout.draggable_row, null); + break; + case MediaUtils.TYPE_SONG: + adapter = mSongAdapter = new MediaAdapter(activity, MediaUtils.TYPE_SONG, mPendingSongLimiter, activity); + mPendingSongLimiter = null; + header = (DraggableRow)inflater.inflate(R.layout.draggable_row, null); + break; + case MediaUtils.TYPE_PLAYLIST: + adapter = mPlaylistAdapter = new MediaAdapter(activity, MediaUtils.TYPE_PLAYLIST, null, activity); + break; + case MediaUtils.TYPE_GENRE: + adapter = mGenreAdapter = new MediaAdapter(activity, MediaUtils.TYPE_GENRE, null, activity); + mGenreAdapter.setExpandable( + getMediaTypePosition(MediaUtils.TYPE_SONG) != -1 || + getMediaTypePosition(MediaUtils.TYPE_ALBUM) != -1 || + getMediaTypePosition(MediaUtils.TYPE_ARTIST) != -1 + ); + break; + case MediaUtils.TYPE_FILE: + adapter = mFilesAdapter = new FileSystemAdapter(activity, mPendingFileLimiter); + mPendingFileLimiter = null; + header = (DraggableRow)inflater.inflate(R.layout.draggable_row, null); + break; + default: + throw new IllegalArgumentException("Invalid media type: " + type); + } + + CoordClickListener ccl = new CoordClickListener(this); + view = (ListView)inflater.inflate(R.layout.listview, null); + ccl.registerForOnItemLongClickListener(view); + view.setOnItemClickListener(this); + view.setTag(type); + + if (header != null) { + header.setText(mHeaderText); + header.setTag(new ViewHolder()); // behave like a normal library row + view.addHeaderView(header); + mHeaderViews.add(header); + } + view.setAdapter(adapter); + + loadSortOrder((SortableAdapter)adapter); + + adapter.setFilter(mFilter); + + mAdapters[type] = adapter; + mLists[type] = view; + mRequeryNeeded[type] = true; + } + + requeryIfNeeded(type); + container.addView(view); + return view; + } + + @Override + public int getItemPosition(Object item) + { + int type = (Integer)((ListView)item).getTag(); + int pos = getMediaTypePosition(type); + return pos == -1 ? POSITION_NONE : pos; + } + + @Override + public void destroyItem(ViewGroup container, int position, Object object) + { + container.removeView((View)object); + } + + @Override + public CharSequence getPageTitle(int position) + { + return mActivity.getResources().getText(TITLES[mTabOrder[position]]); + } + + @Override + public int getCount() + { + return mTabCount; + } + + @Override + public boolean isViewFromObject(View view, Object object) + { + return view == object; + } + + @Override + public void setPrimaryItem(ViewGroup container, int position, Object object) + { + int type = mTabOrder[position]; + LibraryAdapter adapter = mAdapters[type]; + if (position != mCurrentPage || adapter != mCurrentAdapter) { + requeryIfNeeded(type); + mCurrentAdapter = adapter; + mCurrentPage = position; + mActivity.onPageChanged(position, adapter); + } + } + + @Override + public void restoreState(Parcelable state, ClassLoader loader) + { + Bundle in = (Bundle)state; + mPendingArtistLimiter = (Limiter)in.getSerializable("limiter_artists"); + mPendingAlbArtLimiter = (Limiter)in.getSerializable("limiter_albumartists"); + mPendingComposerLimiter = (Limiter)in.getSerializable("limiter_composer"); + mPendingAlbumLimiter = (Limiter)in.getSerializable("limiter_albums"); + mPendingSongLimiter = (Limiter)in.getSerializable("limiter_songs"); + mPendingFileLimiter = (Limiter)in.getSerializable("limiter_files"); + } + + @Override + public Parcelable saveState() + { + Bundle out = new Bundle(10); + if (mArtistAdapter != null) + out.putSerializable("limiter_artists", mArtistAdapter.getLimiter()); + if (mAlbArtAdapter != null) + out.putSerializable("limiter_albumartists", mAlbArtAdapter.getLimiter()); + if (mComposerAdapter != null) + out.putSerializable("limiter_composer", mComposerAdapter.getLimiter()); + if (mAlbumAdapter != null) + out.putSerializable("limiter_albums", mAlbumAdapter.getLimiter()); + if (mSongAdapter != null) + out.putSerializable("limiter_songs", mSongAdapter.getLimiter()); + if (mFilesAdapter != null) + out.putSerializable("limiter_files", mFilesAdapter.getLimiter()); + + maintainPosition(); + return out; + } + + /** + * Sets the text to be displayed in the first row of the artist, album, and + * song lists. + */ + public void setHeaderText(String text) + { + for(DraggableRow row : mHeaderViews) { + row.setText(text); + } + mHeaderText = text; + } + + /** + * Clear a limiter. + * + * @param type Which type of limiter to clear. + */ + public void clearLimiter(int type) + { + ArrayList<LibraryAdapter> targets = new ArrayList<LibraryAdapter>(); + + maintainPosition(); + + if (type == MediaUtils.TYPE_FILE) { + if (mFilesAdapter == null) { + mPendingFileLimiter = null; + } else { + targets.add(mFilesAdapter); + } + } else { + if (mArtistAdapter == null) { + mPendingArtistLimiter = null; + } else { + targets.add(mArtistAdapter); + } + if (mAlbArtAdapter == null) { + mPendingAlbArtLimiter = null; + } else { + targets.add(mAlbArtAdapter); + } + if (mComposerAdapter == null) { + mPendingComposerLimiter = null; + } else { + targets.add(mComposerAdapter); + } + if (mAlbumAdapter == null) { + mPendingAlbumLimiter = null; + } else { + targets.add(mAlbumAdapter); + } + if (mSongAdapter == null) { + mPendingSongLimiter = null; + } else { + targets.add(mSongAdapter); + } + } + + for (LibraryAdapter adapter : targets) { + adapter.setLimiter(null); + loadSortOrder((SortableAdapter)adapter); + requestRequery(adapter); + } + } + + /** + * Update the adapters with the given limiter. + * + * @param limiter The limiter to set. + * @return The tab type that should be switched to to expand the row. + */ + public int setLimiter(Limiter limiter) + { + int tab; + ArrayList<LibraryAdapter> targets = new ArrayList<LibraryAdapter>(); + + maintainPosition(); + + switch (limiter.type) { + case MediaUtils.TYPE_ALBUM: + if (mSongAdapter == null) { + mPendingSongLimiter = limiter; + } else { + targets.add(mSongAdapter); + } + tab = getMediaTypePosition(MediaUtils.TYPE_SONG); + break; + case MediaUtils.TYPE_ARTIST: + case MediaUtils.TYPE_ALBARTIST: + case MediaUtils.TYPE_COMPOSER: + if (mAlbumAdapter == null) { + mPendingAlbumLimiter = limiter; + } else { + targets.add(mAlbumAdapter); + } + if (mSongAdapter == null) { + mPendingSongLimiter = limiter; + } else { + targets.add(mSongAdapter); + } + tab = getMediaTypePosition(MediaUtils.TYPE_ALBUM); + if (tab == -1) + tab = getMediaTypePosition(MediaUtils.TYPE_SONG); + break; + case MediaUtils.TYPE_GENRE: + if (mArtistAdapter == null) { + mPendingArtistLimiter = limiter; + } else { + targets.add(mArtistAdapter); + } + if (mAlbArtAdapter == null) { + mPendingAlbArtLimiter = limiter; + } else { + targets.add(mAlbArtAdapter); + } + if (mComposerAdapter == null) { + mPendingComposerLimiter = limiter; + } else { + targets.add(mComposerAdapter); + } + if (mAlbumAdapter == null) { + mPendingAlbumLimiter = limiter; + } else { + targets.add(mAlbumAdapter); + } + if (mSongAdapter == null) { + mPendingSongLimiter = limiter; + } else { + targets.add(mSongAdapter); + } + tab = getMediaTypePosition(MediaUtils.TYPE_ARTIST); + if (tab == -1) + tab = getMediaTypePosition(MediaUtils.TYPE_ALBUM); + if (tab == -1) + tab = getMediaTypePosition(MediaUtils.TYPE_SONG); + break; + case MediaUtils.TYPE_FILE: + if (mFilesAdapter == null) { + mPendingFileLimiter = limiter; + } else { + targets.add(mFilesAdapter); + // forcefully jump to beginning - commit query might restore a saved position + // but if it doesn't we would end up at the same scrolling position in a new + // folder which is uncool. + mLists[MediaUtils.TYPE_FILE].setSelection(0); + } + tab = getMediaTypePosition(MediaUtils.TYPE_FILE); + break; + default: + throw new IllegalArgumentException("Unsupported limiter type: " + limiter.type); + } + + for (LibraryAdapter adapter : targets) { + adapter.setLimiter(limiter); + loadSortOrder((SortableAdapter)adapter); + requestRequery(adapter); + } + + return tab; + } + + /** + * Saves the scrolling position of every visible limiter + */ + private void maintainPosition() { + for (int i = MAX_ADAPTER_COUNT; --i != -1; ) { + if (mAdapters[i] != null) { + sLruAdapterPos.storePosition(mAdapters[i], mLists[i].getFirstVisiblePosition()); + } + } + } + + /** + * Restores the saved scrolling position + */ + private void restorePosition(int index) { + // Restore scrolling position if present and valid + Integer curPos = sLruAdapterPos.popPosition(mAdapters[index]); + if (curPos != null && curPos < mLists[index].getCount()) + mLists[index].setSelection(curPos); + } + + /** + * Returns the limiter set on the current adapter or null if there is none. + */ + public Limiter getCurrentLimiter() + { + LibraryAdapter current = mCurrentAdapter; + if (current == null) + return null; + return current.getLimiter(); + } + + /** + * Returns the tab position of given media type, -1 if not visible. + * + * @return int + */ + public int getMediaTypePosition(int type) { + int[] order = mTabOrder; + for (int i = mTabCount; --i != -1; ) { + if (order[i] == type) + return i; + } + return -1; + } + + /** + * Run on query on the adapter passed in obj. + * + * Runs on worker thread. + */ + private static final int MSG_RUN_QUERY = 0; + /** + * Save the sort mode for the adapter passed in obj. + * + * Runs on worker thread. + */ + private static final int MSG_SAVE_SORT = 1; + /** + * Call {@link LibraryPagerAdapter#requestRequery(LibraryAdapter)} on the adapter + * passed in obj. + * + * Runs on worker thread. + */ + private static final int MSG_REQUEST_REQUERY = 2; + /** + * Commit the cursor passed in obj to the adapter at the index passed in + * arg1. + * + * Runs on UI thread. + */ + private static final int MSG_COMMIT_QUERY = 3; + + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_RUN_QUERY: { + LibraryAdapter adapter = (LibraryAdapter)message.obj; + int index = adapter.getMediaType(); + Handler handler = mUiHandler; + handler.sendMessage(handler.obtainMessage(MSG_COMMIT_QUERY, index, 0, adapter.query())); + break; + } + case MSG_COMMIT_QUERY: { + int index = message.arg1; + mAdapters[index].commitQuery(message.obj); + restorePosition(index); + break; + } + case MSG_SAVE_SORT: { + SortableAdapter adapter = (SortableAdapter)message.obj; + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(mActivity).edit(); + editor.putInt(adapter.getSortSettingsKey(), adapter.getSortMode()); + editor.apply(); + break; + } + case MSG_REQUEST_REQUERY: + requestRequery((LibraryAdapter)message.obj); + break; + default: + return false; + } + + return true; + } + + /** + * Requery the given adapter. If it is the current adapter, requery + * immediately. Otherwise, mark the adapter as needing a requery and requery + * when its tab is selected. + * + * Must be called on the UI thread. + */ + public void requestRequery(LibraryAdapter adapter) + { + if (adapter == mCurrentAdapter) { + postRunQuery(adapter); + } else { + mRequeryNeeded[adapter.getMediaType()] = true; + // Clear the data for non-visible adapters (so we don't show the old + // data briefly when we later switch to that adapter) + adapter.clear(); + } + } + + /** + * Call {@link LibraryPagerAdapter#requestRequery(LibraryAdapter)} on the UI + * thread. + * + * @param adapter The adapter, passed to requestRequery. + */ + public void postRequestRequery(LibraryAdapter adapter) + { + Handler handler = mUiHandler; + handler.sendMessage(handler.obtainMessage(MSG_REQUEST_REQUERY, adapter)); + } + + /** + * Schedule a query to be run for the given adapter on the worker thread. + * + * @param adapter The adapter to run the query for. + */ + private void postRunQuery(LibraryAdapter adapter) + { + mRequeryNeeded[adapter.getMediaType()] = false; + Handler handler = mWorkerHandler; + handler.removeMessages(MSG_RUN_QUERY, adapter); + handler.sendMessage(handler.obtainMessage(MSG_RUN_QUERY, adapter)); + } + + /** + * Requery the adapter of the given type if it exists and needs a requery. + * + * @param type One of MediaUtils.TYPE_* + */ + private void requeryIfNeeded(int type) + { + LibraryAdapter adapter = mAdapters[type]; + if (adapter != null && mRequeryNeeded[type]) { + postRunQuery(adapter); + } + } + + /** + * Invalidate the data for all adapters. + */ + public void invalidateData() + { + for (LibraryAdapter adapter : mAdapters) { + if (adapter != null) { + postRequestRequery(adapter); + } + } + } + + /** + * Set the saved sort mode for the given adapter. The adapter should + * be re-queried after calling this. + * + * @param adapter The adapter to load for. + */ + public void loadSortOrder(SortableAdapter adapter) + { + String key = adapter.getSortSettingsKey(); + int def = adapter.getDefaultSortMode(); + int sort = SharedPrefHelper.getSettings(mActivity).getInt(key, def); + adapter.setSortMode(sort); + } + + /** + * Set the sort mode for the current adapter. Current adapter must be a + * MediaAdapter. Saves this sort mode to preferences and updates the list + * associated with the adapter to display the new sort mode. + * + * @param mode The sort mode. See {@link MediaAdapter#setSortMode(int)} for + * details. + */ + public void setSortMode(int mode) + { + SortableAdapter adapter = (SortableAdapter)mCurrentAdapter; + if (mode == adapter.getSortMode()) + return; + + adapter.setSortMode(mode); + requestRequery(mCurrentAdapter); + + Handler handler = mWorkerHandler; + handler.sendMessage(handler.obtainMessage(MSG_SAVE_SORT, adapter)); + } + + /** + * Set a new filter on all the adapters. + */ + public void setFilter(String text) + { + if (text.length() == 0) + text = null; + + mFilter = text; + for (LibraryAdapter adapter : mAdapters) { + if (adapter != null) { + adapter.setFilter(text); + requestRequery(adapter); + } + } + } + + @Override + public void onPageScrollStateChanged(int state) + { + } + + @Override + public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) + { + } + + @Override + public void onPageSelected(int position) + { + // onPageSelected and setPrimaryItem are called in similar cases, and it + // would be nice to use just one of them, but each has caveats: + // - onPageSelected isn't called when the ViewPager is first + // initialized if there is no scrolling to do + // - setPrimaryItem isn't called until scrolling is complete, which + // makes tab bar and limiter updates look bad + // So we use both. + setPrimaryItem(null, position, null); + } + + /** + * Creates the row data used by LibraryActivity. + */ + private static Intent createHeaderIntent(View header) + { + int type = (Integer)((View)header.getParent()).getTag(); // tag is set on parent view of header + Intent intent = new Intent(); + intent.putExtra(LibraryAdapter.DATA_ID, LibraryAdapter.HEADER_ID); + intent.putExtra(LibraryAdapter.DATA_TYPE, type); + return intent; + } + + @Override + /** + * Dispatch long click event of a row. + * + * @param parent the parent adapter view + * @param view the long clicked view + * @param position row position + * @param id id of the long clicked row + * @param x x-coords of event + * @param y y-coords of event + * + * @return true if the event was consumed + */ + public boolean onItemLongClickWithCoords (AdapterView<?> parent, View view, int position, long id, float x, float y) { + Intent intent = id == LibraryAdapter.HEADER_ID ? createHeaderIntent(view) : mCurrentAdapter.createData(view); + int type = (Integer)((View)view.getParent()).getTag(); + + if (type == MediaUtils.TYPE_FILE) { + return mFilesAdapter.onCreateFancyMenu(intent, view, x, y); + } + return mActivity.onCreateFancyMenu(intent, view, x, y); + } + + @Override + public void onItemClick (AdapterView<?> parent, View view, int position, long id) { + Intent intent = id == LibraryAdapter.HEADER_ID ? createHeaderIntent(view) : mCurrentAdapter.createData(view); + int type = (Integer)((View)view.getParent()).getTag(); + + if (type == MediaUtils.TYPE_FILE) { + mFilesAdapter.onItemClicked(intent); + } else { + mActivity.onItemClicked(intent); + } + } + + /** + * Perform usability-related actions on pager and contained lists, e.g. highlight current song + * or scroll to it if opted-in + * @param song song that is currently playing, can be null + */ + public void onSongChange(Song song) { + if (mCurrentPage == -1) // no page active, nothing to do + return; + + int type = mTabOrder[mCurrentPage]; + ListView view = mLists[type]; + if (view == null) // not initialized yet, nothing to do + return; + + long id = MediaUtils.getCurrentIdForType(song, type); + if (id == -1) // unknown type + return; + + // scroll to song on song change if opted-in + SharedPreferences sharedPrefs = SharedPrefHelper.getSettings(mActivity); + boolean shouldScroll = sharedPrefs.getBoolean(PrefKeys.ENABLE_SCROLL_TO_SONG, PrefDefaults.ENABLE_SCROLL_TO_SONG); + if(shouldScroll) { + for (int pos = 0; pos < view.getCount(); pos++) { + if (view.getItemIdAtPosition(pos) == id) { + // for Android < 6.x visible positions are valid only if view is shown + boolean interactive = view.isShown(); + int middlePos = (view.getFirstVisiblePosition() + view.getLastVisiblePosition()) / 2; + if (interactive && Math.abs(middlePos - pos) < 30) { + view.smoothScrollToPosition(pos); + } else { + view.setSelection(pos); + } + break; + } + } + } + } + + /** + * LRU implementation: saves the adapter position + */ + private class AdaperPositionLruCache extends LruCache<String, Integer> { + public AdaperPositionLruCache(int size) { + super(size); + } + public void storePosition(LibraryAdapter adapter, Integer val) { + this.put(_k(adapter), val); + } + public Integer popPosition(LibraryAdapter adapter) { + return this.remove(_k(adapter)); + } + + /** + * Assemble internal cache key from adapter + */ + private String _k(LibraryAdapter adapter) { + String result = adapter.getMediaType()+"://"; + Limiter limiter = adapter.getLimiter(); + + if (limiter != null) { + for(String entry : limiter.names) { + result = result + entry + "/"; + } + } + return result; + } + + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/Limiter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/Limiter.java new file mode 100644 index 0000000..139be6e --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/Limiter.java @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import java.io.Serializable; + +/** + * Limiter is a constraint for MediaAdapter and FileSystemAdapter used when + * a row is "expanded". + */ +public class Limiter implements Serializable { + private static final long serialVersionUID = -4729694243900202614L; + + /** + * The type of the limiter. One of MediaUtils.TYPE_ARTIST, TYPE_ALBUM, + * TYPE_GENRE, or TYPE_FILE. + */ + public final int type; + /** + * Each element will be given a separate view each representing a higher + * different limiters. The first element is the broadest limiter, the last + * the most specific. For example, an album limiter would look like: + * { "Some Artist", "Some Album" } + * Or a file limiter: + * { "sdcard", "Music", "folder" } + */ + public final String[] names; + /** + * The data for the limiter. This varies according to the type of the + * limiter. + */ + public final Object data; + + /** + * Create a limiter with the given data. All parameters initialize their + * corresponding fields in the class. + */ + public Limiter(int type, String[] names, Object data) + { + this.type = type; + this.names = names; + this.data = data; + } +}
\ No newline at end of file diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ListPreferenceSummary.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ListPreferenceSummary.java new file mode 100644 index 0000000..6196457 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ListPreferenceSummary.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.preference.ListPreference; +import android.util.AttributeSet; + +/** + * Overrides ListPreference to show the selected value as the summary. + * + * (ListPreference should supposedly be able to do this itself if %s is in the + * summary, but as far as I can tell that behavior is broken.) + */ +public class ListPreferenceSummary extends ListPreference { + public ListPreferenceSummary(Context context, AttributeSet attrs) + { + super(context, attrs); + } + + @Override + public CharSequence getSummary() + { + return getEntry(); + } + + @Override + public boolean shouldDisableDependents() + { + return getValue().equals("0"); + } + + @Override + protected void onDialogClosed(boolean positiveResult) + { + super.onDialogClosed(positiveResult); + notifyDependencyChange(shouldDisableDependents()); + notifyChanged(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/MediaAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaAdapter.java new file mode 100644 index 0000000..042934a --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaAdapter.java @@ -0,0 +1,783 @@ +/* + * Copyright (C) 2015-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.database.DatabaseUtils; +import android.provider.BaseColumns; +import android.provider.MediaStore; +import android.text.format.DateUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.SectionIndexer; + +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.regex.Pattern; +import java.util.ArrayList; +import java.lang.StringBuilder; + + +/** + * MediaAdapter provides an adapter backed by a MediaStore content provider. + * It generates simple one- or two-line text views to display each media + * element. + * + * Filtering is supported, as is a more specific type of filtering referred to + * as limiting. Limiting is separate from filtering; a new filter will not + * erase an active filter. Limiting is intended to allow only media belonging + * to a specific group to be displayed, e.g. only songs from a certain artist. + * See getLimiter and setLimiter for details. + */ +public class MediaAdapter + extends SortableAdapter + implements LibraryAdapter + , View.OnClickListener + , SectionIndexer +{ + private static final Pattern SPACE_SPLIT = Pattern.compile("\\s+"); + /** + * The string to use for length==0 db fields + */ + private static final String DB_NULLSTRING_FALLBACK = "?"; + /** + * A context to use. + */ + private final Context mContext; + /** + * The library activity to use. + */ + private final LibraryActivity mActivity; + /** + * A LayoutInflater to use. + */ + private final LayoutInflater mInflater; + /** + * The current data. + */ + private Cursor mCursor; + /** + * The type of media represented by this adapter. Must be one of the + * MediaUtils.FIELD_* constants. Determines which content provider to query for + * media and what fields to display. + */ + private final int mType; + /** + * The table / view to use for this query + */ + private String mSource; + /** + * The fields to use from the content provider. The last field will be + * displayed in the MediaView, as will the first field if there are + * multiple fields. Other fields will be used for searching. + */ + private String[] mFields; + /** + * The collation keys corresponding to each field. If provided, these are + * used to speed up sorting and filtering. + */ + private String[] mFieldKeys; + /** + * The columns to query from the content provider. + */ + private String[] mProjection; + /** + * A limiter is used for filtering. The intention is to restrict items + * displayed in the list to only those of a specific artist or album, as + * selected through an expander arrow in a broader MediaAdapter list. + */ + private Limiter mLimiter; + /** + * The constraint used for filtering, set by the search box. + */ + private String mConstraint; + /** + * An array ORDER BY expressions for each sort mode. %1$s is replaced by + * ASC or DESC as appropriate before being passed to the query. + */ + private String[] mAdapterSortValues; + /** + * If true, show the expander button on each row. + */ + private boolean mExpandable; + /** + * Defines the media type to use for this entry + * Setting this to MediaUtils.TYPE_INVALID disables cover artwork + */ + private int mCoverCacheType; + /** + * Alphabet to be used for {@link SectionIndexer}. Populated in {@link #buildAlphabet()}. + */ + private List<SectionIndex> mAlphabet = new ArrayList<>(512); + + /** + * Construct a MediaAdapter representing the given <code>type</code> of + * media. + * + * @param context The Context used to access the content model. + * @param type The type of media to represent. Must be one of the + * MediaUtils.TYPE_* constants. This determines which content provider to query + * and what fields to display in the views. + * @param limiter An initial limiter to use + * @param activity The LibraryActivity that will contain this adapter - may be null + * + */ + public MediaAdapter(Context context, int type, Limiter limiter, LibraryActivity activity) + { + mContext = context; + mActivity = activity; + mType = type; + mLimiter = limiter; + + if (mActivity != null) { + mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } else { + mInflater = null; // not running inside an activity + } + + // Use media type + base id as cache key combination + mCoverCacheType = mType; + String coverCacheKey = BaseColumns._ID; + + switch (type) { + case MediaUtils.TYPE_ARTIST: + mSource = MediaLibrary.VIEW_ARTISTS; + mFields = new String[] { MediaLibrary.ContributorColumns.ARTIST }; + mFieldKeys = new String[] { MediaLibrary.ContributorColumns.ARTIST_SORT }; + mSortEntries = new int[] { R.string.title, R.string.date_added }; + mAdapterSortValues = new String[] { MediaLibrary.ContributorColumns.ARTIST_SORT+" %1$s", MediaLibrary.ContributorColumns.MTIME+" %1$s" }; + break; + case MediaUtils.TYPE_ALBARTIST: + mSource = MediaLibrary.VIEW_ALBUMARTISTS; + mFields = new String[] { MediaLibrary.ContributorColumns.ALBUMARTIST }; + mFieldKeys = new String[] { MediaLibrary.ContributorColumns.ALBUMARTIST_SORT }; + mSortEntries = new int[] { R.string.title, R.string.date_added }; + mAdapterSortValues = new String[] { MediaLibrary.ContributorColumns.ALBUMARTIST_SORT+" %1$s", MediaLibrary.ContributorColumns.MTIME+" %1$s" }; + break; + case MediaUtils.TYPE_COMPOSER: + mSource = MediaLibrary.VIEW_COMPOSERS; + mFields = new String[] { MediaLibrary.ContributorColumns.COMPOSER }; + mFieldKeys = new String[] { MediaLibrary.ContributorColumns.COMPOSER_SORT }; + mSortEntries = new int[] { R.string.title, R.string.date_added }; + mAdapterSortValues = new String[] { MediaLibrary.ContributorColumns.COMPOSER_SORT+" %1$s", MediaLibrary.ContributorColumns.MTIME+" %1$s" }; + break; + case MediaUtils.TYPE_ALBUM: + mSource = MediaLibrary.VIEW_ALBUMS_ARTISTS; + mFields = new String[] { MediaLibrary.AlbumColumns.ALBUM, MediaLibrary.ContributorColumns.ARTIST, MediaLibrary.SongColumns.DURATION }; + mFieldKeys = new String[] { MediaLibrary.AlbumColumns.ALBUM_SORT, MediaLibrary.ContributorColumns.ARTIST_SORT }; + mSortEntries = new int[] { R.string.title, R.string.artist_album, R.string.year, R.string.date_added, R.string.duration }; + mAdapterSortValues = new String[] { MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s", + MediaLibrary.ContributorColumns.ARTIST_SORT+" %1$s,"+MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s", + MediaLibrary.AlbumColumns.PRIMARY_ALBUM_YEAR+" %1$s", MediaLibrary.AlbumColumns.MTIME+" %1$s", + MediaLibrary.SongColumns.DURATION+" %1$s" }; + break; + case MediaUtils.TYPE_SONG: + mSource = MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS; + mFields = new String[] { MediaLibrary.SongColumns.TITLE, MediaLibrary.AlbumColumns.ALBUM, MediaLibrary.ContributorColumns.ARTIST, MediaLibrary.SongColumns.DURATION }; + mFieldKeys = new String[] { MediaLibrary.SongColumns.TITLE_SORT, MediaLibrary.AlbumColumns.ALBUM_SORT, MediaLibrary.ContributorColumns.ARTIST_SORT, null }; + mSortEntries = new int[] { R.string.title, R.string.artist_album_track, R.string.artist_album_title, R.string.album_track, R.string.year, R.string.date_added, + R.string.song_playcount, R.string.filename, R.string.duration }; + mAdapterSortValues = new String[] { MediaLibrary.SongColumns.TITLE_SORT+" %1$s", + MediaLibrary.ContributorColumns.ARTIST_SORT+" %1$s,"+MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s,"+MediaLibrary.SongColumns.DISC_NUMBER+","+MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.ContributorColumns.ARTIST_SORT+" %1$s,"+MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s,"+MediaLibrary.SongColumns.TITLE_SORT+" %1$s", + MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s,"+MediaLibrary.SongColumns.DISC_NUMBER+","+MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.SongColumns.YEAR+" %1$s,"+MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s,"+MediaLibrary.SongColumns.DISC_NUMBER+","+MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.SongColumns.MTIME+" %1$s,"+MediaLibrary.SongColumns.DISC_NUMBER+","+MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.SongColumns.PLAYCOUNT+" %1$s,"+MediaLibrary.SongColumns.DISC_NUMBER+","+MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.SongColumns.PATH+" %1$s", + MediaLibrary.SongColumns.DURATION+" %1$s", + }; + // Songs covers are cached per-album + mCoverCacheType = MediaUtils.TYPE_ALBUM; + coverCacheKey = MediaStore.Audio.Albums.ALBUM_ID; + break; + case MediaUtils.TYPE_PLAYLIST: + mSource = MediaLibrary.VIEW_PLAYLISTS; + mFields = new String[] { MediaLibrary.PlaylistColumns.NAME, MediaLibrary.SongColumns.DURATION }; + mFieldKeys = new String[] { MediaLibrary.PlaylistColumns.NAME_SORT }; + mSortEntries = new int[] { R.string.title, R.string.date_added, R.string.duration }; + mAdapterSortValues = new String[] { MediaLibrary.PlaylistColumns.NAME_SORT+" %1$s", MediaLibrary.PlaylistColumns._ID+" %1$s", + MediaLibrary.SongColumns.DURATION+" %1$s" }; + mExpandable = true; + break; + case MediaUtils.TYPE_GENRE: + mSource = MediaLibrary.TABLE_GENRES; + mFields = new String[] { MediaLibrary.GenreColumns._GENRE }; + mFieldKeys = new String[] { MediaLibrary.GenreColumns._GENRE_SORT }; + mSortEntries = new int[] { R.string.title }; + mAdapterSortValues = new String[] { MediaLibrary.GenreColumns._GENRE_SORT+" %1$s" }; + break; + default: + throw new IllegalArgumentException("Invalid value for type: " + type); + } + + + mProjection = new String[mFields.length + 2]; + mProjection[0] = BaseColumns._ID; + mProjection[1] = coverCacheKey; + for (int i = 0; i < mFields.length; i++) { + mProjection[i + 2] = mFields[i]; + } + } + + /** + * Returns first sort column for this adapter. Ensure {@link #mSortMode} is correctly set + * prior to calling this. + * + * @return string representing sort column to be used in projection. + * If the column is binary, returns its human-readable counterpart instead. + */ + private String getFirstSortColumn() { + int mode = mSortMode < 0 ? ~mSortMode : mSortMode; // get current sort mode + String column = SPACE_SPLIT.split(mAdapterSortValues[mode])[0]; + if(column.endsWith("_sort")) { // we want human-readable string, not machine-composed + column = column.substring(0, column.length() - 5); + } + + return column; + } + + /** + * Set whether or not the expander button should be shown in each row. + * Defaults to true for playlist adapter and false for all others. + * + * @param expandable True to show expander, false to hide. + */ + public void setExpandable(boolean expandable) + { + if (expandable != mExpandable) { + mExpandable = expandable; + notifyDataSetChanged(); + } + } + + @Override + public void setFilter(String filter) + { + mConstraint = filter; + } + + /** + * Build the query to be run with runQuery(). + * + * @param projection The columns to query. + * @param returnSongs return songs instead of mType if true. + */ + private QueryTask buildQuery(String[] projection, boolean returnSongs) { + String source = mSource; + String constraint = mConstraint; + Limiter limiter = mLimiter; + + StringBuilder selection = new StringBuilder(); + String[] selectionArgs = null; + String[] enrichedProjection = projection; + + // Assemble the sort string as requested by the user + int mode = getSortModeIndex(); + String sortDir = isSortDescending() ? "DESC" : "ASC"; + + // Fetch current sorting mode and sort by disc+track if we are going to look up the songs table + String sortRaw = mAdapterSortValues[mode]; + if (returnSongs) { + // songs returned from the artist tab should also sort by album + if (mType == MediaUtils.TYPE_ARTIST) // fixme: composer? + sortRaw += ", "+MediaLibrary.AlbumColumns.ALBUM_SORT+" %1$s"; + // and this is for all types: + sortRaw += ", "+MediaLibrary.SongColumns.DISC_NUMBER+", "+MediaLibrary.SongColumns.SONG_NUMBER; + } + + // ...and assemble the SQL string we are really going to use + String sort = String.format(sortRaw, sortDir); + + // include the constraint (aka: search string) if any + if (constraint != null && constraint.length() != 0) { + String colKey = MediaLibrary.keyFor(constraint); + String spaceColKey = DatabaseUtils.getCollationKey(" "); + String[] needles = colKey.split(spaceColKey); + String[] keySource = mFieldKeys; + + int size = needles.length; + selectionArgs = new String[size]; + + StringBuilder keys = new StringBuilder(20); + keys.append(keySource[0]); + for (int j = 1; j != keySource.length; ++j) { + String src = keySource[j]; + if (src != null) { + keys.append("||"); + keys.append(src); + } + } + + for (int j = 0; j != needles.length; ++j) { + selectionArgs[j] = '%' + needles[j] + '%'; + + // If we have something in the selection args (i.e. j > 0), we + // must have something in the selection, so we can skip the more + // costly direct check of the selection length. + if (j != 0 || selection.length() != 0) + selection.append(" AND "); + selection.append(keys); + selection.append(" LIKE ?"); + } + } + + if (limiter != null) { + if (selection.length() != 0) { + selection.append(" AND "); + } + selection.append(limiter.data); + } + + if (returnSongs == true) { + source = MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS_HUGE; + } else { + enrichedProjection = Arrays.copyOf(projection, projection.length + 1); + enrichedProjection[projection.length] = getFirstSortColumn(); + } + + QueryTask query = new QueryTask(source, enrichedProjection, selection.toString(), selectionArgs, sort); + return query; + } + + @Override + public Cursor query() + { + return buildQuery(mProjection, false).runQuery(mContext); + } + + @Override + public void commitQuery(Object data) + { + changeCursor((Cursor)data); + } + + /** + * Build a query for all the songs represented by this adapter, for adding + * to the timeline. + * + * @param projection The columns to query. + */ + @Override + public QueryTask buildSongQuery(String[] projection) + { + QueryTask query = buildQuery(projection, true); + query.type = mType; + return query; + } + + @Override + public void clear() + { + changeCursor(null); + } + + @Override + public int getMediaType() + { + return mType; + } + + @Override + public void setLimiter(Limiter limiter) + { + mLimiter = limiter; + } + + @Override + public Limiter getLimiter() + { + return mLimiter; + } + + @Override + public Limiter buildLimiter(long id) + { + String[] fields; + Object data; + + Cursor cursor = mCursor; + if (cursor == null) + return null; + for (int i = 0, count = cursor.getCount(); i != count; ++i) { + cursor.moveToPosition(i); + if (cursor.getLong(0) == id) + break; + } + + switch (mType) { + case MediaUtils.TYPE_ARTIST: + fields = new String[] { cursor.getString(2) }; + data = String.format("%s=%d", MediaLibrary.ContributorColumns.ARTIST_ID, id); + break; + case MediaUtils.TYPE_ALBARTIST: + fields = new String[] { cursor.getString(2) }; + data = String.format("%s=%d", MediaLibrary.ContributorColumns.ALBUMARTIST_ID, id); + break; + case MediaUtils.TYPE_COMPOSER: + fields = new String[] { cursor.getString(2) }; + data = String.format("%s=%d", MediaLibrary.ContributorColumns.COMPOSER_ID, id); + break; + case MediaUtils.TYPE_ALBUM: + fields = new String[] { cursor.getString(3), cursor.getString(2) }; + data = String.format("%s=%d", MediaLibrary.SongColumns.ALBUM_ID, id); + break; + case MediaUtils.TYPE_GENRE: + fields = new String[] { cursor.getString(2) }; + data = String.format("%s=%d", MediaLibrary.GenreSongColumns._GENRE_ID, id); + break; + default: + throw new IllegalStateException("getLimiter() is not supported for media type: " + mType); + } + + return new Limiter(mType, fields, data); + } + + /** + * Set a new cursor for this adapter. The old cursor will be closed. + * + * @param cursor The new cursor. + */ + public void changeCursor(Cursor cursor) + { + Cursor old = mCursor; + mCursor = cursor; + buildAlphabet(); + if (cursor == null) { + notifyDataSetInvalidated(); + } else { + notifyDataSetChanged(); + } + if (old != null) { + old.close(); + } + } + + @Override + public View getView(int position, View convertView, ViewGroup parent) + { + DraggableRow row; + ViewHolder holder; + + if (convertView == null) { + // We must create a new view if we're not given a recycle view or + // if the recycle view has the wrong layout. + row = (DraggableRow)mInflater.inflate(R.layout.draggable_row, parent, false); + row.setupLayout(DraggableRow.LAYOUT_LISTVIEW); + + holder = new ViewHolder(); + row.setTag(holder); + + row.setDraggerOnClickListener(this); + row.showDragger(mExpandable); + } else { + row = (DraggableRow)convertView; + holder = (ViewHolder)row.getTag(); + } + + Cursor cursor = mCursor; + cursor.moveToPosition(position); + + long id = cursor.getLong(0); + long cacheId = cursor.getLong(1); + String title = cursor.getString(2); + String subtitle = null; + long duration = -1; + + // Title is never null, subtitle may be depending on the type. + title = (title == null ? DB_NULLSTRING_FALLBACK : title); + + // Add subtitle if media type has one. + switch (mType) { + case MediaUtils.TYPE_ALBUM: + case MediaUtils.TYPE_SONG: + subtitle = cursor.getString(3); + subtitle = (subtitle == null ? DB_NULLSTRING_FALLBACK : subtitle); + + // Add album information for songs. + String subsub = (mType == MediaUtils.TYPE_SONG ? cursor.getString(4) : null); + subtitle += (subsub != null ? " · " + subsub : ""); + break; + } + + // Pick up duration + switch (mType) { + case MediaUtils.TYPE_ALBUM: + duration = cursor.getLong(4); + break; + case MediaUtils.TYPE_SONG: + duration = cursor.getLong(5); + break; + case MediaUtils.TYPE_PLAYLIST: + duration = cursor.getLong(3); + break; + } + + holder.id = id; + holder.title = title; + + if (subtitle == null) { + row.setText(title); + } else { + row.setText(title, subtitle); + } + row.showDuration(duration != -1); + row.setDuration(duration); + row.getCoverView().setCover(mCoverCacheType, cacheId, holder.title); + return row; + } + + /** + * Returns the type of the current limiter. + * + * @return One of MediaUtils.TYPE_, or MediaUtils.TYPE_INVALID if there is + * no limiter set. + */ + public int getLimiterType() + { + Limiter limiter = mLimiter; + if (limiter != null) + return limiter.type; + return MediaUtils.TYPE_INVALID; + } + + /** + * {@inheritDoc} + */ + @Override + public int getDefaultSortMode() + { + int type = mType; + if (type == MediaUtils.TYPE_ALBUM || type == MediaUtils.TYPE_SONG) + return 1; // aritst,album,track + return 0; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSortSettingsKey() { + return String.format("sort_%d_%d", getMediaType(), getLimiterType()); + } + + /** + * Creates an intent to dispatch + */ + @Override + public Intent createData(View view) + { + ViewHolder holder = (ViewHolder)view.getTag(); + Intent intent = new Intent(); + intent.putExtra(LibraryAdapter.DATA_TYPE, mType); + intent.putExtra(LibraryAdapter.DATA_ID, holder.id); + intent.putExtra(LibraryAdapter.DATA_TITLE, holder.title); + intent.putExtra(LibraryAdapter.DATA_EXPANDABLE, mExpandable); + return intent; + } + + /** + * Callback of array clicks (item clicks are handled in LibraryPagerAdapter) + */ + @Override + public void onClick(View view) + { + int id = view.getId(); + view = (View)view.getParent(); // get view of linear layout, not the click consumer + Intent intent = createData(view); + mActivity.onItemExpanded(intent); + } + + @Override + public int getCount() + { + Cursor cursor = mCursor; + if (cursor == null) + return 0; + return cursor.getCount(); + } + + @Override + public Object getItem(int position) + { + return null; + } + + @Override + public long getItemId(int position) + { + Cursor cursor = mCursor; + if (cursor == null || cursor.getCount() == 0) + return 0; + cursor.moveToPosition(position); + return cursor.getLong(0); + } + + @Override + public boolean hasStableIds() + { + return true; + } + + /** + * Helper class for building an alphabet. + * Contains a hint that is shown in fast scroll thumb popup and a position where this hint + * has appeared first. + */ + private class SectionIndex + { + + public SectionIndex(Object hint, int position) { + this.hint = hint; + this.position = position; + } + + private Object hint; + private int position; + + @Override + public String toString() { + return String.valueOf(hint); + } + } + + /** + * Build alphabet for fast-scroller. Detects automatically whether we're sorting + * on string-type (e.g. title or album) or integer type (e.g. year). + * + * <p/>Alphabet building is only performed if applicable, i.e. magic playcount sort + * or sort by date added will yield no results as the section hints would not be + * human-readable. + * + * <p/>Note: This clears alphabet in case current cursor is invalid. + */ + private void buildAlphabet() + { + mAlphabet.clear(); + + Cursor cursor = mCursor; + if(cursor == null || cursor.getCount() == 0) { + return; + } + + String columnName = getFirstSortColumn(); + int sortColumnIndex = cursor.getColumnIndex(columnName); + if(sortColumnIndex <= 0) { + // either projection doesn't contain this column + // or the column is _id (e.g. sort by date added), + // no point in building + return; + } + + cursor.moveToFirst(); + + SimpleDateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd"); + String lastString = null; + Object lastKnown = null; + Object next; + do { + int type = cursor.getType(sortColumnIndex); + switch (type) { + case Cursor.FIELD_TYPE_NULL: + next = DB_NULLSTRING_FALLBACK; + break; + case Cursor.FIELD_TYPE_INTEGER: + int value = cursor.getInt(sortColumnIndex); + if (columnName.equals(MediaLibrary.SongColumns.MTIME)) { + next = dfmt.format(new Date(value * 1000L)); + } else if (columnName.equals(MediaLibrary.SongColumns.DURATION)) { + next = DateUtils.formatElapsedTime(value / 1000); + } else { + next = value; + } + break; + case Cursor.FIELD_TYPE_STRING: + lastString = cursor.getString(sortColumnIndex); + lastString = lastString.trim().toUpperCase(); // normalize + + // This is what AOSP's MediaStore.java:1337 does during indexing + if (lastString.startsWith("THE ")) + lastString = lastString.substring(4); + + if (lastString.startsWith("AN ")) + lastString = lastString.substring(3); + + if (lastString.startsWith("A ")) + lastString = lastString.substring(2); + + // Ensure that we got at least one char + if (lastString.length() < 1) + lastString = DB_NULLSTRING_FALLBACK; + + next = lastString.charAt(0); + break; + default: + continue; + } + if (!next.equals(lastKnown)) { // new char + mAlphabet.add(new SectionIndex(next, cursor.getPosition())); + lastKnown = next; + } + } while (cursor.moveToNext()); + } + + @Override + public Object[] getSections() + { + return mAlphabet.toArray(new SectionIndex[mAlphabet.size()]); + } + + @Override + public int getPositionForSection(int sectionIndex) + { + // clip to start + if(sectionIndex < 0) { + return 0; + } + + // clip to end + if(sectionIndex >= mAlphabet.size()) { + return mCursor.getCount() - 1; + } + + return mAlphabet.get(sectionIndex).position; + } + + @Override + public int getSectionForPosition(int position) + { + for(int i = 0; i < mAlphabet.size(); ++i) { + if(mAlphabet.get(i).position > position) + return i - 1; + } + return 0; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/MediaButtonReceiver.java b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaButtonReceiver.java new file mode 100644 index 0000000..00c2071 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaButtonReceiver.java @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.SystemClock; +import android.os.Handler; +import android.view.KeyEvent; + +/** + * Receives media button events and calls to PlaybackService to respond + * appropriately. + * + * Most of this logic is only needed for RemoteControlImplICS (like double-click) + * as >= LP devices handle this using the MediaSessionCompat. + */ +public class MediaButtonReceiver extends BroadcastReceiver { + /** + * If another button event is received before this time in milliseconds + * expires, the event with be considered a double click. + */ + private static final int DOUBLE_CLICK_DELAY = 600; + + /** + * Time of the last play/pause click. Used to detect double-clicks. + */ + private static long sLastClickTime = 0; + + /** + * Process a media button key press. + * + * @param context A context to use. + * @param event The key press event. + * @return True if the event was handled and the broadcast should be + * aborted. + */ + public static boolean processKey(Context context, KeyEvent event) + { + if (event == null) + return false; + + int action = event.getAction(); + String act = null; + + switch (event.getKeyCode()) { + case KeyEvent.KEYCODE_HEADSETHOOK: + case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: + // single click: pause/resume. + // double click: next track + // triple click: previous track + if (action == KeyEvent.ACTION_DOWN) { + long time = SystemClock.uptimeMillis(); + if (time - sLastClickTime < DOUBLE_CLICK_DELAY) { + Handler handler = new Handler(); + DelayedClickCounter dcc = new DelayedClickCounter(context, time); + handler.postDelayed(dcc, DOUBLE_CLICK_DELAY); + } else { + act = PlaybackService.ACTION_TOGGLE_PLAYBACK; + } + sLastClickTime = time; + } + break; + case KeyEvent.KEYCODE_MEDIA_NEXT: + if (action == KeyEvent.ACTION_DOWN) + act = PlaybackService.ACTION_NEXT_SONG_AUTOPLAY; + break; + case KeyEvent.KEYCODE_MEDIA_PREVIOUS: + if (action == KeyEvent.ACTION_DOWN) + act = PlaybackService.ACTION_PREVIOUS_SONG_AUTOPLAY; + break; + case KeyEvent.KEYCODE_MEDIA_PLAY: + if (action == KeyEvent.ACTION_DOWN) + act = PlaybackService.ACTION_PLAY; + break; + case KeyEvent.KEYCODE_MEDIA_PAUSE: + case KeyEvent.KEYCODE_MEDIA_STOP: + // We will behave the same as Google Play Music: for "Stop" we unconditionally Pause instead + if (action == KeyEvent.ACTION_DOWN) + act = PlaybackService.ACTION_PAUSE; + break; + default: + return false; + } + + runAction(context, act); + return true; + } + + + /** + * Passes an action to PlaybackService + * + * @param context the context to use + * @param act the action to pass on + */ + private static void runAction(Context context, String act) { + if (act == null) + return; + + Intent intent = new Intent(context, PlaybackService.class) + .setAction(act) + .putExtra(PlaybackService.EXTRA_FORCE_NOTIFICATION, true) + .putExtra(PlaybackService.EXTRA_EARLY_NOTIFICATION, true); + context.startForegroundService(intent); + } + + + /** + * Runable to run a delayed action + * Inspects sLastClickTime and sDelayedClicks to guess what to do + * Note: this is only used on pre-lolipop devices. + * + * @param context the context to use + * @param serial the value of sLastClickTime during creation, used to identify stale events + */ + private static class DelayedClickCounter implements Runnable { + private Context mContext; + private long mSerial; + private static int sDelayedClicks; + + public DelayedClickCounter(Context context, long serial) { + mContext = context; + mSerial = serial; + } + + @Override + public void run() { + sDelayedClicks++; + if (mSerial != sLastClickTime) + return; // just count the click, don't fire. + + String act = null; + switch (sDelayedClicks) { + case 1: + act = PlaybackService.ACTION_NEXT_SONG_AUTOPLAY; + break; + default: + act = PlaybackService.ACTION_PREVIOUS_SONG_AUTOPLAY; + } + sDelayedClicks = 0; + runAction(mContext, act); + } + } + + + + @Override + public void onReceive(Context context, Intent intent) + { + if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { + KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); + boolean handled = processKey(context, event); + if (handled && isOrderedBroadcast()) + abortBroadcast(); + } + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/MediaFoldersSelectionActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaFoldersSelectionActivity.java new file mode 100644 index 0000000..5d04280 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaFoldersSelectionActivity.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.app.Activity; +import android.os.Bundle; +import android.content.SharedPreferences; + +import java.io.File; +import java.util.ArrayList; + +public class MediaFoldersSelectionActivity extends FolderPickerActivity { + + private SharedPreferences.Editor mPrefEditor; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setTitle(R.string.media_folders_header); + + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(this); + File startPath = FileUtils.getFilesystemBrowseStart(this); + + // Setup UI and enable tritastic options. + enableTritasticSelect(true, prefs.mediaFolders, prefs.blacklistedFolders); + enableTritasticSpinner(true); + // ...and jump to the folder. + setCurrentDir(startPath); + } + + + @Override + public void onFolderPicked(File directory, ArrayList<String> included, ArrayList<String> excluded) { + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(this); + prefs.mediaFolders = included; + prefs.blacklistedFolders = excluded; + MediaLibrary.setPreferences(this, prefs); + finish(); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/MediaSessionTracker.java b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaSessionTracker.java new file mode 100644 index 0000000..4660f1d --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaSessionTracker.java @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2021 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.graphics.Bitmap; +import android.support.v4.media.session.MediaSessionCompat; +import android.support.v4.media.session.PlaybackStateCompat; +import android.support.v4.media.MediaMetadataCompat; +import android.view.KeyEvent; + +/** + * Manages our active media session which is responsible for keeping + * the notification seek bar up to date and handling key events. + */ +public class MediaSessionTracker { + /** + * Context we are working with. + */ + private Context mContext; + /** + * Our generic MediaSession + */ + private MediaSessionCompat mMediaSession; + + + MediaSessionTracker(Context context) { + mContext = context; + mMediaSession = new MediaSessionCompat(mContext, "Vanilla Music Media Session"); + mMediaSession.setCallback(new MediaSessionCompat.Callback() { + @Override + public void onPause() { + MediaButtonReceiver.processKey(mContext, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); + } + @Override + public void onPlay() { + MediaButtonReceiver.processKey(mContext, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); + } + @Override + public void onSkipToNext() { + MediaButtonReceiver.processKey(mContext, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT)); + } + @Override + public void onSkipToPrevious() { + MediaButtonReceiver.processKey(mContext, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS)); + } + @Override + public void onStop() { + // We will behave the same as Google Play Music: for "Stop" we unconditionally Pause instead + MediaButtonReceiver.processKey(mContext, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE)); + } + @Override + public void onSeekTo(long pos) { + PlaybackService.get(mContext).seekToPosition((int)pos); + }}); + mMediaSession.setActive(true); + } + + /** + * Returns the session token of the media session. + */ + public MediaSessionCompat.Token getSessionToken() { + return mMediaSession.getSessionToken(); + } + + /** + * Cleans up the underlying media session + */ + public void release() { + mMediaSession.setActive(false); + mMediaSession.release(); + } + + /** + * Populates the active media session with new info. + * + * @param song The song containing the new metadata. + * @param state PlaybackService state, used to determine playback state. + */ + public void updateSession(Song song, int state) { + final boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + final PlaybackService service = PlaybackService.get(mContext); + + PlaybackStateCompat playbackState = new PlaybackStateCompat.Builder() + .setState(playing ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED, + service.getPosition(), 1.0f) + .setActions(PlaybackStateCompat.ACTION_PLAY | + PlaybackStateCompat.ACTION_STOP | + PlaybackStateCompat.ACTION_PAUSE | + PlaybackStateCompat.ACTION_PLAY_PAUSE | + PlaybackStateCompat.ACTION_SEEK_TO | + PlaybackStateCompat.ACTION_SKIP_TO_NEXT | + PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) + .build(); + + if (song != null) { + final Bitmap cover = song.getMediumCover(mContext); + MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder() + .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artist) + .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.album) + .putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title) + .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.duration); + + boolean showCover = SharedPrefHelper.getSettings(mContext).getBoolean(PrefKeys.COVER_ON_LOCKSCREEN, PrefDefaults.COVER_ON_LOCKSCREEN); + if (showCover) { + metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, cover); + } + + // logic copied from FullPlaybackActivity.updateQueuePosition() + if (PlaybackService.finishAction(service.getState()) != SongTimeline.FINISH_RANDOM) { + metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, service.getTimelinePosition() + 1); + metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, service.getTimelineLength()); + } + mMediaSession.setMetadata(metadataBuilder.build()); + } + + mMediaSession.setPlaybackState(playbackState); + mMediaSession.setActive(true); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/MediaUtils.java b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaUtils.java new file mode 100644 index 0000000..18aff3b --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/MediaUtils.java @@ -0,0 +1,675 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2017-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; +import ch.blinkenlights.android.medialibrary.MediaMetadataExtractor; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import android.util.Log; + +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; +import android.os.Environment; +import android.provider.MediaStore; +import android.database.MatrixCursor; +import android.widget.Toast; + +import androidx.core.content.FileProvider; + + +/** + * Provides some static Song/MediaStore-related utility functions. + */ +public class MediaUtils { + /** + * A special invalid media type. + */ + public static final int TYPE_INVALID = -1; + /** + * Type indicating an id represents an artist. + */ + public static final int TYPE_ARTIST = 0; + /** + * Type indicating an id represents an album. + */ + public static final int TYPE_ALBUM = 1; + /** + * Type indicating an id represents a song. + */ + public static final int TYPE_SONG = 2; + /** + * Type indicating an id represents a playlist. + */ + public static final int TYPE_PLAYLIST = 3; + /** + * Type indicating ids represent genres. + */ + public static final int TYPE_GENRE = 4; + /** + * Type indicating an id represents an albumartist + */ + public static final int TYPE_ALBARTIST = 5; + /** + * Type indicating an id represents a composer + */ + public static final int TYPE_COMPOSER = 6; + /** + * Special type for files and folders. Most methods do not accept this type + * since files have no MediaStore id and require special handling. + */ + public static final int TYPE_FILE = 7; + /** + * The number of different valid media types. + */ + public static final int TYPE_COUNT = 8; + + /** + * The default sort order for media queries. First artist, then album, then + * song number. + */ + private static final String DEFAULT_SORT = "artist_sort,album_sort,disc_num,song_num"; + + /** + * The default sort order for albums. First the album, then songnumber + */ + private static final String ALBUM_SORT = "album_sort,disc_num,song_num"; + + /** + * The default sort order for files. Simply use the path + */ + private static final String FILE_SORT = "path"; + + /** + * The number of files that are added when "play all" selects + * files from the file-system. + */ + private static final int MAX_QUEUED_FILES = 500; + + /** + * Cached random instance. + */ + private static Random sRandom; + + /** + * Shuffled list of all songs in the library. + */ + private static ArrayList<Song> sAllSongs = new ArrayList<Song>(); + /** + * True if sAllSongs was shuffled by album. + */ + private static boolean sAllSongsAS; + + /** + * Total number of songs in the music library, or -1 for uninitialized. + */ + private static int sSongCount = -1; + + /** + * Returns a cached random instanced, creating it if necessary. + */ + public static Random getRandom() + { + if (sRandom == null) + sRandom = new Random(); + return sRandom; + } + + /** + * Builds a query that will return all the songs represented by the given + * parameters. + * + * @param type MediaUtils.TYPE_ARTIST, TYPE_ALBUM, or TYPE_SONG. + * @param id The MediaStore id of the song, artist, or album. + * @param projection The columns to query. + * @param select An extra selection to pass to the query, or null. + * @return The initialized query. + */ + private static QueryTask buildMediaQuery(int type, long id, String[] projection, String select) + { + StringBuilder selection = new StringBuilder(); + String sort = DEFAULT_SORT; + + if (select != null) { + selection.append(select); + selection.append(" AND "); + } + + switch (type) { + case TYPE_SONG: + selection.append(MediaLibrary.SongColumns._ID); + break; + case TYPE_ARTIST: + selection.append(MediaLibrary.ContributorColumns.ARTIST_ID); + break; + case TYPE_ALBARTIST: + selection.append(MediaLibrary.ContributorColumns.ALBUMARTIST_ID); + break; + case TYPE_COMPOSER: + selection.append(MediaLibrary.ContributorColumns.COMPOSER_ID); + break; + case TYPE_ALBUM: + selection.append(MediaLibrary.SongColumns.ALBUM_ID); + sort = ALBUM_SORT; + break; + case TYPE_GENRE: + selection.append(MediaLibrary.GenreSongColumns._GENRE_ID); + break; + default: + throw new IllegalArgumentException("Invalid type specified: " + type); + } + + selection.append('='); + selection.append(id); + + QueryTask result = new QueryTask(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, projection, selection.toString(), null, sort); + result.type = type; + return result; + } + + /** + * Builds a query that will return all the songs in the playlist with the + * given id. + * + * @param id The id of the playlist in MediaStore.Audio.Playlists. + * @param projection The columns to query. + * @return The initialized query. + */ + public static QueryTask buildPlaylistQuery(long id, String[] projection) { + String sort = MediaLibrary.PlaylistSongColumns.POSITION; + String selection = MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"="+id; + QueryTask result = new QueryTask(MediaLibrary.VIEW_PLAYLISTS_SONGS, projection, selection, null, sort); + result.type = TYPE_PLAYLIST; + return result; + } + + /** + * Builds a query with the given information. + * + * @param type Type the id represents. Must be one of the Song.TYPE_* + * constants. + * @param id The id of the element in the MediaStore content provider for + * the given type. + * @param selection An extra selection to be passed to the query. May be + * null. Must not be used with type == TYPE_SONG or type == TYPE_PLAYLIST + */ + public static QueryTask buildQuery(int type, long id, String[] projection, String selection) + { + switch (type) { + case TYPE_ARTIST: + case TYPE_ALBARTIST: + case TYPE_COMPOSER: + case TYPE_ALBUM: + case TYPE_SONG: + case TYPE_GENRE: + return buildMediaQuery(type, id, projection, selection); + case TYPE_PLAYLIST: + return buildPlaylistQuery(id, projection); + default: + throw new IllegalArgumentException("Specified type not valid: " + type); + } + } + + /** + * Query the MediaStore to determine the id of the genre the song belongs + * to. + * + * @param context The context to use + * @param id The id of the song to query the genre for. + */ + public static long queryGenreForSong(Context context, long id) { + String[] projection = { MediaLibrary.GenreSongColumns._GENRE_ID }; + String query = MediaLibrary.GenreSongColumns.SONG_ID+"=?"; + String[] queryArgs = new String[] { Long.toString(id) }; + + Cursor cursor = MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_GENRES_SONGS, projection, query, queryArgs, null); + if (cursor != null) { + if (cursor.moveToNext()) + return cursor.getLong(0); + cursor.close(); + } + return 0; + } + + /** + * Shuffle a Song list using Collections.shuffle(). + * + * @param albumShuffle If true, preserve the order of songs inside albums. + */ + public static void shuffle(List<Song> list, boolean albumShuffle) + { + int size = list.size(); + if (size < 2) + return; + + Random random = getRandom(); + if (albumShuffle) { + List<Song> tempList = new ArrayList<Song>(list); + Collections.sort(tempList); + + // Build map of albumId to start index in sorted list + Map<Long, Integer> albumStartIndices = new HashMap<Long, Integer>(); + int index = 0; + for (Song song : tempList) { + if (!albumStartIndices.containsKey(song.albumId)) { + albumStartIndices.put(song.albumId, index); + } + index++; + } + + //Extract album list and shuffle + List<Long> shuffledAlbums = new ArrayList<Long>(albumStartIndices.keySet()); + Collections.shuffle(shuffledAlbums, random); + + //Build Song list from album list + list.clear(); + for (Long albumId : shuffledAlbums) { + int songIndex = albumStartIndices.get(albumId); + Song song = tempList.get(songIndex); + do { + list.add(song); + songIndex++; + if (songIndex < size) { + song = tempList.get(songIndex); + } else { + break; + } + } while (albumId == song.albumId); + } + } else { + Collections.shuffle(list, random); + } + } + + /** + * Determine if any songs are available from the library. + * + * @param context The Context to use + * @return True if it's possible to retrieve any songs, false otherwise. For + * example, false could be returned if there are no songs in the library. + */ + public static boolean isSongAvailable(Context context) { + if (sSongCount == -1) { + sSongCount = MediaLibrary.getLibrarySize(context); + } + + return sSongCount != 0; + } + + /** + * Returns a list containing all the songs found on the + * device's library. + * + * @param context The Context to use + */ + private static ArrayList<Song> getAllSongs(Context context) { + QueryTask query = new QueryTask(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, Song.FILLED_PROJECTION, null, null, null); + Cursor cursor = query.runQuery(context); + ArrayList<Song> list = new ArrayList<Song>(); + + if (cursor == null) + return list; + + while (cursor.moveToNext()) { + Song song = new Song(-1); + song.populate(cursor); + list.add(song); + } + cursor.close(); + return list; + } + + /** + * Called if we detected a medium change + * This flushes some cached data + */ + public static void onMediaChange() + { + sSongCount = -1; + sAllSongs.clear(); + } + + /** + * Creates and sends a share intent across the system. + * @param ctx context to execute resolving on. + * @param song the song to share. + */ + public static void shareMedia(Context ctx, Song song) { + if (song == null || song.path == null) + return; + + Uri uri = null; + try { + uri = FileProvider.getUriForFile(ctx, ctx.getApplicationContext().getPackageName() + ".fileprovider", new File(song.path)); + } catch (IllegalArgumentException e) { + Toast.makeText(ctx, R.string.share_failed, Toast.LENGTH_SHORT).show(); + } + + if (uri == null) + return; // Fileprovider failed, we can not continue. + + Intent intent = new Intent(Intent.ACTION_SEND); + intent.setType("audio/*"); + intent.putExtra(Intent.EXTRA_STREAM, uri); + try { + ctx.startActivity(Intent.createChooser(intent, ctx.getString(R.string.sendto))); + } catch (ActivityNotFoundException e) { + Toast.makeText(ctx, R.string.no_receiving_apps, Toast.LENGTH_SHORT).show(); + } + } + + /** + * Returns the first matching song (or NULL) of given type + id combination + * + * @param context A Context to use. + * @param type The MediaTye to query + * @param id The id of given type to query + */ + public static Song getSongByTypeId(Context context, int type, long id) { + Song song = new Song(-1); + QueryTask query = buildQuery(type, id, Song.FILLED_PROJECTION, null); + Cursor cursor = query.runQuery(context); + if (cursor != null) { + if (cursor.getCount() > 0) { + cursor.moveToPosition(0); + song.populate(cursor); + } + cursor.close(); + } + return song.isFilled() ? song : null; + } + + /** + * Returns a list of songs randomly selected from all the songs in the Android + * MediaStore. When albumShuffle is specified, the returned list may contain all the songs + * for that album, in order. Otherwise, only one song will be returned. If no songs are + * available, the list will be empty. + * + * @param context The Context to use + * @param albumShuffle Whether or not we should shuffle by album + */ + public static List<Song> getRandomSongs(Context context, boolean albumShuffle) { + ArrayList<Song> songs = sAllSongs; + + if (songs.size() == 0 || sAllSongsAS != albumShuffle) { + sAllSongs = getAllSongs(context); + sAllSongsAS = albumShuffle; + shuffle(sAllSongs, albumShuffle); + songs = sAllSongs; + // We don't need it but know the value, we can fill the cache for free. + sSongCount = songs.size(); + } + + final List<Song> results = new ArrayList<>(); + + if (songs.size() > 0) { + + long firstAlbumId = songs.get(0).albumId; + + // if we're in album shuffle mode, we'll want to add in the entire album in one go, + // so loop through the upcoming songs and add all those that have the same album id + // as the song we initially got + boolean addMore; + do { + final Song song = songs.remove(0); + + // when in album shuffle mode, we don't want to flag any of the added songs + // as random, since manually enqueuing or changing random mode will remove every album track. + if (!albumShuffle) { + song.flags |= Song.FLAG_RANDOM; + } + + results.add(song); + addMore = albumShuffle && songs.size() > 0 && songs.get(0).albumId == firstAlbumId; + } while (addMore); + } + + return results; + } + + /** + * Delete the given file or directory recursively. + * + * @return True if successful; false otherwise. + */ + public static boolean deleteFile(File file) + { + File[] children = file.listFiles(); + if (children != null) { + for (File child : children) { + deleteFile(child); + } + } + return file.delete(); + } + + + /** + * This is an ugly hack: The tries to 'guess' if given path + * is also accessible using a fuse mount + */ + private static String sanitizeMediaPath(String path) { + + String exPath = Environment.getExternalStorageDirectory().getAbsolutePath(); + File exStorage = new File(exPath+"/Android"); + long exLastmod = exStorage.lastModified(); + + if(exLastmod > 0 && path != null) { + String pfx = path; + while(true) { + if((new File(pfx+"/Android")).lastModified() == exLastmod) { + String guessPath = exPath + path.substring(pfx.length()); + if( (new File(guessPath)).exists() ) { + path = guessPath; + break; + } + } + + pfx = (new File(pfx)).getParent(); + if(pfx == null) + break; /* hit root */ + } + } + + return path; + } + + /** + * Adds a final slash if the path points to an existing directory + */ + private static String addDirEndSlash(String path) { + if(path.length() > 0 && path.charAt(path.length()-1) != '/') { + if( (new File(path)).isDirectory() ) { + path += "/"; + } + } + return path; + } + + /** + * Build a query that will contain all the media under the given path. + * + * @param path The path, e.g. /mnt/sdcard/music/ + * @param projection The columns to query + * @param recursive whether or not to do a LIKE search, picking up child items. + * @return The initialized query. + */ + public static QueryTask buildFileQuery(String path, String[] projection, boolean recursive) + { + // Try to detect more popular mount point: + path = sanitizeMediaPath(path); + String query = MediaLibrary.SongColumns.PATH+" = ?"; + + if (recursive) { + // This is a LIKE query: add a slash to the directory if the current path + // points to an existing one. + path = addDirEndSlash(path) + "%"; + query = MediaLibrary.SongColumns.PATH+" LIKE ?"; + } + + QueryTask result = new QueryTask(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, projection, query, new String[]{ path }, FILE_SORT); + result.type = TYPE_FILE; + return result; + } + + /** + * Returns a (possibly empty) Cursor for given file path. + * + * For directories, it recursively adds all files contained + * in this directory. + * + * @param path The path to the file to be queried + * @return A new Cursor object + * */ + public static Cursor getCursorForFileQuery(String path) { + MatrixCursor matrixCursor = new MatrixCursor(Song.FILLED_PROJECTION); + + File directory = new File(path); + if (directory.isDirectory()) { + addDirectoryToCursor(directory, matrixCursor); + } else { + addFileToCursor(path, matrixCursor); + } + + return matrixCursor; + } + + private static void addFileToCursor(String path, MatrixCursor matrixCursor) { + MediaMetadataExtractor tags = new MediaMetadataExtractor(path); + String title = tags.getFirst(MediaMetadataExtractor.TITLE); + String album = tags.getFirst(MediaMetadataExtractor.ALBUM); + String artist = tags.getFirst(MediaMetadataExtractor.ARTIST); + String duration = tags.getFirst(MediaMetadataExtractor.DURATION); + + if (duration != null) { // looks like we will be able to play this file + // Vanilla requires each file to be identified by its unique id in the media database. + // However: This file is not in the database, so we are going to roll our own + // using the negative crc32 sum of the path value. While this is not perfect + // (the same file may be accessed using various paths) it's the fastest method + // and far good enough. + long songId = MediaLibrary.hash63(path) * -1; + if (songId > -2) + songId = -2; // must be less than -1 (-1 defines an empty song object) + + // Build minimal fake-database entry for this file + Object[] objData = new Object[] { songId, path, "", "", "", 0, 0, 0, 0, 0, 0 }; + + if (title != null) + objData[2] = title; + if (album != null) + objData[3] = album; + if (artist != null) + objData[4] = artist; + if (duration != null) + objData[7] = Long.parseLong(duration, 10); + + matrixCursor.addRow(objData); + } + } + + private static void addDirectoryToCursor(File directory, MatrixCursor matrixCursor) { + File[] files = directory.listFiles(); + if (files == null) { + return; + } + + // make sure items are returned in sorted order by the cursor + Arrays.sort(files); + + for (File file : files) { + // don't add more files endlessly, but stop after + // the given maximum number of entries + if (matrixCursor.getCount() >= MAX_QUEUED_FILES) { + break; + } + + if (file.isDirectory()) { + // recurse into this sub-directory + addDirectoryToCursor(file, matrixCursor); + } else { + addFileToCursor(file.getAbsolutePath(), matrixCursor); + } + } + } + + /** + * Returns the id's used by Androids native media database for given song + * + * @param context the context to use + * @param song the song to query + * @return long { song_id, album_id, artist_id } - all set to -1 on error + */ + public static long[] getAndroidMediaIds(Context context, Song song) { + long[] result = { -1, -1, -1 }; + String[] projection = new String[]{ MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.ARTIST_ID }; + try { + Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, MediaStore.Audio.Media.DATA+"=?", new String[] { song.path }, null); + if (cursor != null) { + if (cursor.moveToFirst()) { + for (int i=0; i<result.length; i++) + result[i] = cursor.getLong(i); + } + cursor.close(); + } + } catch (SecurityException e) { + Log.e("VanillaMusic", "Wowies: No permission to read EXTERNAL_CONTENT_URI for song "+song.path+": "+e); + } + return result; + } + + /** + * Retrieve ID of specified media type for requested song. This works only for + * media-oriented types: {@link #TYPE_ARTIST}, {@link #TYPE_ALBUM}, {@link #TYPE_SONG} + * @param song requested song + * @param mType media type e.g. {@link #TYPE_ARTIST} + * @return ID of media type, {@link #TYPE_INVALID} if unsupported + */ + public static long getCurrentIdForType(Song song, int mType) + { + if(song == null) + return TYPE_INVALID; + + switch(mType) { + case TYPE_ARTIST: + return song.artistId; + case TYPE_ALBUM: + return song.albumId; + case TYPE_SONG: + return song.id; + default: + return TYPE_INVALID; + } + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/MiniPlaybackActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/MiniPlaybackActivity.java new file mode 100644 index 0000000..2a5ad85 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/MiniPlaybackActivity.java @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2010 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.view.Window; +import android.widget.ImageButton; + +/** + * Compact playback activity that displays itself like a dialog. That is, the + * window is not fullscreen but only as large as it needs to be. Includes a + * CoverView and control buttons. + */ +public class MiniPlaybackActivity extends PlaybackActivity { + @Override + public void onCreate(Bundle state) + { + ThemeHelper.setTheme(this, R.style.PopupDialog); + super.onCreate(state); + + requestWindowFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.mini_playback); + + mCoverView = (CoverView)findViewById(R.id.cover_view); + mCoverView.setOnClickListener(this); + mCoverView.setup(mLooper, this, CoverBitmap.STYLE_OVERLAPPING_BOX); + + bindControlButtons(); + } + + @Override + public void onClick(View view) + { + switch (view.getId()) { + case R.id.cover_view: + startActivity(new Intent(this, FullPlaybackActivity.class)); + finish(); + break; + default: + super.onClick(view); + } + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/NotificationHelper.java b/app/src/main/java/ch/blinkenlights/android/vanilla/NotificationHelper.java new file mode 100644 index 0000000..3b9ba65 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/NotificationHelper.java @@ -0,0 +1,80 @@ +/* + * Copyright (C) 2017-2021 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.content.Context; +import android.graphics.Bitmap; +import androidx.core.app.NotificationCompat; + + +public class NotificationHelper { + /** + * The notification manager instance we are using. + */ + private NotificationManager mNotificationManager; + /** + * The name of the channel to use for these notifications. + */ + private String mChannelId; + + /** + * Creates and returns a new NotificationHelper. + * + * @param context the context to use. + * @param channelId the ID of the notification channel to create. + * @param name the user visible name of the channel. + */ + public NotificationHelper(Context context, String channelId, String name) { + mNotificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE); + mChannelId = channelId; + + NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW); + mNotificationManager.createNotificationChannel(channel); + } + + /** + * Returns a new NotificationCompat.Builder. + * + * @param context the context to use + */ + public NotificationCompat.Builder getNewBuilder(Context context) { + return new NotificationCompat.Builder(context, mChannelId); + } + + /** + * Post a notification to be shown in the status bar. + * + * @param id the id of this notification. + * @param notification the notification to display. + */ + public void notify(int id, Notification notification) { + mNotificationManager.notify(id, notification); + } + + /** + * Cancels a notification. + * + * @param id the id to cancel + */ + public void cancel(int id) { + mNotificationManager.cancel(id); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/OneCellWidget.java b/app/src/main/java/ch/blinkenlights/android/vanilla/OneCellWidget.java new file mode 100644 index 0000000..6765869 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/OneCellWidget.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.widget.RemoteViews; + +/** + * 1x1 widget that shows title, album art, and hidden next and play/pause + * buttons. + */ +public class OneCellWidget extends AppWidgetProvider { + private static boolean sEnabled; + + @Override + public void onEnabled(Context context) + { + sEnabled = true; + } + + @Override + public void onDisabled(Context context) + { + sEnabled = false; + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) + { + Song song = null; + int state = 0; + + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + song = service.getSong(0); + state = service.getState(); + } + + sEnabled = true; + updateWidget(context, manager, song, state); + } + + /** + * Check if there are any instances of this widget placed. + */ + public static void checkEnabled(Context context, AppWidgetManager manager) + { + sEnabled = manager.getAppWidgetIds(new ComponentName(context, OneCellWidget.class)).length != 0; + } + + /** + * Populate the widgets with the given ids with the given info. + * + * @param context A Context to use. + * @param manager The AppWidgetManager that will be used to update the + * widget. + * @param song The current Song in PlaybackService. + * @param state The current PlaybackService state. + */ + public static void updateWidget(Context context, AppWidgetManager manager, Song song, int state) + { + if (!sEnabled) + return; + + SharedPreferences settings = SharedPrefHelper.getSettings(context); + boolean doubleTap = settings.getBoolean(PrefKeys.DOUBLE_TAP, PrefDefaults.DOUBLE_TAP); + + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.one_cell_widget); + + boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + views.setImageViewResource(R.id.play_pause, playing ? R.drawable.hidden_pause : R.drawable.hidden_play); + + + Intent intent; + PendingIntent pendingIntent; + int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + intent = ShortcutPseudoActivity.getIntent(context, doubleTap ? PlaybackService.ACTION_TOGGLE_PLAYBACK_DELAYED : PlaybackService.ACTION_TOGGLE_PLAYBACK); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.play_pause, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, doubleTap ? PlaybackService.ACTION_NEXT_SONG_DELAYED : PlaybackService.ACTION_NEXT_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.next, pendingIntent); + + + Bitmap cover = null; + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + views.setInt(R.id.title, "setText", R.string.no_songs); + } else if (song == null) { + views.setInt(R.id.title, "setText", R.string.app_name); + } else { + views.setTextViewText(R.id.title, song.title); + cover = song.getMediumCover(context); + } + + if (cover == null) { + views.setImageViewResource(R.id.cover, R.drawable.fallback_cover); + } else { + views.setImageViewBitmap(R.id.cover, cover); + } + + manager.updateAppWidget(new ComponentName(context, OneCellWidget.class), views); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PermissionRequestActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PermissionRequestActivity.java new file mode 100644 index 0000000..d4bf411 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PermissionRequestActivity.java @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2015-2023 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + + +import android.Manifest; +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.pm.PackageManager; +import android.content.Context; +import android.content.Intent; +import android.view.View; +import android.view.ViewGroup; +import android.view.LayoutInflater; +import android.os.Build; +import android.os.Bundle; + +import java.util.Arrays; +import java.util.ArrayList; + +public class PermissionRequestActivity extends Activity { + + /** + * The intent to start after acquiring the required permissions + */ + private Intent mCallbackIntent; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mCallbackIntent = getIntent().getExtras().getParcelable("callbackIntent"); + + ArrayList<String> allPerms = new ArrayList<>(Arrays.asList(getNeededPermissions())); + allPerms.addAll(Arrays.asList(getOptionalPermissions())); + + requestPermissions(allPerms.toArray(new String[0]), 0); + } + + /** + * Called by Activity after the user interacted with the permission request + * Will launch the main activity if all permissions were granted, exits otherwise + * + * @param requestCode The code set by requestPermissions + * @param permissions Names of the permissions we got granted or denied + * @param grantResults Results of the permission requests + */ + @Override + public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + ArrayList<String> neededPerms = new ArrayList<>(Arrays.asList(getNeededPermissions())); + int grantedPermissions = 0; + + for (int i = 0; i < permissions.length; i++) { + if (!neededPerms.contains(permissions[i])) + continue; + if (grantResults[i] == PackageManager.PERMISSION_GRANTED) + grantedPermissions++; + } + + // set as finished before (possibly) killing ourselfs + finish(); + + if (grantedPermissions == neededPerms.size()) { + if (mCallbackIntent != null) { + // start the old intent but ensure to make it a new task & clear any old attached activites + mCallbackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(mCallbackIntent); + } + // Hack: We *kill* ourselfs (while launching the main activity) to get startet + // in a new process: This works around a bug/feature in 6.0 that would cause us + // to get 'partial read' permissions (eg: reading from the content provider works + // but reading from /sdcard doesn't) + android.os.Process.killProcess(android.os.Process.myPid()); + } + } + + /** + * Injects a warning that we are missing read permissions into the activity layout + * + * @param activity Reference to LibraryActivity + * @param intent The intent starting the parent activity + */ + public static void showWarning(final LibraryActivity activity, final Intent intent) { + LayoutInflater inflater = LayoutInflater.from(activity); + View view = inflater.inflate(R.layout.permission_request, null, false); + + view.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + PermissionRequestActivity.requestPermissions(activity, intent); + } + }); + + ViewGroup parent = (ViewGroup)activity.findViewById(R.id.content); // main layout of library_content + parent.addView(view, -1); + } + + /** + * Launches a permission request dialog if needed + * + * @param activity The activitys context to use for the permission check + * @return boolean true if we showed a permission request dialog + */ + public static boolean requestPermissions(Activity activity, Intent callbackIntent) { + boolean havePermissions = havePermissions(activity); + + if (havePermissions == false) { + Intent intent = new Intent(activity, PermissionRequestActivity.class); + intent.putExtra("callbackIntent", callbackIntent); + activity.startActivity(intent); + } + + return !havePermissions; + } + + /** + * Checks if all required permissions have been granted + * + * @param context The context to use + * @return boolean true if all permissions have been granded + */ + public static boolean havePermissions(Context context) { + for (String permission : getNeededPermissions()) { + if (context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { + return false; + } + } + return true; + } + + private static String[] getNeededPermissions() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + return new String[] { Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES }; + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + return new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }; + } + return new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; + } + + private static String[] getOptionalPermissions() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + return new String[] { Manifest.permission.POST_NOTIFICATIONS }; + } + return new String[]{}; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlayCountsHelper.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlayCountsHelper.java new file mode 100644 index 0000000..b65c6fb --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlayCountsHelper.java @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2014-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.database.Cursor; +import java.util.ArrayList; + +public class PlayCountsHelper { + + public PlayCountsHelper() { + } + + /** + * Counts this song object as 'played' or 'skipped' + */ + public static void countSong(Context context, Song song, boolean played) { + final long id = Song.getId(song); + MediaLibrary.updateSongPlayCounts(context, id, played); + } + + + + /** + * Returns a sorted array list of most often listen song ids + */ + public static ArrayList<Long> getTopSongs(Context context, int limit) { + ArrayList<Long> payload = new ArrayList<Long>(); + Cursor cursor = MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_SONGS, new String[]{ MediaLibrary.SongColumns._ID }, MediaLibrary.SongColumns.PLAYCOUNT+" > 0", null, MediaLibrary.SongColumns.PLAYCOUNT+" DESC"); + while (cursor.moveToNext() && limit > 0) { + payload.add(cursor.getLong(0)); + limit--; + } + cursor.close(); + return payload; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaybackActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaybackActivity.java new file mode 100644 index 0000000..8de1203 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaybackActivity.java @@ -0,0 +1,737 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2014-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import java.io.File; +import java.util.ArrayList; +import java.util.Map; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.ApplicationInfo; +import android.content.res.Resources; +import android.media.AudioManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.os.Message; +import android.os.Process; +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.ImageButton; +import android.widget.Toast; + +/** + * Base activity for activities that contain playback controls. Handles + * communication with the PlaybackService and response to state and song + * changes. + */ +public abstract class PlaybackActivity extends Activity + implements TimelineCallback, + Handler.Callback, + View.OnClickListener, + CoverView.Callback +{ + + private Action mUpAction; + private Action mDownAction; + + /** + * A Handler running on the UI thread, in contrast with mHandler which runs + * on a worker thread. + */ + protected final Handler mUiHandler = new Handler(this); + /** + * A Handler running on a worker thread. + */ + protected Handler mHandler; + /** + * The looper for the worker thread. + */ + protected Looper mLooper; + + protected CoverView mCoverView; + protected ImageButton mPlayPauseButton; + protected ImageButton mShuffleButton; + protected ImageButton mEndButton; + + protected int mState; + private long mLastStateEvent; + private long mLastSongEvent; + + @Override + public void onCreate(Bundle state) + { + super.onCreate(state); + + PlaybackService.addTimelineCallback(this); + + setVolumeControlStream(AudioManager.STREAM_MUSIC); + + HandlerThread thread = new HandlerThread(getClass().getName(), Process.THREAD_PRIORITY_LOWEST); + thread.start(); + + mLooper = thread.getLooper(); + mHandler = new Handler(mLooper, this); + + } + + @Override + public void onDestroy() + { + PlaybackService.removeTimelineCallback(this); + mLooper.quit(); + super.onDestroy(); + } + + @Override + public void onStart() + { + super.onStart(); + + if (PlaybackService.hasInstance()) + onServiceReady(); + else + startService(new Intent(this, PlaybackService.class)); + + SharedPreferences prefs = SharedPrefHelper.getSettings(this); + mUpAction = Action.getAction(prefs, PrefKeys.SWIPE_UP_ACTION, PrefDefaults.SWIPE_UP_ACTION); + mDownAction = Action.getAction(prefs, PrefKeys.SWIPE_DOWN_ACTION, PrefDefaults.SWIPE_DOWN_ACTION); + + Window window = getWindow(); + + // Set lockscreen preference + if (prefs.getBoolean(PrefKeys.DISABLE_LOCKSCREEN, PrefDefaults.DISABLE_LOCKSCREEN)) + window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + else + window.clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + + // Set screen-on preference + if (prefs.getBoolean(PrefKeys.KEEP_SCREEN_ON, PrefDefaults.KEEP_SCREEN_ON)) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + else + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + + } + + @Override + public void onResume() + { + super.onResume(); + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(this); + service.userActionTriggered(); + } + + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) + { + switch (keyCode) { + case KeyEvent.KEYCODE_HEADSETHOOK: + case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: + case KeyEvent.KEYCODE_MEDIA_NEXT: + case KeyEvent.KEYCODE_MEDIA_PREVIOUS: + return MediaButtonReceiver.processKey(this, event); + } + + return super.onKeyDown(keyCode, event); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) + { + switch (keyCode) { + case KeyEvent.KEYCODE_HEADSETHOOK: + case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: + case KeyEvent.KEYCODE_MEDIA_NEXT: + case KeyEvent.KEYCODE_MEDIA_PREVIOUS: + return MediaButtonReceiver.processKey(this, event); + } + + return super.onKeyUp(keyCode, event); + } + + @Override + public void shiftCurrentSong(int delta) + { + setSong(PlaybackService.get(this).shiftCurrentSong(delta)); + } + + public void playPause() + { + PlaybackService service = PlaybackService.get(this); + int state = service.playPause(false); + if ((state & PlaybackService.FLAG_ERROR) != 0) + showToast(service.getErrorMessage(), Toast.LENGTH_LONG); + setState(state); + } + + private void rewindCurrentSong() + { + setSong(PlaybackService.get(this).rewindCurrentSong()); + } + + + @Override + public void onClick(View view) + { + switch (view.getId()) { + case R.id.next: + shiftCurrentSong(SongTimeline.SHIFT_NEXT_SONG); + break; + case R.id.play_pause: + playPause(); + break; + case R.id.previous: + rewindCurrentSong(); + break; + case R.id.end_action: + cycleFinishAction(); + break; + case R.id.shuffle: + cycleShuffle(); + break; + } + } + + /** + * Called when the PlaybackService state has changed. + * + * @param state PlaybackService state + * @param toggled The flags that have changed from the previous state + */ + protected void onStateChange(int state, int toggled) + { + if ((toggled & PlaybackService.FLAG_PLAYING) != 0 && mPlayPauseButton != null) { + mPlayPauseButton.setImageResource((state & PlaybackService.FLAG_PLAYING) == 0 ? R.drawable.play : R.drawable.pause); + } + if ((toggled & PlaybackService.MASK_FINISH) != 0 && mEndButton != null) { + mEndButton.setImageResource(SongTimeline.FINISH_ICONS[PlaybackService.finishAction(state)]); + } + if ((toggled & PlaybackService.MASK_SHUFFLE) != 0 && mShuffleButton != null) { + mShuffleButton.setImageResource(SongTimeline.SHUFFLE_ICONS[PlaybackService.shuffleMode(state)]); + } + } + + protected void setState(final int state) + { + mLastStateEvent = System.nanoTime(); + + if (mState != state) { + final int toggled = mState ^ state; + mState = state; + runOnUiThread(new Runnable() { + @Override + public void run() + { + onStateChange(state, toggled); + } + }); + } + } + + /** + * Called by PlaybackService to update the state. + */ + public void setState(long uptime, int state) + { + if (uptime > mLastStateEvent) { + setState(state); + mLastStateEvent = uptime; + } + } + + /** + * Sets up components when the PlaybackService is initialized and available to + * interact with. Override to implement further post-initialization behavior. + */ + protected void onServiceReady() + { + PlaybackService service = PlaybackService.get(this); + setSong(service.getSong(0)); + setState(service.getState()); + } + + /** + * Called when the current song changes. + * + * @param song The new song + */ + protected void onSongChange(Song song) + { + if (mCoverView != null) + mCoverView.querySongs(); + } + + protected void setSong(final Song song) + { + mLastSongEvent = System.nanoTime(); + runOnUiThread(new Runnable() { + @Override + public void run() + { + onSongChange(song); + } + }); + } + + /** + * Sets up onClick listeners for our common control buttons bar + */ + protected void bindControlButtons() { + View previousButton = findViewById(R.id.previous); + previousButton.setOnClickListener(this); + mPlayPauseButton = (ImageButton)findViewById(R.id.play_pause); + mPlayPauseButton.setOnClickListener(this); + View nextButton = findViewById(R.id.next); + nextButton.setOnClickListener(this); + + mShuffleButton = (ImageButton)findViewById(R.id.shuffle); + mShuffleButton.setOnClickListener(this); + registerForContextMenu(mShuffleButton); + mEndButton = (ImageButton)findViewById(R.id.end_action); + mEndButton.setOnClickListener(this); + registerForContextMenu(mEndButton); + } + + /** + * Called by PlaybackService to update the current song. + */ + public void setSong(long uptime, Song song) + { + if (uptime > mLastSongEvent) { + setSong(song); + mLastSongEvent = uptime; + } + } + + /** + * Called by PlaybackService to update an active song (next, previous, or + * current). + */ + public void replaceSong(int delta, Song song) + { + if (mCoverView != null) + mCoverView.replaceSong(delta, song); + } + + /** + * Called when the song timeline position/size has changed. + */ + public void onPositionInfoChanged() + { + } + + /** + * Called when the content of the media store has changed. + */ + public void onMediaChange() + { + } + + /** + * Called when the timeline change has changed. + */ + public void onTimelineChanged() + { + } + + static final int MENU_SORT = 1; + static final int MENU_PREFS = 2; + static final int MENU_PLAYBACK = 3; + static final int MENU_SEARCH = 4; + static final int MENU_ENQUEUE = 7; // toplevel menu, has no action + static final int MENU_ENQUEUE_ALBUM = 8; + static final int MENU_ENQUEUE_ARTIST = 9; + static final int MENU_ENQUEUE_GENRE = 10; + static final int MENU_CLEAR_QUEUE = 11; + static final int MENU_SONG_FAVORITE = 12; + static final int MENU_SHOW_QUEUE = 13; + static final int MENU_HIDE_QUEUE = 14; + static final int MENU_DELETE = 15; + static final int MENU_EMPTY_QUEUE = 16; + static final int MENU_ADD_TO_PLAYLIST = 17; + static final int MENU_SHARE = 18; + static final int MENU_GO_HOME = 19; + static final int MENU_PLUGINS = 20; // used in FullPlaybackActivity + static final int MENU_MORE = 21; // toplevel menu, has no own action + static final int MENU_MORE_ALBUM = 22; + static final int MENU_MORE_ARTIST = 23; + static final int MENU_MORE_GENRE = 24; + static final int MENU_MORE_FOLDER = 25; + static final int MENU_JUMP_TO_TIME = 26; + + @Override + public boolean onCreateOptionsMenu(Menu menu) + { + menu.add(0, MENU_PREFS, 10, R.string.settings).setIcon(R.drawable.ic_menu_preferences); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) + { + switch (item.getItemId()) { + case MENU_PREFS: + startActivity(new Intent(this, PreferencesActivity.class)); + break; + case MENU_CLEAR_QUEUE: + PlaybackService.get(this).clearQueue(); + break; + case MENU_EMPTY_QUEUE: + PlaybackService.get(this).emptyQueue(); + break; + default: + return false; + } + return true; + } + + + /** + * Same as MSG_ADD_TO_PLAYLIST but creates the new playlist on-the-fly (or overwrites an existing list) + */ + protected static final int MSG_CREATE_PLAYLIST = 0; + /** + * Call renamePlaylist with the results from a NewPlaylistDialog stored in + * obj. + */ + protected static final int MSG_RENAME_PLAYLIST = 1; + /** + * Call addToPlaylist with data from the playlisttask object. + */ + protected static final int MSG_ADD_TO_PLAYLIST = 2; + /** + * Call removeFromPlaylist with data from the playlisttask object. + */ + protected static final int MSG_REMOVE_FROM_PLAYLIST = 3; + /** + * Removes a media object + */ + protected static final int MSG_DELETE = 4; + /** + * Saves the current queue as a playlist + */ + protected static final int MSG_ADD_QUEUE_TO_PLAYLIST = 5; + /** + * Notification that we changed some playlist members + */ + protected static final int MSG_NOTIFY_PLAYLIST_CHANGED = 6; + + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_CREATE_PLAYLIST: { + PlaylistTask playlistTask = (PlaylistTask)message.obj; + int nextAction = message.arg1; + long playlistId = Playlist.createPlaylist(this, playlistTask.name); + playlistTask.playlistId = playlistId; + mHandler.sendMessage(mHandler.obtainMessage(nextAction, playlistTask)); + break; + } + case MSG_ADD_TO_PLAYLIST: { + PlaylistTask playlistTask = (PlaylistTask)message.obj; + addToPlaylist(playlistTask); + break; + } + case MSG_ADD_QUEUE_TO_PLAYLIST: { + PlaylistTask playlistTask = (PlaylistTask)message.obj; + playlistTask.audioIds = new ArrayList<Long>(); + Song song; + PlaybackService service = PlaybackService.get(this); + for (int i=0; ; i++) { + song = service.getSongByQueuePosition(i); + if (song == null) + break; + playlistTask.audioIds.add(song.id); + } + addToPlaylist(playlistTask); + break; + } + case MSG_REMOVE_FROM_PLAYLIST: { + PlaylistTask playlistTask = (PlaylistTask)message.obj; + removeFromPlaylist(playlistTask); + break; + } + case MSG_RENAME_PLAYLIST: { + PlaylistTask playlistTask = (PlaylistTask)message.obj; + Playlist.renamePlaylist(getApplicationContext(), playlistTask.playlistId, playlistTask.name); + break; + } + case MSG_DELETE: { + delete((Intent)message.obj); + break; + } + case MSG_NOTIFY_PLAYLIST_CHANGED: { + // this is a NOOP here: super classes might implement this. + break; + } + default: + return false; + } + return true; + } + + /** + * Add a set of songs represented by the playlistTask to a playlist. Displays a + * Toast notifying of success. + * + * @param playlistTask The pending PlaylistTask to execute + */ + protected void addToPlaylist(PlaylistTask playlistTask) { + int count = 0; + + if (playlistTask.query != null) { + count += Playlist.addToPlaylist(this, playlistTask.playlistId, playlistTask.query); + } + + if (playlistTask.audioIds != null) { + count += Playlist.addToPlaylist(this, playlistTask.playlistId, playlistTask.audioIds); + } + + String message = getResources().getQuantityString(R.plurals.added_to_playlist, count, count, playlistTask.name); + showToast(message, Toast.LENGTH_SHORT); + mHandler.sendEmptyMessage(MSG_NOTIFY_PLAYLIST_CHANGED); + } + + /** + * Removes a set of songs represented by the playlistTask from a playlist. Displays a + * Toast notifying of success. + * + * @param playlistTask The pending PlaylistTask to execute + */ + private void removeFromPlaylist(PlaylistTask playlistTask) { + int count = 0; + + if (playlistTask.query != null) { + throw new IllegalArgumentException("Delete by query is not implemented yet"); + } + + if (playlistTask.audioIds != null) { + count += Playlist.removeFromPlaylist(getApplicationContext(), playlistTask.playlistId, playlistTask.audioIds); + } + + String message = getResources().getQuantityString(R.plurals.removed_from_playlist, count, count, playlistTask.name); + showToast(message, Toast.LENGTH_SHORT); + mHandler.sendEmptyMessage(MSG_NOTIFY_PLAYLIST_CHANGED); + } + + /** + * Delete the media represented by the given intent and show a Toast + * informing the user of this. + * + * @param intent An intent created with + * {@link LibraryAdapter#createData(View)}. + */ + private void delete(Intent intent) + { + int type = intent.getIntExtra("type", MediaUtils.TYPE_INVALID); + long id = intent.getLongExtra("id", LibraryAdapter.INVALID_ID); + String message = null; + Resources res = getResources(); + + if (type == MediaUtils.TYPE_FILE) { + String file = intent.getStringExtra("file"); + boolean success = MediaUtils.deleteFile(new File(file)); + if (!success) { + message = res.getString(R.string.delete_file_failed, file); + } + } else if (type == MediaUtils.TYPE_PLAYLIST) { + Playlist.deletePlaylist(this, id); + } else { + int count = PlaybackService.get(this).deleteMedia(type, id); + message = res.getQuantityString(R.plurals.deleted, count, count); + } + + if (message == null) { + message = res.getString(R.string.deleted_item, intent.getStringExtra("title")); + } + + showToast(message, Toast.LENGTH_SHORT); + } + + /** + * Creates and displays a new toast message + */ + private void showToast(final String message, final int duration) { + runOnUiThread(new Runnable() { + @Override + public void run() { + Toast.makeText(getApplicationContext(), message, duration).show(); + } + }); + } + + + /** + * Cycle shuffle mode. + */ + public void cycleShuffle() + { + setState(PlaybackService.get(this).cycleShuffle()); + } + + /** + * Cycle the finish action. + */ + public void cycleFinishAction() + { + setState(PlaybackService.get(this).cycleFinishAction()); + } + + /** + * Open the library activity. + * + * @param song If non-null, will open the library focused on this song. + * @param type the media type to switch to for 'song' + */ + public void openLibrary(Song song, int type) + { + Intent intent = new Intent(this, LibraryActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + if (song != null) { + long id = -1; + String folder = null; + switch(type) { + case MediaUtils.TYPE_ARTIST: + id = song.artistId; + break; + case MediaUtils.TYPE_ALBUM: + id = song.albumId; + break; + case MediaUtils.TYPE_GENRE: + id = MediaUtils.queryGenreForSong(this, song.id); + break; + case MediaUtils.TYPE_FILE: + File file = new File(song.path); + folder = file.getParent(); + break; + default: + throw new IllegalArgumentException("Invalid media type " + type); + } + intent.putExtra("type", type); + intent.putExtra("id", id); + intent.putExtra("folder", folder); + } + startActivity(intent); + } + + @Override + public void upSwipe() + { + performAction(mUpAction); + } + + @Override + public void downSwipe() + { + performAction(mDownAction); + } + + protected void performAction(Action action) + { + PlaybackService.get(this).performAction(action, this); + } + + private static final int CTX_MENU_GRP_SHUFFLE = 200; + private static final int CTX_MENU_GRP_FINISH = 201; + + @Override + public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) + { + if (view == mShuffleButton) { + menu.add(CTX_MENU_GRP_SHUFFLE, SongTimeline.SHUFFLE_NONE, 0, R.string.no_shuffle); + menu.add(CTX_MENU_GRP_SHUFFLE, SongTimeline.SHUFFLE_SONGS, 0, R.string.shuffle_songs); + menu.add(CTX_MENU_GRP_SHUFFLE, SongTimeline.SHUFFLE_ALBUMS, 0, R.string.shuffle_albums); + } else if (view == mEndButton) { + menu.add(CTX_MENU_GRP_FINISH, SongTimeline.FINISH_STOP, 0, R.string.no_repeat); + menu.add(CTX_MENU_GRP_FINISH, SongTimeline.FINISH_REPEAT, 0, R.string.repeat); + menu.add(CTX_MENU_GRP_FINISH, SongTimeline.FINISH_REPEAT_CURRENT, 0, R.string.repeat_current_song); + menu.add(CTX_MENU_GRP_FINISH, SongTimeline.FINISH_STOP_CURRENT, 0, R.string.stop_current_song); + menu.add(CTX_MENU_GRP_FINISH, SongTimeline.FINISH_RANDOM, 0, R.string.random); + } + } + + @Override + public boolean onContextItemSelected(MenuItem item) + { + int group = item.getGroupId(); + int id = item.getItemId(); + if (group == CTX_MENU_GRP_SHUFFLE) + setState(PlaybackService.get(this).setShuffleMode(id)); + else if (group == CTX_MENU_GRP_FINISH) + setState(PlaybackService.get(this).setFinishAction(id)); + return true; + } + + /** + * Queries all plugin packages and shows plugin selection dialog. + * @param intent intent with a song to send to plugins + */ + protected void showPluginMenu(final Intent intent) { + final Map<String, ApplicationInfo> plugins = PluginUtils.getPluginMap(this); + final String[] pNamesArr = plugins.keySet().toArray(new String[0]); + + new AlertDialog.Builder(this) + .setItems(pNamesArr, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + long id = intent.getLongExtra("id", LibraryAdapter.INVALID_ID); + Song song = MediaUtils.getSongByTypeId(PlaybackActivity.this, MediaUtils.TYPE_SONG, id); + if (song != null) { + ApplicationInfo selected = plugins.get(pNamesArr[which]); + Intent request = new Intent(PluginUtils.ACTION_LAUNCH_PLUGIN); + request.setPackage(selected.packageName); + request.putExtra(PluginUtils.EXTRA_PARAM_URI, Uri.fromFile(new File(song.path))); + request.putExtra(PluginUtils.EXTRA_PARAM_SONG_TITLE, song.title); + request.putExtra(PluginUtils.EXTRA_PARAM_SONG_ARTIST, song.artist); + request.putExtra(PluginUtils.EXTRA_PARAM_SONG_ALBUM, song.album); + if (request.resolveActivity(getPackageManager()) != null) { + startActivity(request); + } else { + Log.e("PluginSystem", "Couldn't start plugin activity for " + request); + } + } + } + }) + .create().show(); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaybackService.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaybackService.java new file mode 100644 index 0000000..97fd663 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaybackService.java @@ -0,0 +1,2398 @@ +/* + * Copyright (C) 2012-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; +import ch.blinkenlights.android.medialibrary.LibraryObserver; + +import android.app.Notification; +import android.app.PendingIntent; +import android.app.Service; +import android.app.backup.BackupManager; +import android.appwidget.AppWidgetManager; +import android.content.BroadcastReceiver; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; +import android.media.AudioDeviceInfo; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.os.Build; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.PowerManager; +import android.os.Process; +import android.os.SystemClock; +import android.util.Log; +import android.view.View; +import android.widget.Toast; +import androidx.core.app.NotificationCompat; +import java.lang.Math; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.EOFException; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.ArrayList; + + +/** + * Handles music playback and pretty much all the other work. + */ +public final class PlaybackService extends Service + implements Handler.Callback + , MediaPlayer.OnCompletionListener + , MediaPlayer.OnErrorListener + , SharedPreferences.OnSharedPreferenceChangeListener + , SongTimeline.Callback + , SensorEventListener + , AudioManager.OnAudioFocusChangeListener +{ + /** + * Name of the state file. + */ + private static final String STATE_FILE = "state"; + /** + * Header for state file to help indicate if the file is in the right + * format. + */ + private static final long STATE_FILE_MAGIC = 0x1533574DC74B6ECL; + /** + * State file version that indicates data order. + */ + private static final int STATE_VERSION = 6; + + private static final int NOTIFICATION_ID = 2; + private static final String NOTIFICATION_CHANNEL = "Playback"; + + /** + * Rewind song if we already played more than 2.5 sec + */ + private static final int REWIND_AFTER_PLAYED_MS = 2500; + + /** + * Action for startService: toggle playback on/off. + */ + public static final String ACTION_TOGGLE_PLAYBACK = "ch.blinkenlights.android.vanilla.action.TOGGLE_PLAYBACK"; + /** + * Action for startService: start playback if paused. + */ + public static final String ACTION_PLAY = "ch.blinkenlights.android.vanilla.action.PLAY"; + /** + * Action for startService: pause playback if playing. + */ + public static final String ACTION_PAUSE = "ch.blinkenlights.android.vanilla.action.PAUSE"; + /** + * Action for startService: toggle playback on/off. + * + * Unlike {@link PlaybackService#ACTION_TOGGLE_PLAYBACK}, the toggle does + * not occur immediately. Instead, it is delayed so that if two of these + * actions are received within 400 ms, the playback activity is opened + * instead. + */ + public static final String ACTION_TOGGLE_PLAYBACK_DELAYED = "ch.blinkenlights.android.vanilla.action.TOGGLE_PLAYBACK_DELAYED"; + /** + * Action for startService: advance to the next song. + */ + public static final String ACTION_NEXT_SONG = "ch.blinkenlights.android.vanilla.action.NEXT_SONG"; + /** + * Action for startService: advance to the next song. + * + * Unlike {@link PlaybackService#ACTION_NEXT_SONG}, the toggle does + * not occur immediately. Instead, it is delayed so that if two of these + * actions are received within 400 ms, the playback activity is opened + * instead. + */ + public static final String ACTION_NEXT_SONG_DELAYED = "ch.blinkenlights.android.vanilla.action.NEXT_SONG_DELAYED"; + /** + * Action for startService: advance to the next song. + * + * Like ACTION_NEXT_SONG, but starts playing automatically if paused + * when this is called. + */ + public static final String ACTION_NEXT_SONG_AUTOPLAY = "ch.blinkenlights.android.vanilla.action.NEXT_SONG_AUTOPLAY"; + /** + * Action for startService: go back to the previous song. + */ + public static final String ACTION_PREVIOUS_SONG = "ch.blinkenlights.android.vanilla.action.PREVIOUS_SONG"; + /** + * Action for startService: go back to the previous song. + * + * Like ACTION_PREVIOUS_SONG, but starts playing automatically if paused + * when this is called. + */ + public static final String ACTION_PREVIOUS_SONG_AUTOPLAY = "ch.blinkenlights.android.vanilla.action.PREVIOUS_SONG_AUTOPLAY"; + /** + * Flushes the queue, switches to random mode and starts playing. + */ + public static final String ACTION_RANDOM_MIX_AUTOPLAY = "ch.blinkenlights.android.vanilla.action.RANDOM_MIX_AUTOPLAY"; + /** + * Flushes the queue and plays everything of the passed type/id combination. + */ + public static final String ACTION_FROM_TYPE_ID_AUTOPLAY = "ch.blinkenlights.android.vanilla.action.FROM_TYPE_ID_AUTOPLAY"; + /** + * Change the shuffle mode. + */ + public static final String ACTION_CYCLE_SHUFFLE = "ch.blinkenlights.android.vanilla.CYCLE_SHUFFLE"; + /** + * Change the repeat mode. + */ + public static final String ACTION_CYCLE_REPEAT = "ch.blinkenlights.android.vanilla.CYCLE_REPEAT"; + /** + * Whether we should create a foreground notification as early as possible. + */ + public static final String EXTRA_EARLY_NOTIFICATION = "extra_early_notification"; + /** + * Keep notification forcefully around on stops if set. + */ + public static final String EXTRA_FORCE_NOTIFICATION = "extra_force_notification"; + + /** + * Visibility modes of the notification. + */ + public static final int VISIBILITY_WHEN_PLAYING = 0; + public static final int VISIBILITY_ALWAYS = 1; + + /** + * Notification click action: open LaunchActivity. + */ + private static final int NOT_ACTION_MAIN_ACTIVITY = 0; + /** + * Notification click action: open MiniPlaybackActivity. + */ + private static final int NOT_ACTION_MINI_ACTIVITY = 1; + /** + * Notification click action: open FullPlaybackActivity. + */ + private static final int NOT_ACTION_FULL_ACTIVITY = 2; + /** + * Notification click action: skip to next song. + */ + private static final int NOT_ACTION_NEXT_SONG = 3; + + /** + * If a user action is triggered within this time (in ms) after the + * idle time fade-out occurs, playback will be resumed. + */ + private static final long IDLE_GRACE_PERIOD = 60000; + /** + * Minimum time in milliseconds between shake actions. + */ + private static final int MIN_SHAKE_PERIOD = 500; + /** + * Defer entering deep sleep for this time (in ms). + */ + private static final int SLEEP_STATE_DELAY = 60000; + /** + * Save the current playlist state on queue changes after this time (in ms). + */ + private static final int SAVE_STATE_DELAY = 5000; + /** + * If set, music will play. + */ + public static final int FLAG_PLAYING = 0x1; + /** + * Set when there is no media available on the device. + */ + public static final int FLAG_NO_MEDIA = 0x2; + /** + * Set when the current song is unplayable. + */ + public static final int FLAG_ERROR = 0x4; + /** + * Set when the user needs to select songs to play. + */ + public static final int FLAG_EMPTY_QUEUE = 0x8; + public static final int SHIFT_FINISH = 4; + /** + * These three bits will be one of SongTimeline.FINISH_*. + */ + public static final int MASK_FINISH = 0x7 << SHIFT_FINISH; + public static final int SHIFT_SHUFFLE = 7; + /** + * These three bits will be one of SongTimeline.SHUFFLE_*. + */ + public static final int MASK_SHUFFLE = 0x7 << SHIFT_SHUFFLE; + public static final int SHIFT_DUCKING = 10; + /** + * Whether we're 'ducking' (lowering the playback volume temporarily due to a transient system + * sound, such as a notification) or not + */ + public static final int FLAG_DUCKING = 0x1 << SHIFT_DUCKING; + + /** + * The PlaybackService state, indicating if the service is playing, + * repeating, etc. + * + * The format of this is 0b00000000_00000000_000000gff_feeedcba, + * where each bit is: + * a: {@link PlaybackService#FLAG_PLAYING} + * b: {@link PlaybackService#FLAG_NO_MEDIA} + * c: {@link PlaybackService#FLAG_ERROR} + * d: {@link PlaybackService#FLAG_EMPTY_QUEUE} + * eee: {@link PlaybackService#MASK_FINISH} + * fff: {@link PlaybackService#MASK_SHUFFLE} + * g: {@link PlaybackService#FLAG_DUCKING} + */ + int mState; + + /** + * How many broken songs we did already skip + */ + int mSkipBroken; + + /** + * Object used for state-related locking. + */ + final Object[] mStateLock = new Object[0]; + /** + * Object used for PlaybackService startup waiting. + */ + private static final Object[] sWait = new Object[0]; + /** + * The appplication-wide instance of the PlaybackService. + */ + public static PlaybackService sInstance; + /** + * Static referenced-array to PlaybackActivities, used for callbacks + */ + private static final ArrayList<TimelineCallback> sCallbacks = new ArrayList<TimelineCallback>(5); + + boolean mHeadsetPause; + private boolean mScrobble; + /** + * If true, emulate the music status broadcasts sent by the stock android + * music player. + */ + private boolean mStockBroadcast; + /** + * Behaviour of the notification + */ + private int mNotificationVisibility; + /** + * If true, audio will not be played through the speaker. + */ + private boolean mHeadsetOnly; + /** + * The time to wait before considering the player idle. + */ + private int mIdleTimeout; + /** + * The intent for the notification to execute, created by + * {@link PlaybackService#createNotificationAction(SharedPreferences)}. + */ + private PendingIntent mNotificationAction; + /** + * Notification helper instance. + */ + private NotificationHelper mNotificationHelper; + + private Looper mLooper; + private Handler mHandler; + VanillaMediaPlayer mMediaPlayer; + VanillaMediaPlayer mPreparedMediaPlayer; + private boolean mMediaPlayerInitialized; + private boolean mMediaPlayerAudioFxActive; + private PowerManager.WakeLock mWakeLock; + private AudioManager mAudioManager; + /** + * The SensorManager service. + */ + private SensorManager mSensorManager; + /** + * A remote control client implementation + */ + private RemoteControl.Client mRemoteControlClient; + + /** + * Media session state tracker for notification + */ + private MediaSessionTracker mMediaSessionTracker; + + SongTimeline mTimeline; + private Song mCurrentSong; + + /** + * Stores the saved position in the current song from saved state. Should + * be seeked to when the song is loaded into MediaPlayer. Used only during + * initialization. The song that the saved position is for is stored in + * {@link #mPendingSeekSong}. + */ + private int mPendingSeek; + /** + * The id of the song that the mPendingSeek position is for. -1 indicates + * an invalid song. Value is undefined when mPendingSeek is 0. + */ + private long mPendingSeekSong; + public Receiver mReceiver; + private String mErrorMessage; + /** + * Current fade-out progress. 1.0f if we are not fading out + */ + private float mFadeOut = 1.0f; + /** + * Elapsed realtime at which playback was paused by idle timeout. -1 + * indicates that no timeout has occurred. + */ + private long mIdleStart = -1; + /** + * True if we encountered a transient audio loss + */ + private boolean mTransientAudioLoss; + /** + * Magnitude of last sensed acceleration. + */ + private double mAccelLast; + /** + * Filtered acceleration used for shake detection. + */ + private double mAccelFiltered; + /** + * Elapsed realtime of last shake action. + */ + private long mLastShakeTime; + /** + * Minimum jerk required for shake. + */ + private double mShakeThreshold; + /** + * What to do when an accelerometer shake is detected. + */ + private Action mShakeAction; + /** + * If true, the notification should not be hidden when pausing regardless + * of user settings. + */ + private boolean mForceNotificationVisible; + /** + * Amount of songs included in our auto playlist + */ + private int mAutoPlPlaycounts; + /** + * Enables or disables Replay Gain + */ + private boolean mReplayGainTrackEnabled; + private boolean mReplayGainAlbumEnabled; + private int mReplayGainBump; + private int mReplayGainUntaggedDeBump; + /** + * Percentage to set the volume as while a notification is playing (aka ducking) + */ + private int mVolumeDuringDucking; + /** + * + */ + private boolean mIgnoreAudioFocusLoss; + /** + * TRUE if the readahead feature is enabled + */ + private boolean mReadaheadEnabled; + /** + * Reference to precreated ReadAhead thread + */ + private ReadaheadThread mReadahead; + /** + * Referente to our playlist observer + */ + private PlaylistObserver mPlaylistObserver; + /** + * Reference to precreated BASTP Object + */ + private BastpUtil mBastpUtil; + /** + * Don't use gapless playback, useful for bug ridden devices. + */ + private boolean mDisableGaplessPlayback; + + @Override + public void onCreate() + { + HandlerThread thread = new HandlerThread("PlaybackService", Process.THREAD_PRIORITY_DEFAULT); + thread.start(); + + mTimeline = new SongTimeline(this); + mTimeline.setCallback(this); + int state = loadState(); + + mMediaPlayer = getNewMediaPlayer(); + mPreparedMediaPlayer = getNewMediaPlayer(); + // We only have a single audio session + mPreparedMediaPlayer.setAudioSessionId(mMediaPlayer.getAudioSessionId()); + + mBastpUtil = new BastpUtil(); + mReadahead = new ReadaheadThread(); + + mNotificationHelper = new NotificationHelper(this, NOTIFICATION_CHANNEL, getString(R.string.app_name)); + mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE); + + SharedPreferences settings = SharedPrefHelper.getSettings(this); + settings.registerOnSharedPreferenceChangeListener(this); + mNotificationVisibility = Integer.parseInt(settings.getString(PrefKeys.NOTIFICATION_VISIBILITY, PrefDefaults.NOTIFICATION_VISIBILITY)); + mScrobble = settings.getBoolean(PrefKeys.SCROBBLE, PrefDefaults.SCROBBLE); + mIdleTimeout = settings.getBoolean(PrefKeys.USE_IDLE_TIMEOUT, PrefDefaults.USE_IDLE_TIMEOUT) ? settings.getInt(PrefKeys.IDLE_TIMEOUT, PrefDefaults.IDLE_TIMEOUT) : 0; + + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_ANDROID, PrefDefaults.COVERLOADER_ANDROID) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_ANDROID : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_ANDROID); + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_VANILLA, PrefDefaults.COVERLOADER_VANILLA) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_VANILLA : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_VANILLA); + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_SHADOW , PrefDefaults.COVERLOADER_SHADOW) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_SHADOW : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_SHADOW); + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_INLINE , PrefDefaults.COVERLOADER_INLINE) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_INLINE : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_INLINE); + + mHeadsetOnly = settings.getBoolean(PrefKeys.HEADSET_ONLY, PrefDefaults.HEADSET_ONLY); + mStockBroadcast = settings.getBoolean(PrefKeys.STOCK_BROADCAST, PrefDefaults.STOCK_BROADCAST); + mNotificationAction = createNotificationAction(settings); + mHeadsetPause = SharedPrefHelper.getSettings(this).getBoolean(PrefKeys.HEADSET_PAUSE, PrefDefaults.HEADSET_PAUSE); + mShakeAction = settings.getBoolean(PrefKeys.ENABLE_SHAKE, PrefDefaults.ENABLE_SHAKE) ? Action.getAction(settings, PrefKeys.SHAKE_ACTION, PrefDefaults.SHAKE_ACTION) : Action.Nothing; + mShakeThreshold = settings.getInt(PrefKeys.SHAKE_THRESHOLD, PrefDefaults.SHAKE_THRESHOLD) / 10.0f; + + mReplayGainTrackEnabled = settings.getBoolean(PrefKeys.ENABLE_TRACK_REPLAYGAIN, PrefDefaults.ENABLE_TRACK_REPLAYGAIN); + mReplayGainAlbumEnabled = settings.getBoolean(PrefKeys.ENABLE_ALBUM_REPLAYGAIN, PrefDefaults.ENABLE_ALBUM_REPLAYGAIN); + mReplayGainBump = settings.getInt(PrefKeys.REPLAYGAIN_BUMP, PrefDefaults.REPLAYGAIN_BUMP); + mReplayGainUntaggedDeBump = settings.getInt(PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP, PrefDefaults.REPLAYGAIN_UNTAGGED_DEBUMP); + mDisableGaplessPlayback = settings.getBoolean(PrefKeys.DISABLE_GAPLESS_PLAYBACK, PrefDefaults.DISABLE_GAPLESS_PLAYBACK); + + mVolumeDuringDucking = settings.getInt(PrefKeys.VOLUME_DURING_DUCKING, PrefDefaults.VOLUME_DURING_DUCKING); + mIgnoreAudioFocusLoss = settings.getBoolean(PrefKeys.IGNORE_AUDIOFOCUS_LOSS, PrefDefaults.IGNORE_AUDIOFOCUS_LOSS); + refreshDuckingValues(); + + mReadaheadEnabled = settings.getBoolean(PrefKeys.ENABLE_READAHEAD, PrefDefaults.ENABLE_READAHEAD); + + mAutoPlPlaycounts = settings.getInt(PrefKeys.AUTOPLAYLIST_PLAYCOUNTS, PrefDefaults.AUTOPLAYLIST_PLAYCOUNTS); + + PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE); + mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VanillaMusic:PlaybackService"); + + mReceiver = new Receiver(); + IntentFilter filter = new IntentFilter(); + filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); + filter.addAction(Intent.ACTION_SCREEN_ON); + registerReceiver(mReceiver, filter); + + MediaLibrary.registerLibraryObserver(mObserver); + + mRemoteControlClient = new RemoteControl().getClient(this); + mRemoteControlClient.initializeRemote(); + + mMediaSessionTracker = new MediaSessionTracker(this); + + int syncMode = Integer.parseInt(settings.getString(PrefKeys.PLAYLIST_SYNC_MODE, PrefDefaults.PLAYLIST_SYNC_MODE)); + boolean exportRelativePaths = settings.getBoolean(PrefKeys.PLAYLIST_EXPORT_RELATIVE_PATHS, PrefDefaults.PLAYLIST_EXPORT_RELATIVE_PATHS); + String syncFolder = settings.getString(PrefKeys.PLAYLIST_SYNC_FOLDER, PrefDefaults.PLAYLIST_SYNC_FOLDER); + mPlaylistObserver = new PlaylistObserver(this, syncFolder, syncMode, exportRelativePaths); + + mLooper = thread.getLooper(); + mHandler = new Handler(mLooper, this); + + initWidgets(); + + updateState(state); + setCurrentSong(0); + + sInstance = this; + synchronized (sWait) { + sWait.notifyAll(); + } + + mAccelFiltered = 0.0f; + mAccelLast = SensorManager.GRAVITY_EARTH; + setupSensor(); + + ScheduledLibraryUpdate.scheduleUpdate(this); + } + + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (intent != null) { + final String action = intent.getAction(); + final boolean earlyNotification = intent.hasExtra(EXTRA_EARLY_NOTIFICATION); + final boolean forceNotification = intent.hasExtra(EXTRA_FORCE_NOTIFICATION); + + if (earlyNotification) { + Song song = mCurrentSong != null ? mCurrentSong : new Song(-1); + startForeground(NOTIFICATION_ID, createNotification(song, mState)); + } + + if (ACTION_TOGGLE_PLAYBACK.equals(action)) { + playPause(forceNotification); + } else if (ACTION_TOGGLE_PLAYBACK_DELAYED.equals(action)) { + if (mHandler.hasMessages(MSG_CALL_GO, Integer.valueOf(0))) { + mHandler.removeMessages(MSG_CALL_GO, Integer.valueOf(0)); + Intent launch = new Intent(this, LibraryActivity.class); + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + launch.setAction(Intent.ACTION_MAIN); + startActivity(launch); + } else { + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_CALL_GO, 0, 0, Integer.valueOf(0)), 400); + } + } else if (ACTION_NEXT_SONG.equals(action)) { + shiftCurrentSong(SongTimeline.SHIFT_NEXT_SONG); + } else if (ACTION_NEXT_SONG_AUTOPLAY.equals(action)) { + shiftCurrentSong(SongTimeline.SHIFT_NEXT_SONG); + play(); + } else if (ACTION_NEXT_SONG_DELAYED.equals(action)) { + if (mHandler.hasMessages(MSG_CALL_GO, Integer.valueOf(1))) { + mHandler.removeMessages(MSG_CALL_GO, Integer.valueOf(1)); + Intent launch = new Intent(this, LibraryActivity.class); + launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + launch.setAction(Intent.ACTION_MAIN); + startActivity(launch); + } else { + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_CALL_GO, 1, 0, Integer.valueOf(1)), 400); + } + } else if (ACTION_PREVIOUS_SONG.equals(action)) { + rewindCurrentSong(); + } else if (ACTION_PREVIOUS_SONG_AUTOPLAY.equals(action)) { + rewindCurrentSong(); + play(); + } else if (ACTION_PLAY.equals(action)) { + play(); + } else if (ACTION_PAUSE.equals(action)) { + pause(); + } else if (ACTION_CYCLE_REPEAT.equals(action)) { + cycleFinishAction(); + } else if (ACTION_CYCLE_SHUFFLE.equals(action)) { + cycleShuffle(); + } else if (ACTION_RANDOM_MIX_AUTOPLAY.equals(action)) { + pause(); + emptyQueue(); + setFinishAction(SongTimeline.FINISH_RANDOM); + // We can't use play() here as setFinishAction() is handled in the background. + // We therefore send a GO message to the same queue, so it will get handled as + // soon as the queue is ready. + mHandler.sendEmptyMessage(MSG_CALL_GO); + } else if (ACTION_FROM_TYPE_ID_AUTOPLAY.equals(action)) { + int type = intent.getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID); + long id = intent.getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID); + QueryTask query = MediaUtils.buildQuery(type, id, Song.FILLED_PROJECTION, null); + // Flush the queue and start playing: + query.mode = SongTimeline.MODE_PLAY; + addSongs(query); + } + } + + return START_NOT_STICKY; + } + + @Override + public void onDestroy() + { + sInstance = null; + + mLooper.quit(); + + // clear the notification + stopForeground(true); + + // defer wakelock and close audioFX + enterSleepState(); + + // stop getting preference changes. + SharedPrefHelper.getSettings(this).unregisterOnSharedPreferenceChangeListener(this); + + // shutdown all observers. + MediaLibrary.unregisterLibraryObserver(mObserver); + mPlaylistObserver.unregister(); + + if (mMediaPlayer != null) { + mMediaPlayer.release(); + mMediaPlayer = null; + } + + if (mPreparedMediaPlayer != null) { + mPreparedMediaPlayer.release(); + mPreparedMediaPlayer = null; + } + + try { + unregisterReceiver(mReceiver); + } catch (IllegalArgumentException e) { + // we haven't registered the receiver yet + } + + if (mSensorManager != null) + mSensorManager.unregisterListener(this); + + if (mRemoteControlClient != null) + mRemoteControlClient.unregisterRemote(); + + if (mMediaSessionTracker != null) + mMediaSessionTracker.release(); + + super.onDestroy(); + } + + /** + * Returns a new MediaPlayer object + */ + private VanillaMediaPlayer getNewMediaPlayer() { + VanillaMediaPlayer mp = new VanillaMediaPlayer(this); + mp.setAudioStreamType(AudioManager.STREAM_MUSIC); + mp.setOnCompletionListener(this); + mp.setOnErrorListener(this); + return mp; + } + + public void prepareMediaPlayer(VanillaMediaPlayer mp, String path) throws IOException{ + mp.setDataSource(path); + mp.prepare(); + applyReplayGain(mp); + } + + /** + * Checks if we need to update the play/skipcounter for this action + * + * @param delta One of the SongTimeline.SHIFT_* + */ + private void preparePlayCountsUpdate(int delta) { + if (isPlaying()) { + double pctPlayed = (double)getPosition()/getDuration(); + int action = 0; + + if (delta == SongTimeline.SHIFT_KEEP_SONG && pctPlayed >= 0.8) { + action = 1; // song is playing again and had more than 0.8pct -> count this + } else if(delta == SongTimeline.SHIFT_NEXT_SONG && pctPlayed <= 0.5) { + action = -1; + } + + if (action != 0) { + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_PLAYCOUNTS, action, 0, mCurrentSong), 800); + } + } + } + + /** + * Make sure that the current ReplayGain volume matches + * the (maybe just changed) user settings + */ + private void refreshReplayGainValues() { + if (mMediaPlayer != null) { + applyReplayGain(mMediaPlayer); + } + if (mPreparedMediaPlayer != null) { + applyReplayGain(mPreparedMediaPlayer); + } + } + + private void refreshDuckingValues() { + float duckingFactor = ((float) mVolumeDuringDucking)/100f; + if (mMediaPlayer != null) { + mMediaPlayer.setDuckingFactor(duckingFactor); + } + if (mPreparedMediaPlayer != null) { + mPreparedMediaPlayer.setDuckingFactor(duckingFactor); + } + } + + /*** + * Reads the replay gain value of the media players data source + * and adjusts the volume + */ + private void applyReplayGain(VanillaMediaPlayer mp) { + + BastpUtil.GainValues rg = getReplayGainValues(mp.getDataSource()); + float adjust = 0f; + + if (mReplayGainAlbumEnabled) { + adjust = (rg.track != 0 ? rg.track : adjust); // Album gain enabled, but we use the track gain as a backup. + adjust = (rg.album != 0 ? rg.album : adjust); // If album gain is present, we will prefer it. + } + + if (mReplayGainTrackEnabled || (mReplayGainAlbumEnabled && adjust == 0)) { + adjust = (rg.album != 0 ? rg.album : adjust); // Track gain enabled, but we use the album gain as a backup. + adjust = (rg.track != 0 ? rg.track : adjust); // If track gain is present, we will prefer it. + } + + if (!rg.found) { + // No replay gain information found: adjust volume if requested by user. + adjust = (mReplayGainUntaggedDeBump-150)/10f; + } else { + // This song has some replay gain info, we are now going to apply the 'bump' value + // The preferences stores the raw value of the seekbar, that's 0-150 + // But we want -15 <-> +15, so 75 shall be zero. + adjust += 2*(mReplayGainBump-75)/10f; // 2* -> we want +-15, not +-7.5 + } + + if(mReplayGainAlbumEnabled == false && mReplayGainTrackEnabled == false) { + // Feature is disabled: Make sure that we are going to 100% volume. + adjust = 0f; + } + + float rg_result = ((float)Math.pow(10, (adjust/20) ))*mFadeOut; + if(rg_result > 1.0f) { + rg_result = 1.0f; // Android would IGNORE the change if this is > 1 and we would end up with the wrong volume. + } else if (rg_result < 0.0f) { + rg_result = 0.0f; + } + mp.setReplayGain(rg_result); + } + + /** + * Returns the (hopefully cached) replaygain + * values of given file + */ + public BastpUtil.GainValues getReplayGainValues(String path) { + return mBastpUtil.getReplayGainValues(path); + } + + /** + * Prepares PlaybackService to sleep / shutdown + * Closes any open AudioFX session and releases + * our wakelock if held + */ + private synchronized void enterSleepState() + { + if (mMediaPlayer != null) { + if (mMediaPlayerAudioFxActive) { + mMediaPlayer.closeAudioFx(); + mMediaPlayerAudioFxActive = false; + } + saveState(mMediaPlayer.getCurrentPosition()); + } + + if (mWakeLock != null && mWakeLock.isHeld()) + mWakeLock.release(); + } + + /** + * Destroys any currently prepared MediaPlayer and + * re-creates a newone if needed. + */ + private void triggerGaplessUpdate() { + if(mMediaPlayerInitialized != true) + return; + + if(mDisableGaplessPlayback) + return; + + boolean doGapless = false; + int fa = finishAction(mState); + Song nextSong = getSong(1); + + if( nextSong != null + && fa != SongTimeline.FINISH_REPEAT_CURRENT + && fa != SongTimeline.FINISH_STOP_CURRENT + && !mTimeline.isEndOfQueue() ) { + doGapless = true; + } + else { + Log.d("VanillaMusic", "Must not create new media player object"); + } + + if(doGapless == true) { + try { + if(nextSong.path.equals(mPreparedMediaPlayer.getDataSource()) == false) { + // Prepared MP has a different data source: We need to re-initalize + // it and set it as the next MP for the active media player + mPreparedMediaPlayer.reset(); + prepareMediaPlayer(mPreparedMediaPlayer, nextSong.path); + mMediaPlayer.setNextMediaPlayer(mPreparedMediaPlayer); + } + if(mMediaPlayer.hasNextMediaPlayer() == false) { + // We can reuse the prepared MediaPlayer but the current instance lacks + // a link to it + mMediaPlayer.setNextMediaPlayer(mPreparedMediaPlayer); + } + } catch (IOException | IllegalArgumentException e) { + Log.e("VanillaMusic", "Exception while preparing gapless media player: " + e); + mMediaPlayer.setNextMediaPlayer(null); + mPreparedMediaPlayer.reset(); + } + } else { + if(mMediaPlayer.hasNextMediaPlayer()) { + mMediaPlayer.setNextMediaPlayer(null); + // There is no need to cleanup mPreparedMediaPlayer + } + } + } + + /** + * Stops or starts the readahead thread + */ + private void triggerReadAhead() { + Song song = mCurrentSong; + if((mState & FLAG_PLAYING) != 0 && song != null) { + mReadahead.setSong(song); + } else { + mReadahead.pause(); + } + } + + /** + * Setup the accelerometer. + */ + private void setupSensor() + { + if (mShakeAction == Action.Nothing) { + if (mSensorManager != null) + mSensorManager.unregisterListener(this); + } else { + if (mSensorManager == null) + mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); + mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI); + } + } + + + private void loadPreference(String key) + { + SharedPreferences settings = SharedPrefHelper.getSettings(this); + if (PrefKeys.HEADSET_PAUSE.equals(key)) { + mHeadsetPause = settings.getBoolean(PrefKeys.HEADSET_PAUSE, PrefDefaults.HEADSET_PAUSE); + } else if (PrefKeys.NOTIFICATION_ACTION.equals(key)) { + mNotificationAction = createNotificationAction(settings); + updateNotification(); + } else if (PrefKeys.NOTIFICATION_VISIBILITY.equals(key)){ + mNotificationVisibility = Integer.parseInt(settings.getString(PrefKeys.NOTIFICATION_VISIBILITY, PrefDefaults.NOTIFICATION_VISIBILITY)); + // This is the only way to remove a notification created by + // startForeground(), even if we are not currently in foreground + // mode. + stopForeground(true); + updateNotification(); + } else if (PrefKeys.SCROBBLE.equals(key)) { + mScrobble = settings.getBoolean(PrefKeys.SCROBBLE, PrefDefaults.SCROBBLE); + } else if (PrefKeys.COVER_ON_LOCKSCREEN.equals(key)) { + mRemoteControlClient.reloadPreference(); + } else if (PrefKeys.USE_IDLE_TIMEOUT.equals(key) || PrefKeys.IDLE_TIMEOUT.equals(key)) { + mIdleTimeout = settings.getBoolean(PrefKeys.USE_IDLE_TIMEOUT, PrefDefaults.USE_IDLE_TIMEOUT) ? settings.getInt(PrefKeys.IDLE_TIMEOUT, PrefDefaults.IDLE_TIMEOUT) : 0; + userActionTriggered(); + } else if (PrefKeys.COVERLOADER_ANDROID.equals(key)) { + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_ANDROID, PrefDefaults.COVERLOADER_ANDROID) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_ANDROID : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_ANDROID); + CoverCache.evictAll(); + } else if (PrefKeys.COVERLOADER_VANILLA.equals(key)) { + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_VANILLA, PrefDefaults.COVERLOADER_VANILLA) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_VANILLA : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_VANILLA); + CoverCache.evictAll(); + } else if (PrefKeys.COVERLOADER_SHADOW.equals(key)) { + CoverCache.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_SHADOW, PrefDefaults.COVERLOADER_SHADOW) ? CoverCache.mCoverLoadMode | CoverCache.COVER_MODE_SHADOW : CoverCache.mCoverLoadMode & ~(CoverCache.COVER_MODE_SHADOW); + CoverCache.evictAll(); + } else if (PrefKeys.HEADSET_ONLY.equals(key)) { + mHeadsetOnly = settings.getBoolean(key, PrefDefaults.HEADSET_ONLY); + if (mHeadsetOnly && isSpeakerOn()) + unsetFlag(FLAG_PLAYING); + } else if (PrefKeys.STOCK_BROADCAST.equals(key)) { + mStockBroadcast = settings.getBoolean(key, PrefDefaults.STOCK_BROADCAST); + } else if (PrefKeys.ENABLE_SHAKE.equals(key) || PrefKeys.SHAKE_ACTION.equals(key)) { + mShakeAction = settings.getBoolean(PrefKeys.ENABLE_SHAKE, PrefDefaults.ENABLE_SHAKE) ? Action.getAction(settings, PrefKeys.SHAKE_ACTION, PrefDefaults.SHAKE_ACTION) : Action.Nothing; + setupSensor(); + } else if (PrefKeys.SHAKE_THRESHOLD.equals(key)) { + mShakeThreshold = settings.getInt(PrefKeys.SHAKE_THRESHOLD, PrefDefaults.SHAKE_THRESHOLD) / 10.0f; + } else if (PrefKeys.ENABLE_TRACK_REPLAYGAIN.equals(key)) { + mReplayGainTrackEnabled = settings.getBoolean(PrefKeys.ENABLE_TRACK_REPLAYGAIN, PrefDefaults.ENABLE_TRACK_REPLAYGAIN); + refreshReplayGainValues(); + } else if (PrefKeys.ENABLE_ALBUM_REPLAYGAIN.equals(key)) { + mReplayGainAlbumEnabled = settings.getBoolean(PrefKeys.ENABLE_ALBUM_REPLAYGAIN, PrefDefaults.ENABLE_ALBUM_REPLAYGAIN); + refreshReplayGainValues(); + } else if (PrefKeys.REPLAYGAIN_BUMP.equals(key)) { + mReplayGainBump = settings.getInt(PrefKeys.REPLAYGAIN_BUMP, PrefDefaults.REPLAYGAIN_BUMP); + refreshReplayGainValues(); + } else if (PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP.equals(key)) { + mReplayGainUntaggedDeBump = settings.getInt(PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP, PrefDefaults.REPLAYGAIN_UNTAGGED_DEBUMP); + refreshReplayGainValues(); + } else if (PrefKeys.VOLUME_DURING_DUCKING.equals(key)) { + mVolumeDuringDucking = settings.getInt(PrefKeys.VOLUME_DURING_DUCKING, PrefDefaults.VOLUME_DURING_DUCKING); + refreshDuckingValues(); + } else if (PrefKeys.IGNORE_AUDIOFOCUS_LOSS.equals(key)) { + mIgnoreAudioFocusLoss = settings.getBoolean(PrefKeys.IGNORE_AUDIOFOCUS_LOSS, PrefDefaults.IGNORE_AUDIOFOCUS_LOSS); + } else if (PrefKeys.ENABLE_READAHEAD.equals(key)) { + mReadaheadEnabled = settings.getBoolean(PrefKeys.ENABLE_READAHEAD, PrefDefaults.ENABLE_READAHEAD); + } else if (PrefKeys.AUTOPLAYLIST_PLAYCOUNTS.equals(key)) { + mAutoPlPlaycounts = settings.getInt(PrefKeys.AUTOPLAYLIST_PLAYCOUNTS, PrefDefaults.AUTOPLAYLIST_PLAYCOUNTS); + } else if (PrefKeys.PLAYLIST_SYNC_MODE.equals(key) || PrefKeys.PLAYLIST_SYNC_FOLDER.equals(key) || PrefKeys.PLAYLIST_EXPORT_RELATIVE_PATHS.equals(key)) { + int syncMode = Integer.parseInt(settings.getString(PrefKeys.PLAYLIST_SYNC_MODE, PrefDefaults.PLAYLIST_SYNC_MODE)); + boolean exportRelativePaths = settings.getBoolean(PrefKeys.PLAYLIST_EXPORT_RELATIVE_PATHS, PrefDefaults.PLAYLIST_EXPORT_RELATIVE_PATHS); + String syncFolder = settings.getString(PrefKeys.PLAYLIST_SYNC_FOLDER, PrefDefaults.PLAYLIST_SYNC_FOLDER); + + mPlaylistObserver.unregister(); + mPlaylistObserver = new PlaylistObserver(this, syncFolder, syncMode, exportRelativePaths); + } else if (PrefKeys.SELECTED_THEME.equals(key) || PrefKeys.DISPLAY_MODE.equals(key)) { + // Theme changed: trigger a restart of all registered activites + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).recreate(); + } else if (PrefKeys.DISABLE_GAPLESS_PLAYBACK.equals(key)) { + mDisableGaplessPlayback = settings.getBoolean(PrefKeys.DISABLE_GAPLESS_PLAYBACK, PrefDefaults.DISABLE_GAPLESS_PLAYBACK); + } + + /* Tell androids cloud-backup manager that we just changed our preferences */ + (new BackupManager(this)).dataChanged(); + } + + /** + * Set a state flag. + */ + public void setFlag(int flag) + { + synchronized (mStateLock) { + updateState(mState | flag); + } + } + + /** + * Unset a state flag. + */ + public void unsetFlag(int flag) + { + synchronized (mStateLock) { + updateState(mState & ~flag); + } + } + + /** + * Return true if audio would play through the speaker. + */ + @SuppressWarnings("deprecation") + private boolean isSpeakerOn() + { + // Devices we consider to not be speakers. + final Integer[] headsetTypes = { AudioDeviceInfo.TYPE_BLUETOOTH_A2DP, AudioDeviceInfo.TYPE_BLUETOOTH_SCO, + AudioDeviceInfo.TYPE_WIRED_HEADSET, AudioDeviceInfo.TYPE_WIRED_HEADPHONES, + AudioDeviceInfo.TYPE_USB_HEADSET, AudioDeviceInfo.TYPE_USB_DEVICE }; + + boolean result = true; + AudioDeviceInfo[] devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS); + for (AudioDeviceInfo device: devices) { + Log.v("VanillaMusic", "AudioDeviceInfo type = " + device.getType()); + if (Arrays.asList(headsetTypes).contains(device.getType())) { + result = false; + break; + } + } + return result; + } + + /** + * Modify the service state. + * + * @param state Union of PlaybackService.STATE_* flags + * @return The new state + */ + private int updateState(int state) + { + if ((state & (FLAG_NO_MEDIA|FLAG_ERROR|FLAG_EMPTY_QUEUE)) != 0 || mHeadsetOnly && isSpeakerOn()) + state &= ~FLAG_PLAYING; + + int oldState = mState; + mState = state; + + if (state != oldState) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_PROCESS_STATE, oldState, state)); + mHandler.sendMessage(mHandler.obtainMessage(MSG_BROADCAST_CHANGE, state, 0, new TimestampedObject(null))); + } + + return state; + } + + private void processNewState(int oldState, int state) + { + int toggled = oldState ^ state; + + if ( ((toggled & FLAG_PLAYING) != 0) && mCurrentSong != null) { // user requested to start playback AND we have a song selected + if ((state & FLAG_PLAYING) != 0) { + + // We get noisy: Acquire a new AudioFX session if required + if (mMediaPlayerAudioFxActive == false) { + mMediaPlayer.openAudioFx(); + mMediaPlayerAudioFxActive = true; + } + + if (mMediaPlayerInitialized) + mMediaPlayer.start(); + + // Update the notification with the current song information. + startForeground(NOTIFICATION_ID, createNotification(mCurrentSong, mState)); + + final int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); + if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { + unsetFlag(FLAG_PLAYING); + } + + mHandler.removeMessages(MSG_ENTER_SLEEP_STATE); + try { + if (mWakeLock != null && mWakeLock.isHeld() == false) + mWakeLock.acquire(); + } catch (SecurityException e) { + // Don't have WAKE_LOCK permission + } + } else { + if (mMediaPlayerInitialized) + mMediaPlayer.pause(); + + // We are switching into background mode. The notification will be removed + // unless we forcefully show it (or the user selected to always show it) + // In both cases we will update the notification to reflect the + // actual playback state (or to hit cancel() as this is required to + // get rid of it if it was created via notify()) + boolean removeNotification = (mForceNotificationVisible == false && mNotificationVisibility != VISIBILITY_ALWAYS); + stopForeground(removeNotification); + updateNotification(); + + // Delay entering deep sleep. This allows the headset + // button to continue to function for a short period after + // pausing and keeps the AudioFX session open + mHandler.sendEmptyMessageDelayed(MSG_ENTER_SLEEP_STATE, SLEEP_STATE_DELAY); + } + + setupSensor(); + } + + if ((toggled & FLAG_NO_MEDIA) != 0 && (state & FLAG_NO_MEDIA) != 0) { + Song song = mCurrentSong; + if (song != null && mMediaPlayerInitialized) { + mPendingSeek = mMediaPlayer.getCurrentPosition(); + mPendingSeekSong = song.id; + } + } + + if ((toggled & MASK_SHUFFLE) != 0) + mTimeline.setShuffleMode(shuffleMode(state)); + if ((toggled & MASK_FINISH) != 0) + mTimeline.setFinishAction(finishAction(state)); + + if((toggled & FLAG_DUCKING) != 0) { + boolean isDucking = (state & FLAG_DUCKING) != 0; + mMediaPlayer.setIsDucking(isDucking); + mPreparedMediaPlayer.setIsDucking(isDucking); + } + } + + private void broadcastChange(int state, Song song, long uptime) + { + if (state != -1) { + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).setState(uptime, state); + } + + if (song != null) { + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).setSong(uptime, song); + } + + updateWidgets(); + + if (mReadaheadEnabled) + triggerReadAhead(); + + mRemoteControlClient.updateRemote(mCurrentSong, mState, mForceNotificationVisible); + mMediaSessionTracker.updateSession(mCurrentSong, mState); + + scrobbleBroadcast(); + } + + /** + * Check if there are any instances of each widget. + */ + private void initWidgets() + { + AppWidgetManager manager = AppWidgetManager.getInstance(this); + OneCellWidget.checkEnabled(this, manager); + FourSquareWidget.checkEnabled(this, manager); + FourLongWidget.checkEnabled(this, manager); + FourWhiteWidget.checkEnabled(this, manager); + WidgetD.checkEnabled(this, manager); + WidgetE.checkEnabled(this, manager); + } + + /** + * Update the widgets with the current song and state. + */ + private void updateWidgets() + { + AppWidgetManager manager = AppWidgetManager.getInstance(this); + Song song = mCurrentSong; + int state = mState; + OneCellWidget.updateWidget(this, manager, song, state); + FourLongWidget.updateWidget(this, manager, song, state); + FourSquareWidget.updateWidget(this, manager, song, state); + FourWhiteWidget.updateWidget(this, manager, song, state); + WidgetD.updateWidget(this, manager, song, state); + WidgetE.updateWidget(this, manager, song, state); + } + + /** + * Scrobbles and broadcasts the currently playing song + */ + private void scrobbleBroadcast() { + Song song = mCurrentSong; + if (song == null) + return; + + if (!mStockBroadcast && !mScrobble) + return; + + long[] androidIds = MediaUtils.getAndroidMediaIds(getApplicationContext(), song); + if (mStockBroadcast) { + Intent intent = new Intent("com.android.music.playstatechanged"); + intent.putExtra("playing", (mState & FLAG_PLAYING) != 0); + intent.putExtra("track", song.title); + intent.putExtra("album", song.album); + intent.putExtra("artist", song.artist); + if (androidIds[0] != -1) { + intent.putExtra("songid", androidIds[0]); + intent.putExtra("albumid", androidIds[1]); + } + sendBroadcast(intent); + } + + if (mScrobble) { + Intent intent = new Intent("net.jjc1138.android.scrobbler.action.MUSIC_STATUS"); + intent.putExtra("playing", (mState & FLAG_PLAYING) != 0); + if (androidIds[0] != -1) + intent.putExtra("id", androidIds[0]); + sendBroadcast(intent); + } + } + + private void updateNotification() + { + if (mCurrentSong != null) { + // We always update the notification, even if we are about to cancel it as it may still stick around + // for a few seconds and we want to ensure that we are showing the correct state. + mNotificationHelper.notify(NOTIFICATION_ID, createNotification(mCurrentSong, mState)); + } + if (!(mForceNotificationVisible || + mNotificationVisibility == VISIBILITY_ALWAYS || + mNotificationVisibility == VISIBILITY_WHEN_PLAYING && (mState & FLAG_PLAYING) != 0)) { + mNotificationHelper.cancel(NOTIFICATION_ID); + } + } + + /** + * Enqueues a Toast message to be shown. + */ + private void showToast(int resId, int duration) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_TOAST, duration, resId)); + } + + private void showToast(CharSequence text, int duration) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_SHOW_TOAST, duration, 0, text)); + } + + /** + * Start playing if currently paused. + * + * @return The new state after this is called. + */ + public int play() + { + synchronized (mStateLock) { + if ((mState & FLAG_EMPTY_QUEUE) != 0) { + setFinishAction(SongTimeline.FINISH_RANDOM); + showToast(R.string.random_enabling, Toast.LENGTH_SHORT); + } + + int state = updateState(mState | FLAG_PLAYING); + userActionTriggered(); + return state; + } + } + + /** + * Pause if currently playing. + * + * @return The new state after this is called. + */ + public int pause() + { + synchronized (mStateLock) { + mTransientAudioLoss = false; // do not resume playback as this pause was user initiated + int state = updateState(mState & ~FLAG_PLAYING & ~FLAG_DUCKING); + userActionTriggered(); + return state; + } + } + + /** + * If playing, pause. If paused, play. + * + * @return The new state after this is called. + */ + public int playPause(boolean forceNotification) + { + synchronized (mStateLock) { + mForceNotificationVisible = forceNotification; + if ((mState & FLAG_PLAYING) != 0) + return pause(); + else + return play(); + } + } + + + /** + * Change the end action (e.g. repeat, random). + * + * @param action The new action. One of SongTimeline.FINISH_*. + * @return The new state after this is called. + */ + public int setFinishAction(int action) + { + synchronized (mStateLock) { + return updateState(mState & ~MASK_FINISH | action << SHIFT_FINISH); + } + } + + /** + * Cycle repeat mode. Disables random mode. + * + * @return The new state after this is called. + */ + public int cycleFinishAction() + { + synchronized (mStateLock) { + int mode = finishAction(mState) + 1; + if (mode > SongTimeline.FINISH_RANDOM) + mode = SongTimeline.FINISH_STOP; + return setFinishAction(mode); + } + } + + /** + * Change the shuffle mode. + * + * @param mode The new mode. One of SongTimeline.SHUFFLE_*. + * @return The new state after this is called. + */ + public int setShuffleMode(int mode) + { + synchronized (mStateLock) { + return updateState(mState & ~MASK_SHUFFLE | mode << SHIFT_SHUFFLE); + } + } + + /** + * Cycle shuffle mode. + * + * @return The new state after this is called. + */ + public int cycleShuffle() + { + synchronized (mStateLock) { + int mode = shuffleMode(mState) + 1; + if (mode > SongTimeline.SHUFFLE_ALBUMS) + mode = SongTimeline.SHUFFLE_NONE; // end reached: switch to none + return setShuffleMode(mode); + } + } + + /** + * Move to the next or previous song or album in the timeline. + * + * @param delta One of SongTimeline.SHIFT_*. 0 can also be passed to + * initialize the current song with media player, notification, + * broadcasts, etc. + * @return The new current song + */ + private Song setCurrentSong(int delta) + { + if (mMediaPlayer == null) + return null; + + if (mMediaPlayer.isPlaying()) + mMediaPlayer.stop(); + + Song song = mTimeline.shiftCurrentSong(delta); + mCurrentSong = song; + if (song == null) { + if (MediaUtils.isSongAvailable(getApplicationContext())) { + int flag = finishAction(mState) == SongTimeline.FINISH_RANDOM ? FLAG_ERROR : FLAG_EMPTY_QUEUE; + synchronized (mStateLock) { + updateState((mState | flag) & ~FLAG_NO_MEDIA); + } + return null; + } else { + // we don't have any songs : / + synchronized (mStateLock) { + updateState((mState | FLAG_NO_MEDIA) & ~FLAG_EMPTY_QUEUE); + } + return null; + } + } else if ((mState & (FLAG_NO_MEDIA|FLAG_EMPTY_QUEUE)) != 0) { + synchronized (mStateLock) { + updateState(mState & ~(FLAG_EMPTY_QUEUE|FLAG_NO_MEDIA)); + } + } + + mHandler.removeMessages(MSG_PROCESS_SONG); + + mMediaPlayerInitialized = false; + mHandler.sendMessage(mHandler.obtainMessage(MSG_PROCESS_SONG, song)); + mHandler.sendMessage(mHandler.obtainMessage(MSG_BROADCAST_CHANGE, -1, 0, new TimestampedObject(song))); + return song; + } + + private void processSong(Song song) + { + /* Save our 'current' state as the try block may set the ERROR flag (which clears the PLAYING flag */ + boolean playing = (mState & FLAG_PLAYING) != 0; + + try { + mMediaPlayerInitialized = false; + mMediaPlayer.reset(); + + if(mPreparedMediaPlayer.isPlaying()) { + // The prepared media player is playing as the previous song + // reched its end 'naturally' (-> gapless) + // We can now swap mPreparedMediaPlayer and mMediaPlayer + VanillaMediaPlayer tmpPlayer = mMediaPlayer; + mMediaPlayer = mPreparedMediaPlayer; + mPreparedMediaPlayer = tmpPlayer; // this was mMediaPlayer and is in reset() state + } + else { + prepareMediaPlayer(mMediaPlayer, song.path); + } + + + mMediaPlayerInitialized = true; + // Cancel any pending gapless updates and re-send them + mHandler.removeMessages(MSG_GAPLESS_UPDATE); + mHandler.sendEmptyMessage(MSG_GAPLESS_UPDATE); + + if (mPendingSeek != 0) { + if (mPendingSeekSong == song.id) + mMediaPlayer.seekTo(mPendingSeek); + // Clear this even if we did not seek: + // We somehow managed to play a different song, so + // whatever we were supposed to seek to, is invalid now. + mPendingSeek = 0; + } + + if ((mState & FLAG_PLAYING) != 0) + mMediaPlayer.start(); + + if ((mState & FLAG_ERROR) != 0) { + mErrorMessage = null; + updateState(mState & ~FLAG_ERROR); + } + mSkipBroken = 0; /* File not broken, reset skip counter */ + } catch (IOException e) { + mErrorMessage = getResources().getString(R.string.song_load_failed, song.path); + updateState(mState | FLAG_ERROR); + showToast(mErrorMessage, Toast.LENGTH_LONG); + Log.e("VanillaMusic", "IOException", e); + + /* Automatically advance to next song IF we are currently playing or already did skip something + * This will stop after skipping 10 songs to avoid endless loops (queue full of broken stuff */ + if(!mTimeline.isEndOfQueue() && getSong(1) != null && (playing || (mSkipBroken > 0 && mSkipBroken < 10))) { + mSkipBroken++; + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SKIP_BROKEN_SONG, getTimelinePosition(), 0), 1000); + } + + } + + updateNotification(); + + } + + @Override + public void onCompletion(MediaPlayer player) + { + + // Count this song as played + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_PLAYCOUNTS, 1, 0, mCurrentSong), 800); + + if (finishAction(mState) == SongTimeline.FINISH_REPEAT_CURRENT) { + setCurrentSong(0); + } else if (finishAction(mState) == SongTimeline.FINISH_STOP_CURRENT) { + unsetFlag(FLAG_PLAYING); + setCurrentSong(+1); + } else { + if (mTimeline.isEndOfQueue()) { + unsetFlag(FLAG_PLAYING); + } + setCurrentSong(+1); + } + } + + @Override + public boolean onError(MediaPlayer player, int what, int extra) + { + Log.e("VanillaMusic", "MediaPlayer error: " + what + ' ' + extra); + + return true; + } + + /** + * Returns the song <code>delta</code> places away from the current + * position. + * + * @see SongTimeline#getSong(int) + */ + public Song getSong(int delta) + { + if (mTimeline == null) + return null; + if (delta == 0) + return mCurrentSong; + return mTimeline.getSong(delta); + } + + private class Receiver extends BroadcastReceiver { + @Override + public void onReceive(Context content, Intent intent) + { + String action = intent.getAction(); + + if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) { + if (mHeadsetPause) { + pause(); + } + } else if (Intent.ACTION_SCREEN_ON.equals(action)) { + userActionTriggered(); + } + } + } + + public void onMediaChange() + { + if (MediaUtils.isSongAvailable(getApplicationContext())) { + if ((mState & FLAG_NO_MEDIA) != 0) + setCurrentSong(0); + } else { + setFlag(FLAG_NO_MEDIA); + } + + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).onMediaChange(); + + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences settings, String key) + { + loadPreference(key); + } + + /** + * Releases mWakeLock and closes any open AudioFx sessions + */ + private static final int MSG_ENTER_SLEEP_STATE = 1; + /** + * Run the given query and add the results to the timeline. + * + * obj is the QueryTask. arg1 is the add mode (one of SongTimeline.MODE_*) + */ + private static final int MSG_QUERY = 2; + /** + * This message is sent with a delay specified by a user preference. After + * this delay, assuming no new IDLE_TIMEOUT messages cancel it, playback + * will be stopped. + */ + private static final int MSG_IDLE_TIMEOUT = 4; + /** + * Decrease the volume gradually over five seconds, pausing when 0 is + * reached. + * + * arg1 should be the progress in the fade as a percentage, 1-100. + */ + private static final int MSG_FADE_OUT = 7; + /** + * If arg1 is 0, calls {@link PlaybackService#playPause()}. + * Otherwise, calls {@link PlaybackService#setCurrentSong(int)} with arg1. + */ + private static final int MSG_CALL_GO = 8; + /** + * The combination of (current song, current playback state) changed. + */ + private static final int MSG_BROADCAST_CHANGE = 10; + private static final int MSG_SAVE_STATE = 12; + private static final int MSG_PROCESS_SONG = 13; + private static final int MSG_PROCESS_STATE = 14; + private static final int MSG_SKIP_BROKEN_SONG = 15; + private static final int MSG_GAPLESS_UPDATE = 16; + private static final int MSG_UPDATE_PLAYCOUNTS = 17; + private static final int MSG_SHOW_TOAST = 18; + /** + * The current song's playback position changed. + */ + private static final int MSG_BROADCAST_SEEK = 19; + + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_CALL_GO: + if (message.arg1 == 0) + playPause(false); + else + setCurrentSong(message.arg1); + break; + case MSG_SAVE_STATE: + // For unexpected terminations: crashes, task killers, etc. + // In most cases onDestroy will handle this + saveState(0); + break; + case MSG_PROCESS_SONG: + processSong((Song)message.obj); + break; + case MSG_QUERY: + runQuery((QueryTask)message.obj); + break; + case MSG_IDLE_TIMEOUT: + if ((mState & FLAG_PLAYING) != 0) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_FADE_OUT, 0)); + } + break; + case MSG_FADE_OUT: + if (mFadeOut <= 0.0f) { + mIdleStart = SystemClock.elapsedRealtime(); + unsetFlag(FLAG_PLAYING); + } else { + mFadeOut -= 0.01f; + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_FADE_OUT, 0), 50); + } + refreshReplayGainValues(); /* Updates the volume using the new mFadeOut value */ + break; + case MSG_PROCESS_STATE: + processNewState(message.arg1, message.arg2); + break; + case MSG_BROADCAST_CHANGE: + TimestampedObject tso = (TimestampedObject)message.obj; + broadcastChange(message.arg1, (Song)tso.object, tso.uptime); + break; + case MSG_ENTER_SLEEP_STATE: + enterSleepState(); + break; + case MSG_SKIP_BROKEN_SONG: + /* Advance to next song if the user didn't already change. + * But we are restoring the Playing state in ANY case as we are most + * likely still stopped due to the error + * Note: This is somewhat racy with user input but also is the - by far - simplest + * solution */ + if(getTimelinePosition() == message.arg1) { + setCurrentSong(1); + } + // Optimistically claim to have recovered from this error + mErrorMessage = null; + unsetFlag(FLAG_ERROR); + mHandler.sendMessage(mHandler.obtainMessage(MSG_CALL_GO, 0, 0)); + break; + case MSG_GAPLESS_UPDATE: + triggerGaplessUpdate(); + break; + case MSG_UPDATE_PLAYCOUNTS: + Song song = (Song)message.obj; + boolean played = message.arg1 == 1; + PlayCountsHelper.countSong(getApplicationContext(), song, played); + // Update the playcounts playlist in ~20% of all cases if enabled + if (mAutoPlPlaycounts > 0 && Math.random() > 0.8) { + Context context = getApplicationContext(); + // Add an invisible whitespace to adjust our sorting + String playlistName = getString(R.string.autoplaylist_playcounts_name, mAutoPlPlaycounts); + long id = Playlist.createPlaylist(context, playlistName); + ArrayList<Long> items = PlayCountsHelper.getTopSongs(context, mAutoPlPlaycounts); + Playlist.addToPlaylist(context, id, items); + } + break; + case MSG_SHOW_TOAST: + CharSequence text = (CharSequence)message.obj; + int duration = message.arg1; + int resId = message.arg2; + if (text != null) { + Toast.makeText(this, text, duration).show(); + } else { + Toast.makeText(this, resId, duration).show(); + } + break; + case MSG_BROADCAST_SEEK: + mRemoteControlClient.updateRemote(mCurrentSong, mState, mForceNotificationVisible); + mMediaSessionTracker.updateSession(mCurrentSong, mState); + break; + default: + return false; + } + + return true; + } + + /** + * Returns the current service state. The state comprises several individual + * flags. + */ + public int getState() + { + synchronized (mStateLock) { + return mState; + } + } + + /** + * Returns the current position in current song in milliseconds. + */ + public int getPosition() + { + if (!mMediaPlayerInitialized) + return 0; + return mMediaPlayer.getCurrentPosition(); + } + + /** + * Returns the song duration in milliseconds. + */ + public int getDuration() + { + if (!mMediaPlayerInitialized) + return 0; + return mMediaPlayer.getDuration(); + } + + /** + * Returns the global audio session + */ + public int getAudioSession() { + // Must not be 'ready' or initialized: the audio session + // is set on object creation + return mMediaPlayer.getAudioSessionId(); + } + + /** + * Seek to a position in the current song. + * + * @param progress Proportion of song completed (where 1000 is the end of the song) + */ + public void seekToProgress(int progress) + { + if (!mMediaPlayerInitialized) + return; + long position = (long)mMediaPlayer.getDuration() * progress / 1000; + seekToPosition((int) position); + } + + /** + * Seeks to the given position in the current song. + * + * @param msec the offset in milliseconds from the start to seek to + */ + public void seekToPosition(int msec) { + if (!mMediaPlayerInitialized) { + return; + } + mMediaPlayer.seekTo(msec); + mHandler.sendEmptyMessage(MSG_BROADCAST_SEEK); + } + + @Override + public IBinder onBind(Intent intents) + { + return null; + } + + @Override + public void activeSongReplaced(int delta, Song song) + { + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).replaceSong(delta, song); + + if (delta == 0) + setCurrentSong(0); + } + + /** + * Delete all the songs in the given media set. Should be run on a + * background thread. + * + * @param type One of the TYPE_* constants, excluding playlists. + * @param id The MediaStore id of the media to delete. + * @return The number of songs deleted. + */ + public int deleteMedia(int type, long id) + { + int count = 0; + String[] projection = new String [] { MediaLibrary.SongColumns._ID, MediaLibrary.SongColumns.PATH }; + Cursor cursor = MediaUtils.buildQuery(type, id, projection, null).runQuery(getApplicationContext()); + + if (cursor != null) { + while (cursor.moveToNext()) { + if (new File(cursor.getString(1)).delete()) { + long songId = cursor.getLong(0); + MediaLibrary.removeSong(getApplicationContext(), songId); + mTimeline.removeSong(songId); + ++count; + } + } + cursor.close(); + } + return count; + } + + /** + * Move to next or previous song or album in the queue. + * + * @param delta One of SongTimeline.SHIFT_*. + * @return The new current song. + */ + public Song shiftCurrentSong(int delta) + { + preparePlayCountsUpdate(delta); + Song song = setCurrentSong(delta); + userActionTriggered(); + return song; + } + + /** + * Skips to the previous song OR rewinds the currently playing track, depending + * on the current position. + * + * @return The new current song + */ + public Song rewindCurrentSong() { + int delta = SongTimeline.SHIFT_PREVIOUS_SONG; + if(getPosition() > REWIND_AFTER_PLAYED_MS && getDuration() > REWIND_AFTER_PLAYED_MS*2) { + delta = SongTimeline.SHIFT_KEEP_SONG; + } + return shiftCurrentSong(delta); + } + + /** + * Resets the idle timeout countdown. Should be called by a user action + * has been triggered (new song chosen or playback toggled). + * + * If an idle fade out is actually in progress, aborts it and resets the + * volume. + */ + public void userActionTriggered() + { + mHandler.removeMessages(MSG_FADE_OUT); + mHandler.removeMessages(MSG_IDLE_TIMEOUT); + if (mIdleTimeout != 0) + mHandler.sendEmptyMessageDelayed(MSG_IDLE_TIMEOUT, mIdleTimeout * 1000); + + if (mFadeOut != 1.0f) { + mFadeOut = 1.0f; + refreshReplayGainValues(); + } + + long idleStart = mIdleStart; + if (idleStart != -1 && SystemClock.elapsedRealtime() - idleStart < IDLE_GRACE_PERIOD) { + mIdleStart = -1; + setFlag(FLAG_PLAYING); + } + } + + /** + * Run the query and add the results to the timeline. Should be called in the + * worker thread. + * + * @param query The query to run. + */ + private void runQuery(QueryTask query) + { + int count = mTimeline.addSongs(this, query); + + int text; + + switch (query.mode) { + case SongTimeline.MODE_PLAY: + case SongTimeline.MODE_PLAY_POS_FIRST: + case SongTimeline.MODE_PLAY_ID_FIRST: + text = R.plurals.playing; + if (count != 0 && (mState & FLAG_PLAYING) == 0) + setFlag(FLAG_PLAYING); + break; + case SongTimeline.MODE_FLUSH_AND_PLAY_NEXT: + case SongTimeline.MODE_ENQUEUE: + case SongTimeline.MODE_ENQUEUE_ID_FIRST: + case SongTimeline.MODE_ENQUEUE_POS_FIRST: + case SongTimeline.MODE_ENQUEUE_AS_NEXT: + text = R.plurals.enqueued; + break; + default: + throw new IllegalArgumentException("Invalid add mode: " + query.mode); + } + showToast(getResources().getQuantityString(text, count, count), Toast.LENGTH_SHORT); + } + + /** + * Run the query in the background and add the results to the timeline. + * + * @param query The query. + */ + public void addSongs(QueryTask query) + { + mHandler.sendMessage(mHandler.obtainMessage(MSG_QUERY, query)); + } + + + /** + * Enqueues all the songs with the same album/artist/genre as the passed + * song. + * + * This will clear the queue and place the first song from the group after + * the playing song. + * + * @param song The song to base the query on + * @param type The media type, one of MediaUtils.TYPE_ALBUM, TYPE_ARTIST, + * or TYPE_GENRE + */ + public void enqueueFromSong(Song song, int type) + { + if (song == null) + return; + + long id; + switch (type) { + case MediaUtils.TYPE_ARTIST: + id = song.artistId; + break; + case MediaUtils.TYPE_ALBUM: + id = song.albumId; + break; + case MediaUtils.TYPE_GENRE: + id = MediaUtils.queryGenreForSong(getApplicationContext(), song.id); + break; + default: + throw new IllegalArgumentException("Unsupported media type: " + type); + } + + String selection = "_id!=" + song.id; + QueryTask query = MediaUtils.buildQuery(type, id, Song.FILLED_PROJECTION, selection); + query.mode = SongTimeline.MODE_FLUSH_AND_PLAY_NEXT; + addSongs(query); + } + + /** + * Clear the song queue. + */ + public void clearQueue() + { + mTimeline.clearQueue(); + } + + /** + * Empty the song queue. + */ + public void emptyQueue() + { + pause(); + setFlag(FLAG_EMPTY_QUEUE); + mTimeline.emptyQueue(); + } + + /** + * Return the error message set when FLAG_ERROR is set. + */ + public String getErrorMessage() + { + return mErrorMessage; + } + + @Override + public void timelineChanged() + { + mHandler.removeMessages(MSG_SAVE_STATE); + mHandler.sendEmptyMessageDelayed(MSG_SAVE_STATE, SAVE_STATE_DELAY); + + // Trigger a gappless update for the new timeline + // This might get canceled if setCurrentSong() also fired a call + // to processSong(); + mHandler.removeMessages(MSG_GAPLESS_UPDATE); + mHandler.sendEmptyMessageDelayed(MSG_GAPLESS_UPDATE, 100); + + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).onTimelineChanged(); + + } + + @Override + public void positionInfoChanged() + { + ArrayList<TimelineCallback> list = sCallbacks; + for (int i = list.size(); --i != -1; ) + list.get(i).onPositionInfoChanged(); + mRemoteControlClient.updateRemote(mCurrentSong, mState, mForceNotificationVisible); + mMediaSessionTracker.updateSession(mCurrentSong, mState); + } + + private final LibraryObserver mObserver = new LibraryObserver() { + @Override + public void onChange(LibraryObserver.Type type, long id, boolean ongoing) + { + if (type != LibraryObserver.Type.SONG && type != LibraryObserver.Type.PLAYLIST) + return; + + MediaUtils.onMediaChange(); + onMediaChange(); + } + }; + + /** + * Return the PlaybackService instance, creating one if needed. + */ + public static PlaybackService get(Context context) + { + if (sInstance == null) { + context.startService(new Intent(context, PlaybackService.class)); + + while (sInstance == null) { + try { + synchronized (sWait) { + sWait.wait(); + } + } catch (InterruptedException ignored) { + } + } + } + + return sInstance; + } + + /** + * Returns true if a PlaybackService instance is active. + */ + public static boolean hasInstance() + { + return sInstance != null; + } + + /** + * Add an Activity to the registered PlaybackActivities. + */ + public static void addTimelineCallback(TimelineCallback consumer) + { + sCallbacks.add(consumer); + } + + /** + * Remove an Activity from the registered PlaybackActivities + */ + public static void removeTimelineCallback(TimelineCallback consumer) + { + sCallbacks.remove(consumer); + } + + /** + * Initializes the service state, loading songs saved from the disk into the + * song timeline. + * + * @return The loaded value for mState. + */ + public int loadState() + { + int state = 0; + + try { + DataInputStream in = new DataInputStream(openFileInput(STATE_FILE)); + + if (in.readLong() == STATE_FILE_MAGIC && in.readInt() == STATE_VERSION) { + mPendingSeek = in.readInt(); + mPendingSeekSong = in.readLong(); + mTimeline.readState(in); + state |= mTimeline.getShuffleMode() << SHIFT_SHUFFLE; + state |= mTimeline.getFinishAction() << SHIFT_FINISH; + } + + in.close(); + } catch (EOFException e) { + Log.w("VanillaMusic", "Failed to load state", e); + } catch (IOException e) { + Log.w("VanillaMusic", "Failed to load state", e); + } + + return state; + } + + /** + * Save the service state to disk. + * + * @param pendingSeek The pendingSeek to store. Should be the current + * MediaPlayer position or 0. + */ + public void saveState(int pendingSeek) + { + try { + DataOutputStream out = new DataOutputStream(openFileOutput(STATE_FILE, 0)); + Song song = mCurrentSong; + out.writeLong(STATE_FILE_MAGIC); + out.writeInt(STATE_VERSION); + out.writeInt(pendingSeek); + out.writeLong(song == null ? -1 : song.id); + mTimeline.writeState(out); + out.close(); + } catch (IOException e) { + Log.w("VanillaMusic", "Failed to save state", e); + } + } + + /** + * Returns the shuffle mode for the given state. + * + * @param state The PlaybackService state to process. + * @return The shuffle mode. One of SongTimeline.SHUFFLE_*. + */ + public static int shuffleMode(int state) + { + return (state & MASK_SHUFFLE) >> SHIFT_SHUFFLE; + } + + /** + * Returns the finish action for the given state. + * + * @param state The PlaybackService state to process. + * @return The finish action. One of SongTimeline.FINISH_*. + */ + public static int finishAction(int state) + { + return (state & MASK_FINISH) >> SHIFT_FINISH; + } + + /** + * Create a PendingIntent for use with the notification. + * + * @param prefs Where to load the action preference from. + */ + public PendingIntent createNotificationAction(SharedPreferences prefs) + { + switch (Integer.parseInt(prefs.getString(PrefKeys.NOTIFICATION_ACTION, PrefDefaults.NOTIFICATION_ACTION))) { + case NOT_ACTION_NEXT_SONG: { + Intent intent = new Intent(this, PlaybackService.class); + intent.setAction(PlaybackService.ACTION_NEXT_SONG_AUTOPLAY); + return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); + } + case NOT_ACTION_MINI_ACTIVITY: { + Intent intent = new Intent(this, MiniPlaybackActivity.class); + return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); + } + default: + Log.w("VanillaMusic", "Unknown value for notification_action. Defaulting to 0."); + // fall through + case NOT_ACTION_MAIN_ACTIVITY: { + Intent intent = new Intent(this, LibraryActivity.class); + intent.setAction(Intent.ACTION_MAIN); + return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); + } + case NOT_ACTION_FULL_ACTIVITY: { + Intent intent = new Intent(this, FullPlaybackActivity.class); + intent.setAction(Intent.ACTION_MAIN); + return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); + } + } + } + + /** + * Create a song notification. Call through the NotificationHelper to + * display it. + * + * @param song The Song to display information about. + * @param state The state. Determines whether to show paused or playing icon. + */ + public Notification createNotification(Song song, int state) + { + final boolean playing = (state & FLAG_PLAYING) != 0; + + ComponentName service = new ComponentName(this, PlaybackService.class); + + int playButton = ThemeHelper.getPlayButtonResource(playing); + Intent playPause = new Intent(PlaybackService.ACTION_TOGGLE_PLAYBACK) + .putExtra(PlaybackService.EXTRA_FORCE_NOTIFICATION, true) + .setComponent(service); + + Intent next = new Intent(PlaybackService.ACTION_NEXT_SONG) + .setComponent(service); + + Intent previous = new Intent(PlaybackService.ACTION_PREVIOUS_SONG) + .setComponent(service); + + NotificationCompat.Builder n = mNotificationHelper.getNewBuilder(getApplicationContext()) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setSmallIcon(R.drawable.status_icon) + .setContentTitle(song.title) + .setContentText(song.album) + .setSubText(song.artist) + .setContentIntent(mNotificationAction) + .addAction(new NotificationCompat.Action(R.drawable.previous, + getString(R.string.previous_song), PendingIntent.getService(this, 0, previous, PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT))) + .addAction(new NotificationCompat.Action(playButton, + getString(R.string.play_pause), PendingIntent.getService(this, 0, playPause, PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT))) + .addAction(new NotificationCompat.Action(R.drawable.next, + getString(R.string.next_song), PendingIntent.getService(this, 0, next, PendingIntent.FLAG_IMMUTABLE|PendingIntent.FLAG_UPDATE_CURRENT))) + .setStyle(new androidx.media.app.NotificationCompat.MediaStyle() + .setMediaSession(mMediaSessionTracker.getSessionToken()) + .setShowActionsInCompactView(0, 1, 2)) + .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE); + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + // Only set the cover for android < 13 since newer versions display the cover from the media session anyway. + Bitmap cover = song.getMediumCover(this); + if (cover == null) { + cover = BitmapFactory.decodeResource(getResources(), R.drawable.fallback_cover_large); + } + n.setLargeIcon(cover); + } + + return n.build(); + } + + public void onAudioFocusChange(int type) + { + Log.d("VanillaMusic", "audio focus change: " + type); + + // Rewrite permanent focus loss into can_duck + if (mIgnoreAudioFocusLoss) { + switch (type) { + case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: + case AudioManager.AUDIOFOCUS_LOSS: + type = AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK; + } + } + + switch (type) { + case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: + case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: + synchronized (mStateLock) { + if((mState & FLAG_PLAYING) != 0) { + mTransientAudioLoss = true; + + if(type == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { + setFlag(FLAG_DUCKING); + } else { + mForceNotificationVisible = true; + unsetFlag(FLAG_PLAYING); + } + } + break; + } + case AudioManager.AUDIOFOCUS_LOSS: + mTransientAudioLoss = false; + mForceNotificationVisible = true; + unsetFlag(FLAG_PLAYING); + break; + case AudioManager.AUDIOFOCUS_GAIN: + if (mTransientAudioLoss) { + mTransientAudioLoss = false; + // Restore all flags possibly changed by AUDIOFOCUS_LOSS_TRANSIENT_* + unsetFlag(FLAG_DUCKING); + setFlag(FLAG_PLAYING); + } + break; + } + } + + @Override + public void onSensorChanged(SensorEvent se) + { + double x = se.values[0]; + double y = se.values[1]; + double z = se.values[2]; + + double accel = Math.sqrt(x*x + y*y + z*z); + double delta = accel - mAccelLast; + mAccelLast = accel; + + double filtered = mAccelFiltered * 0.9f + delta; + mAccelFiltered = filtered; + + if (filtered > mShakeThreshold) { + long now = SystemClock.elapsedRealtime(); + if (now - mLastShakeTime > MIN_SHAKE_PERIOD) { + mLastShakeTime = now; + performAction(mShakeAction, null); + } + } + } + + @Override + public void onAccuracyChanged(Sensor sensor, int accuracy) + { + } + + /** + * Execute the given action. + * + * @param action The action to execute. + * @param receiver Optional. If non-null, update the PlaybackActivity with + * new song or state from the executed action. The activity will still be + * updated by the broadcast if not passed here; passing it just makes the + * update immediate. + */ + public void performAction(Action action, PlaybackActivity receiver) + { + switch (action) { + case Nothing: + break; + case Library: + Intent intent = new Intent(this, LibraryActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + break; + case PlayPause: { + int state = playPause(false); + if (receiver != null) + receiver.setState(state); + break; + } + case NextSong: { + Song song = shiftCurrentSong(SongTimeline.SHIFT_NEXT_SONG); + if (receiver != null) + receiver.setSong(song); + break; + } + case PreviousSong: { + Song song = shiftCurrentSong(SongTimeline.SHIFT_PREVIOUS_SONG); + if (receiver != null) + receiver.setSong(song); + break; + } + case NextAlbum: { + Song song = shiftCurrentSong(SongTimeline.SHIFT_NEXT_ALBUM); + if (receiver != null) + receiver.setSong(song); + break; + } + case PreviousAlbum: { + Song song = shiftCurrentSong(SongTimeline.SHIFT_PREVIOUS_ALBUM); + if (receiver != null) + receiver.setSong(song); + break; + } + case Repeat: { + int state = cycleFinishAction(); + if (receiver != null) + receiver.setState(state); + break; + } + case Shuffle: { + int state = cycleShuffle(); + if (receiver != null) + receiver.setState(state); + break; + } + case EnqueueAlbum: + enqueueFromSong(mCurrentSong, MediaUtils.TYPE_ALBUM); + break; + case EnqueueArtist: + enqueueFromSong(mCurrentSong, MediaUtils.TYPE_ARTIST); + break; + case EnqueueGenre: + enqueueFromSong(mCurrentSong, MediaUtils.TYPE_GENRE); + break; + case ClearQueue: + clearQueue(); + showToast(R.string.queue_cleared, Toast.LENGTH_SHORT); + break; + case ToggleControls: + case ShowQueue: + // These are NOOPs here and should be handled in FullPlaybackActivity + break; + case SeekForward: + if (mCurrentSong != null) { + mPendingSeekSong = mCurrentSong.id; + mPendingSeek = getPosition() + 10000; + // We 'abuse' setCurrentSong as it will stop the playback and restart it + // at the new position, taking care of the ui update + setCurrentSong(0); + } + break; + case SeekBackward: + if (mCurrentSong != null) { + mPendingSeekSong = mCurrentSong.id; + mPendingSeek = getPosition() - 10000; + if (mPendingSeek < 1) mPendingSeek = 1; // must at least be 1 + setCurrentSong(0); + } + break; + default: + throw new IllegalArgumentException("Invalid action: " + action); + } + } + + /** + * Returns the playing status of the current song + */ + public boolean isPlaying() { + return (mState & FLAG_PLAYING) != 0; + } + + /** + * Returns the position of the current song in the song timeline. + */ + public int getTimelinePosition() + { + return mTimeline.getPosition(); + } + + /** + * Returns the number of songs in the song timeline. + */ + public int getTimelineLength() + { + return mTimeline.getLength(); + } + + /** + * Returns {@link Song} with given position from timeline or null if nothing found + */ + public Song getSongByQueuePosition(int pos) { + return mTimeline.getSongByQueuePosition(pos); + } + + /** + * Retrieve song position in timeline + * @param id song id as defined in {@link Song#id} + * @return absolute position in song timeline or -1 if song currently not in timeline + */ + public int getQueuePositionForSongId(long id) { + return mTimeline.getQueuePositionForSongId(id); + } + + /** + * Do a 'hard' jump to given queue position + */ + public void jumpToQueuePosition(int pos) { + mTimeline.setCurrentQueuePosition(pos); + play(); + } + + /** + * Moves a songs position in the queue + * + * @param from the index of the song to be moved + * @param to the new index position of the song + */ + public void moveSongPosition(int from, int to) { + mTimeline.moveSongPosition(from, to); + } + + /** + * Removes a song from the queue + * @param which index to remove + */ + public void removeSongPosition(int which) { + mTimeline.removeSongPosition(which); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/Playlist.java b/app/src/main/java/ch/blinkenlights/android/vanilla/Playlist.java new file mode 100644 index 0000000..ade3bae --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/Playlist.java @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2010 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2014-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.content.ContentValues; +import android.database.Cursor; +import android.text.TextUtils; +import java.util.ArrayList; + +import androidx.annotation.Nullable; + +/** + * Provides various playlist-related utility functions. + */ +public class Playlist { + /** + * Queries all the playlists known to the MediaLibrary. + * + * @param context the context to use + * @return The queried cursor. + */ + public static Cursor queryPlaylists(Context context) { + final String[] projection = { MediaLibrary.PlaylistColumns._ID, MediaLibrary.PlaylistColumns.NAME }; + final String sort = MediaLibrary.PlaylistColumns.NAME; + return MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS, projection, null, null, sort); + } + + /** + * Retrieves the id for a playlist with the given name. + * + * @param context the context to use + * @param name The name of the playlist. + * @return The id of the playlist, or -1 if there is no playlist with the + * given name. + */ + public static long getPlaylist(Context context, String name) + { + long id = -1; + final String[] projection = { MediaLibrary.PlaylistColumns._ID }; + final String selection = MediaLibrary.PlaylistColumns.NAME+"=?"; + final String[] selectionArgs = { name }; + Cursor cursor = MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS, projection, selection, selectionArgs, null); + + if (cursor != null) { + if (cursor.moveToNext()) + id = cursor.getLong(0); + cursor.close(); + } + + return id; + } + + /** + * Returns the name of given playlist id. + * + * @param context the context to use + * @param id the playlist id to look up + * @return name of the playlist, may be null + */ + public static @Nullable String getPlaylist(Context context, long id) + { + String name = null; + final String[] projection = { MediaLibrary.PlaylistColumns.NAME }; + final String selection = MediaLibrary.PlaylistColumns._ID+"=?"; + final String[] selectionArgs = { Long.valueOf(id).toString() }; + Cursor cursor = MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS, projection, selection, selectionArgs, null); + + if (cursor != null) { + if (cursor.moveToNext()) + name = cursor.getString(0); + cursor.close(); + } + + return name; + } + + /** + * Create a new playlist with the given name. If a playlist with the given + * name already exists, it will be overwritten. + * + * @param context the context to use + * @param name The name of the playlist. + * @return The id of the new playlist. + */ + public static long createPlaylist(Context context, String name) + { + long id = getPlaylist(context, name); + if (id != -1) + deletePlaylist(context, id); + + id = MediaLibrary.createPlaylist(context, name); + return id; + } + + /** + * Run the given query and add the results to the given playlist. Should be + * run on a background thread. + * + * @param context the context to use + * @param playlistId The playlist id of the playlist to + * modify. + * @param query The query to run. The audio id should be the first column. + * @return The number of songs that were added to the playlist. + */ + public static int addToPlaylist(Context context, long playlistId, QueryTask query) { + ArrayList<Long> result = new ArrayList<Long>(); + Cursor cursor = query.runQuery(context); + if (cursor != null) { + while (cursor.moveToNext()) { + result.add(cursor.getLong(0)); + } + } + return addToPlaylist(context, playlistId, result); + } + + /** + * Adds a set of audioIds to the given playlist. Should be + * run on a background thread. + * + * @param context the context to use + * @param playlistId The playlist id of the playlist to + * modify. + * @param audioIds An ArrayList with all IDs to add + * @return The number of songs that were added to the playlist. + */ + public static int addToPlaylist(Context context, long playlistId, ArrayList<Long> audioIds) { + if (playlistId == -1) + return 0; + return MediaLibrary.addToPlaylist(context, playlistId, audioIds); + } + + /** + * Removes a set of audioIds from the given playlist. Should be + * run on a background thread. + * + * @param context the context to use + * @param playlistId id of the playlist to + * modify. + * @param audioIds An ArrayList with all IDs to drop + * @return The number of songs that were removed from the playlist + */ + public static int removeFromPlaylist(Context context, long playlistId, ArrayList<Long> audioIds) { + if (playlistId == -1) + return 0; + + String idList = TextUtils.join(", ", audioIds); + String selection = MediaLibrary.PlaylistSongColumns.SONG_ID+" IN ("+idList+") AND "+MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"="+playlistId; + return MediaLibrary.removeFromPlaylist(context, selection, null); + } + + /** + * Delete the playlist with the given id. + * + * @param context the context to use + * @param id the id of the playlist. + */ + public static void deletePlaylist(Context context, long id) { + MediaLibrary.removePlaylist(context, id); + } + + + /** + * Rename the playlist with the given id. + * + * @param context the context to use + * @param id The Media.Audio.Playlists id of the playlist. + * @param newName The new name for the playlist. + */ + public static void renamePlaylist(Context context, long id, String newName) { + MediaLibrary.renamePlaylist(context, id, newName); + } + + /** + * Returns the ID of the 'favorites' playlist. + * + * @param context The Context to use + * @param create Create the playlist if it does not exist + * @return the id of the playlist, -1 on error + */ + public static long getFavoritesId(Context context, boolean create) { + String playlistName = context.getString(R.string.playlist_favorites); + long playlistId = getPlaylist(context, playlistName); + + if (playlistId == -1 && create == true) + playlistId = createPlaylist(context, playlistName); + + return playlistId; + } + + /** + * Searches for given song in given playlist + * + * @param context the context to use + * @param playlistId The ID of the Playlist to query + * @param song The Song to search in given playlistId + * @return true if `song' was found in `playlistId' + */ + public static boolean isInPlaylist(Context context, long playlistId, Song song) { + if (playlistId == -1 || song == null) + return false; + + boolean found = false; + String selection = MediaLibrary.PlaylistSongColumns.PLAYLIST_ID+"=? AND "+MediaLibrary.PlaylistSongColumns.SONG_ID+"=?"; + String[] selectionArgs = { Long.toString(playlistId), Long.toString(song.id) }; + + Cursor cursor = MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_PLAYLISTS_SONGS, Song.EMPTY_PLAYLIST_PROJECTION, selection, selectionArgs, null); + if (cursor != null) { + found = cursor.getCount() != 0; + cursor.close(); + } + return found; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistActivity.java new file mode 100644 index 0000000..7aed110 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistActivity.java @@ -0,0 +1,337 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.vanilla.ui.FancyMenu; +import ch.blinkenlights.android.vanilla.ui.FancyMenuItem; +import ch.blinkenlights.android.vanilla.ext.CoordClickListener; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.os.HandlerThread; +import android.os.Looper; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AbsListView; +import android.widget.AdapterView; +import android.widget.Button; +import com.mobeta.android.dslv.DragSortListView; + + +/** + * The playlist activity where playlist songs can be viewed and reordered. + */ +public class PlaylistActivity extends Activity + implements View.OnClickListener + , AbsListView.OnItemClickListener + , CoordClickListener.Callback + , DialogInterface.OnClickListener + , DragSortListView.DropListener + , DragSortListView.RemoveListener + , FancyMenu.Callback +{ + /** + * The SongTimeline play mode corresponding to each + * LibraryActivity.ACTION_* + */ + private static final int[] MODE_FOR_ACTION = + { SongTimeline.MODE_PLAY, SongTimeline.MODE_ENQUEUE, -1, + SongTimeline.MODE_PLAY_POS_FIRST, SongTimeline.MODE_ENQUEUE_POS_FIRST, + -1, -1, -1, SongTimeline.MODE_ENQUEUE_AS_NEXT }; + + /** + * An event loop running on a worker thread. + */ + private Looper mLooper; + private DragSortListView mListView; + private PlaylistAdapter mAdapter; + + /** + * The id of the playlist this activity is currently viewing. + */ + private long mPlaylistId; + /** + * The name of the playlist this activity is currently viewing. + */ + private String mPlaylistName; + /** + * If true, then playlists songs can be dragged to reorder. + */ + private boolean mEditing; + + /** + * The item click action specified in the preferences. + */ + private int mDefaultAction; + /** + * The last action used from the context menu, used to implement + * LAST_USED_ACTION action. + */ + private int mLastAction = LibraryActivity.ACTION_PLAY; + + private Button mEditButton; + private Button mDeleteButton; + + @Override + public void onCreate(Bundle state) + { + ThemeHelper.setTheme(this, R.style.BackActionBar); + super.onCreate(state); + + HandlerThread thread = new HandlerThread(getClass().getName()); + thread.start(); + + setContentView(R.layout.playlist_activity); + + CoordClickListener ccl = new CoordClickListener(this); + DragSortListView view = (DragSortListView)findViewById(R.id.list); + ccl.registerForOnItemLongClickListener(view); + view.setOnItemClickListener(this); + view.setDropListener(this); + view.setRemoveListener(this); + mListView = view; + + View header = LayoutInflater.from(this).inflate(R.layout.playlist_buttons, null); + mEditButton = (Button)header.findViewById(R.id.edit); + mEditButton.setOnClickListener(this); + mDeleteButton = (Button)header.findViewById(R.id.delete); + mDeleteButton.setOnClickListener(this); + view.addHeaderView(header, null, false); + mLooper = thread.getLooper(); + mAdapter = new PlaylistAdapter(this, mLooper); + view.setAdapter(mAdapter); + + onNewIntent(getIntent()); + } + + @Override + public void onStart() + { + super.onStart(); + SharedPreferences settings = SharedPrefHelper.getSettings(this); + mDefaultAction = Integer.parseInt(settings.getString(PrefKeys.DEFAULT_PLAYLIST_ACTION, PrefDefaults.DEFAULT_PLAYLIST_ACTION)); + } + + @Override + public void onDestroy() + { + mLooper.quit(); + super.onDestroy(); + } + + @Override + public void onNewIntent(Intent intent) + { + long id = intent.getLongExtra("playlist", 0); + String title = intent.getStringExtra("title"); + mAdapter.setPlaylistId(id); + setTitle(title); + mPlaylistId = id; + mPlaylistName = title; + } + + /** + * Enable or disable edit mode, which allows songs to be reordered and + * removed. + * + * @param editing True to enable edit mode. + */ + public void setEditing(boolean editing) + { + mListView.setDragEnabled(editing); + mAdapter.setEditable(editing); + int visible = editing ? View.GONE : View.VISIBLE; + mDeleteButton.setVisibility(visible); + mEditButton.setText(editing ? R.string.done : R.string.edit); + mEditing = editing; + } + + @Override + public void onClick(View view) + { + switch (view.getId()) { + case R.id.edit: + setEditing(!mEditing); + break; + case R.id.delete: { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + String message = getResources().getString(R.string.delete_playlist, mPlaylistName); + builder.setMessage(message); + builder.setPositiveButton(R.string.delete, this); + builder.setNegativeButton(android.R.string.cancel, this); + builder.show(); + break; + } + } + } + + private static final int MENU_PLAY = LibraryActivity.ACTION_PLAY; + private static final int MENU_PLAY_ALL = LibraryActivity.ACTION_PLAY_ALL; + private static final int MENU_ENQUEUE = LibraryActivity.ACTION_ENQUEUE; + private static final int MENU_ENQUEUE_ALL = LibraryActivity.ACTION_ENQUEUE_ALL; + private static final int MENU_ENQUEUE_AS_NEXT = LibraryActivity.ACTION_ENQUEUE_AS_NEXT; + private static final int MENU_REMOVE = -1; + private static final int MENU_SHOW_DETAILS = -2; + + @Override + public boolean onItemLongClickWithCoords(AdapterView<?> parent, View view, int pos, long id, float x, float y) { + ViewHolder holder = (ViewHolder)view.findViewById(R.id.text).getTag(); + Intent intent = new Intent(); + intent.putExtra("id", id); + intent.putExtra("position", pos); + intent.putExtra("audioId", holder.id); + + FancyMenu fm = new FancyMenu(this, this); + fm.setHeaderTitle(holder.title); + + fm.add(MENU_PLAY, 0, R.drawable.menu_play, R.string.play).setIntent(intent); + fm.add(MENU_PLAY_ALL, 0, R.drawable.menu_play_all, R.string.play_all).setIntent(intent); + + fm.addSpacer(0); + fm.add(MENU_ENQUEUE_AS_NEXT, 0, R.drawable.menu_enqueue_as_next, R.string.enqueue_as_next).setIntent(intent); + fm.add(MENU_ENQUEUE, 0, R.drawable.menu_enqueue, R.string.enqueue).setIntent(intent); + fm.add(MENU_ENQUEUE_ALL, 0, R.drawable.menu_enqueue, R.string.enqueue_all).setIntent(intent); + + fm.addSpacer(0); + fm.add(MENU_SHOW_DETAILS, 0, R.drawable.menu_details, R.string.details).setIntent(intent); + fm.add(MENU_REMOVE, 0, R.drawable.menu_remove, R.string.remove).setIntent(intent); + fm.show(view, x, y); + return true; + } + + @Override + public boolean onFancyItemSelected(FancyMenuItem item) + { + int itemId = item.getItemId(); + Intent intent = item.getIntent(); + int pos = intent.getIntExtra("position", -1); + + if (itemId == MENU_REMOVE) { + mAdapter.removeItem(pos - mListView.getHeaderViewsCount()); + } else if (itemId == MENU_SHOW_DETAILS) { + long songId = intent.getLongExtra("audioId", -1); + TrackDetailsDialog.show(getFragmentManager(), songId); + } else { + performAction(itemId, pos, intent.getLongExtra("audioId", -1)); + } + + return true; + } + + /** + * Perform the specified action on the adapter row with the given id and + * position. + * + * @param action One of LibraryActivity.ACTION_*. + * @param position The position in the adapter. + * @param audioId The id of the selected song, for PLAY/ENQUEUE. + */ + private void performAction(int action, int position, long audioId) + { + if (action == LibraryActivity.ACTION_PLAY_OR_ENQUEUE) + action = (PlaybackService.get(this).isPlaying() ? LibraryActivity.ACTION_ENQUEUE : LibraryActivity.ACTION_PLAY); + + if (action == LibraryActivity.ACTION_LAST_USED) + action = mLastAction; + + switch (action) { + case LibraryActivity.ACTION_PLAY: + case LibraryActivity.ACTION_ENQUEUE: + case LibraryActivity.ACTION_ENQUEUE_AS_NEXT: { + QueryTask query = MediaUtils.buildQuery(MediaUtils.TYPE_SONG, audioId, Song.FILLED_PROJECTION, null); + query.mode = MODE_FOR_ACTION[action]; + PlaybackService.get(this).addSongs(query); + break; + } + case LibraryActivity.ACTION_PLAY_ALL: + case LibraryActivity.ACTION_ENQUEUE_ALL: { + QueryTask query = MediaUtils.buildPlaylistQuery(mPlaylistId, Song.FILLED_PLAYLIST_PROJECTION); + query.mode = MODE_FOR_ACTION[action]; + query.data = position - mListView.getHeaderViewsCount(); + PlaybackService.get(this).addSongs(query); + break; + } + } + + mLastAction = action; + } + + @Override + public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) + { + if (!mEditing && mDefaultAction != LibraryActivity.ACTION_DO_NOTHING) { + // A DSLV row was clicked, but we need to get the DraggableRow class. + final View target = ((ViewGroup)view).getChildAt(0); + final ViewHolder holder = (ViewHolder)target.getTag(); + performAction(mDefaultAction, position, holder.id); + } + } + + @Override + public void onClick(DialogInterface dialog, int which) + { + if (which == DialogInterface.BUTTON_POSITIVE) { + Playlist.deletePlaylist(this, mPlaylistId); + finish(); + } + dialog.dismiss(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) + { + if (item.getItemId() == android.R.id.home) { + finish(); + return true; + } else { + return super.onOptionsItemSelected(item); + } + } + + /** + * Fired from adapter listview if user moved an item + * @param from the item index that was dragged + * @param to the index where the item was dropped + */ + @Override + public void drop(int from, int to) { + mAdapter.moveItem(from, to); + } + + /** + * Fired from adapter listview if user fling-removed an item + * @param position The position of the removed item + */ + @Override + public void remove(int position) { + mAdapter.removeItem(position); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistAdapter.java new file mode 100644 index 0000000..855e9e6 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistAdapter.java @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2011 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2015-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.database.Cursor; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.TextView; + +/** + * CursorAdapter backed by MediaLibrary playlists. + */ +public class PlaylistAdapter extends CursorAdapter implements Handler.Callback { + + private static final String[] PROJECTION = new String[] { + MediaLibrary.PlaylistSongColumns._ID, + MediaLibrary.PlaylistSongColumns.SONG_ID, + MediaLibrary.SongColumns.TITLE, + MediaLibrary.AlbumColumns.ALBUM, + MediaLibrary.ContributorColumns.ARTIST, + MediaLibrary.SongColumns.ALBUM_ID, + MediaLibrary.SongColumns.DURATION, + }; + + private final Context mContext; + private final Handler mWorkerHandler; + private final Handler mUiHandler; + private final LayoutInflater mInflater; + + private long mPlaylistId; + + private boolean mEditable; + + /** + * Create a playlist adapter. + * + * @param context A context to use. + * @param worker A looper running a worker thread (to run queries on). + */ + public PlaylistAdapter(Context context, Looper worker) + { + super(context, null, false); + + mContext = context; + mUiHandler = new Handler(this); + mWorkerHandler = new Handler(worker, this); + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + + /** + * Set the id of the backing playlist. + * + * @param id The id of a playlist. + */ + public void setPlaylistId(long id) + { + mPlaylistId = id; + mWorkerHandler.sendEmptyMessage(MSG_RUN_QUERY); + } + + /** + * Enabled or disable edit mode. Edit mode adds a drag grabber to the left + * side a views and a delete button to the right side of views. + * + * @param editable True to enable edit mode. + */ + public void setEditable(boolean editable) + { + mEditable = editable; + notifyDataSetInvalidated(); + } + + /** + * Update the values in the given view. + */ + @Override + public void bindView(View view, Context context, Cursor cursor) + { + DraggableRow dview = (DraggableRow)view; + final String title = cursor.getString(2); + final String album = cursor.getString(3); + final String artist = cursor.getString(4); + + ViewHolder holder = new ViewHolder(); + holder.title = title; + holder.id = cursor.getLong(1); + + dview.setupLayout(DraggableRow.LAYOUT_DRAGGABLE); + dview.showDragger(mEditable); + dview.setText(title, album+", "+artist); + dview.setTag(holder); + dview.setDuration(cursor.getLong(6)); + + LazyCoverView cover = dview.getCoverView(); + cover.setCover(MediaUtils.TYPE_ALBUM, cursor.getLong(5), null); + } + + /** + * Generate a new view. + */ + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) + { + return mInflater.inflate(R.layout.draggable_row, parent, false); + } + + /** + * Re-run the query. Should be run on worker thread. + */ + public static final int MSG_RUN_QUERY = 1; + /** + * Update the cursor. Must be run on UI thread. + */ + public static final int MSG_UPDATE_CURSOR = 2; + + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_RUN_QUERY: { + Cursor cursor = runQuery(); + mUiHandler.sendMessage(mUiHandler.obtainMessage(MSG_UPDATE_CURSOR, cursor)); + break; + } + case MSG_UPDATE_CURSOR: + changeCursor((Cursor)message.obj); + break; + default: + return false; + } + + return true; + } + + /** + * Query the playlist songs. + * + * @return The resulting cursor. + */ + private Cursor runQuery() + { + QueryTask query = MediaUtils.buildPlaylistQuery(mPlaylistId, PROJECTION); + return query.runQuery(mContext); + } + + /** + * Moves a song in the playlist + * @param from original position of item + * @param to destination of item + **/ + public void moveItem(int from, int to) + { + if (from == to) + // easy mode + return; + + int count = getCount(); + if (to >= count || from >= count) + // this can happen when the adapter changes during the drag + return; + + MediaLibrary.movePlaylistItem(mContext, getItemId(from), getItemId(to)); + changeCursor(runQuery()); + } + + public void removeItem(int position) { + MediaLibrary.removeFromPlaylist(mContext, MediaLibrary.PlaylistSongColumns._ID+"="+getItemId(position), null); + mUiHandler.sendEmptyMessage(MSG_RUN_QUERY); + } + + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistDialog.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistDialog.java new file mode 100644 index 0000000..89ad4e9 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistDialog.java @@ -0,0 +1,173 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.database.Cursor; +import android.os.Bundle; + +public class PlaylistDialog extends DialogFragment + implements DialogInterface.OnClickListener +{ + + // Unicode of checkbox + String CHECKBOX_UNCHECKED = "\u2610"; + String CHECKBOX_CHECKED = "\u2611"; + + Song mCurrentSong; + + /** + * Default constructor as required by Gradle Release Lint + */ + public PlaylistDialog() { + } + + /** + * Creates a new playlist dialog to assemble a playlist using an intent. + * Uses a static constructor method to satisfy Gradle Release Lint. + */ + public static PlaylistDialog newInstance(Callback callback, Intent intent, LibraryAdapter allSource, Song currentSong) { + PlaylistDialog pd = new PlaylistDialog(); + pd.mCallback = callback; + pd.mData = pd.new Data(); + pd.mData.sourceIntent = intent; + pd.mData.allSource = allSource; + pd.mCurrentSong = currentSong; + return pd; + } + + /** + * For backward compatible + */ + public static PlaylistDialog newInstance(Callback callback, Intent intent, LibraryAdapter allSource) { + return newInstance( callback, intent, allSource, null); + } + + /** + * A class implementing our callback interface + */ + private Callback mCallback; + /** + * The data passed to the callback + */ + private PlaylistDialog.Data mData; + /** + * Array of all found playlist names + */ + private String[] mItemName; + /** + * Array of all found playlist values + */ + private long[] mItemValue; + /** + * Index of 'create playlist' button + */ + private final int BUTTON_CREATE_PLAYLIST = 0; + /** + * Our callback interface + */ + public interface Callback { + void updatePlaylistFromPlaylistDialog(PlaylistDialog.Data data); + } + /** + * Our data structure + */ + public class Data { + public String name; + public long id; + public Intent sourceIntent; + public LibraryAdapter allSource; + } + + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + Context ctx = getActivity(); + Cursor cursor = Playlist.queryPlaylists(ctx); + if (cursor == null) + return null; + + int count = cursor.getCount(); + mItemName = new String[1+count]; + mItemValue = new long[1+count]; + String[] displayItem = new String[count+1]; + + // Index 0 is always 'New Playlist...' + mItemName[0] = getResources().getString(R.string.new_playlist); + mItemValue[0] = -1; + displayItem[0] = mItemName[0]; + + for (int i = 0 ; i < count; i++) { + cursor.moveToPosition(i); + mItemValue[1+i] = cursor.getLong(0); + mItemName[1+i] = cursor.getString(1); + if(mCurrentSong==null){ + displayItem[1+i] = mItemName[1+i]; + } + else { + if (Playlist.isInPlaylist(ctx, mItemValue[1+i], mCurrentSong)) { + displayItem[1 + i] = CHECKBOX_CHECKED + " " + mItemName[1 + i]; + } + else { + displayItem[1 + i] = CHECKBOX_UNCHECKED + " " + mItemName[1 + i]; + } + } + } + + + + + // All names are now known: we can show the dialog + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setTitle(R.string.add_to_playlist) + .setItems(displayItem, this); + return builder.create(); + } + + @Override + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case BUTTON_CREATE_PLAYLIST: + PlaylistInputDialog newDialog = PlaylistInputDialog.newInstance(new PlaylistInputDialog.Callback() { + @Override + public void onSuccess(String input) { + mData.id = -1; + mData.name = input; + mCallback.updatePlaylistFromPlaylistDialog(mData); + } + }, "", R.string.create); + newDialog.show(getFragmentManager(), "PlaylistInputDialog"); + break; + default: + mData.id = mItemValue[which]; + mData.name = mItemName[which]; + mCallback.updatePlaylistFromPlaylistDialog(mData); + } + dialog.dismiss(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistInputDialog.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistInputDialog.java new file mode 100644 index 0000000..f6f06cb --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistInputDialog.java @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.AlertDialog; +import android.app.Dialog; +import android.app.DialogFragment; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; +import android.text.Editable; +import android.text.InputType; +import android.text.TextWatcher; +import android.view.WindowManager; +import android.widget.EditText; + +public class PlaylistInputDialog extends DialogFragment + implements DialogInterface.OnClickListener, TextWatcher +{ + /** + * Default constructor as required by Gradle Release Lint + */ + public PlaylistInputDialog() { + } + + /** + * Creates a new instance. + * Uses a static constructor method to satisfy Gradle Release Lint. + * @param callback the callback to call back + * @param initialText the initial value mEditText + * @param actionRes the label of the positive button + */ + public static PlaylistInputDialog newInstance(Callback callback, String initialText, int actionRes) { + PlaylistInputDialog pid = new PlaylistInputDialog(); + pid.mCallback = callback; + pid.mInitialText = initialText; + pid.mActionRes = actionRes; + return pid; + } + + public interface Callback { + void onSuccess(String input); + } + + /** + * A editText instance + */ + private EditText mEditText; + /** + * Our callback implementing the PlaylistInputDialog.Callback + * interface + */ + private Callback mCallback; + /** + * The label of the positive button + */ + private int mActionRes; + /** + * The initial text to display + */ + private String mInitialText; + /** + * The instance of the alert dialog + */ + private AlertDialog mDialog; + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + mEditText = new EditText(getActivity()); + mEditText.setInputType(InputType.TYPE_CLASS_TEXT); + mEditText.addTextChangedListener(this); + + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + builder.setTitle(R.string.choose_playlist_name) + .setView(mEditText) + .setPositiveButton(mActionRes, this) + .setNegativeButton(android.R.string.cancel, this); + mDialog = builder.create(); + mDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + + return mDialog; + } + + /** + * Called when the view becomes visible, so we can + * set the button positive-button and request focus + */ + public void onStart() { + super.onStart(); + mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false); + mEditText.setText(mInitialText); + mEditText.requestFocus(); + } + + /** + * Called after mEditText changed + */ + public void afterTextChanged(Editable s) { + // noop + } + + /** + * Called before mEditText changed + */ + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + // noop + } + + /** + * Called when mEditText changed + */ + public void onTextChanged(CharSequence text, int start, int before, int count) { + String string = text.toString(); + if (string.equals(mInitialText)) { + mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false); + } else { + mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true); + int res = Playlist.getPlaylist(getActivity(), string) == -1 ? mActionRes : R.string.overwrite; + mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setText(res); + } + } + + @Override + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case DialogInterface.BUTTON_NEGATIVE: + // noop + break; + case DialogInterface.BUTTON_POSITIVE: + mCallback.onSuccess(mEditText.getText().toString()); + break; + default: + break; + } + dialog.dismiss(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistObserver.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistObserver.java new file mode 100644 index 0000000..1f2db9e --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistObserver.java @@ -0,0 +1,659 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; +import ch.blinkenlights.android.medialibrary.LibraryObserver; + +import android.content.Context; +import android.content.ContentValues; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.os.Build; +import android.os.FileObserver; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Message; +import android.os.Process; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.PrintWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.zip.CRC32; + +import android.util.Log; + + +public class PlaylistObserver extends SQLiteOpenHelper implements Handler.Callback { + /** + * Whether or not to write debug logs. + */ + private static final boolean DEBUG = false; + /** + * Bits for mSyncMode + */ + public static final int SYNC_MODE_IMPORT = (1 << 0); + public static final int SYNC_MODE_EXPORT = (1 << 1); + public static final int SYNC_MODE_PURGE = (1 << 2); + /** + * Timeout to coalesce duplicate messages, ~2.3 sec because no real reason. + */ + private static final int COALESCE_EVENTS_DELAY_MS = 2345; + /** + * Extension to use for M3U files + */ + private static final String M3U_EXT = ".m3u"; + /** + * Line comment prefix for M3U files + */ + private static final String M3U_LINE_COMMENT_PREFIX = "#"; + /** + * Context to use. + */ + private Context mContext; + /** + * Thread used for execution. + */ + private HandlerThread mHandlerThread; + /** + * Handler thread used to perform playlist sync. + */ + private Handler mHandler; + /** + * Observer which watches the playlist directory. + */ + private FileObserver mFileObserver; + /** + * Directory which holds observed playlists. + */ + private File mPlaylists; + /** + * What kind of synching to perform, bitmask of PlaylistObserver.SYNC_MODE_* + */ + private int mSyncMode; + /** + * Whether to export playlists using relative file paths. + */ + private boolean mExportRelativePaths; + /** + * Database fields + */ + private static class Database { + static final String TABLE_NAME = "playlist_metadata"; + static final String _ID = "_id"; + static final String NAME = "name"; + static final String HASH = "hash"; + static final String[] FILLED_PROJECTION = { + _ID, + NAME, + HASH, + }; + } + + + public PlaylistObserver(Context context, String folder, int mode, boolean exportRelativePaths) { + super(context, "playlist_observer.db", null, 1 /* version */); + mContext = context; + mSyncMode = mode; + mPlaylists = new File(folder); + mExportRelativePaths = exportRelativePaths; + + // Launch new thread for background execution + mHandlerThread= new HandlerThread("PlaylisObserverHandler", Process.THREAD_PRIORITY_LOWEST); + mHandlerThread.start(); + mHandler = new Handler(mHandlerThread.getLooper(), this); + + // Create playlists directory if not existing. + if ((mSyncMode & SYNC_MODE_EXPORT) != 0) { + try { + mPlaylists.mkdir(); + } catch (Exception e) { + // don't care: code will ignore events + // if mPlaylists is not a (writable) dir. + } + } + + // Register to receive media library events. + MediaLibrary.registerLibraryObserver(mLibraryObserver); + // Create and start directory observer. + mFileObserver = getFileObserver(mPlaylists); + mFileObserver.startWatching(); + + XT("Object created, trigger FULL_SYNC_SCAN"); + sendUniqueMessage(MSG_FULL_SYNC_SCAN, 0); + } + + /** + * Unregisters this observer, the object must not be used anymore + * after this function was called. + */ + public void unregister() { + MediaLibrary.unregisterLibraryObserver(mLibraryObserver); + mFileObserver.stopWatching(); + + mHandlerThread.quitSafely(); + mHandlerThread = null; + mHandler = null; + } + + /** + * Whether or not to handle (or drop) any events received. + * This has the same effect as unregistering, without actually + * unregistering. The function prevents false events from + * being handled if our playlists folder becomes 'suspect'. + */ + private boolean shouldDispatch() { + // This is so sad, but java.nio.file is only available since API 26, + // so we are stuck with java being java. + boolean deny = false; + try { + File f = File.createTempFile("vanilla-write-check", null, mPlaylists); + f.delete(); + } catch (Exception e) { + // don't care about the exact error: as long as the write failed, + // we should not assume that we could write anything else. + deny = true; + } + return !deny; + } + + /** + * SQLiteHelper onCreate + */ + @Override + public void onCreate(SQLiteDatabase dbh) { + dbh.execSQL("CREATE TABLE "+Database.TABLE_NAME+" ( " + + Database._ID + " INTEGER PRIMARY KEY, " + + Database.HASH + " INTEGER NOT NULL, " + + Database.NAME + " TEXT NOT NULL )" + ); + } + + /** + * SQLiteHelper onUpgrade + */ + @Override + public void onUpgrade(SQLiteDatabase dbh, int oldVersion, int newVersion) { + // No updates so far. + } + + /** + * Message handler, used to dedupe messages and perform + * background work. + */ + private static final int MSG_DUMP_M3U = 1; + private static final int MSG_DUMP_ALL_M3U = 2; + private static final int MSG_IMPORT_M3U = 3; + private static final int MSG_FORCE_M3U_IMPORT = 4; + private static final int MSG_FULL_SYNC_SCAN = 5; + ArrayList<Integer> msgDedupe = new ArrayList<>(); + @Override + public boolean handleMessage(Message message) { + msgDedupe.remove(0); + + switch (message.what) { + case MSG_DUMP_M3U: + Long id = (Long)message.obj; + if (Playlist.getPlaylist(mContext, id) != null) { + XT("DUMP_M3U: source of id "+id+" exists, dumping"); + dumpAsM3uPlaylist(id); + } else { + XT("DUMP_M3U: source of id "+id+" vanished, scanning all"); + sendUniqueMessage(MSG_FULL_SYNC_SCAN, 0); + } + break; + case MSG_DUMP_ALL_M3U: + dumpAllAsM3uPlaylist(); + break; + case MSG_IMPORT_M3U: + File f = (File)(message.obj); + importM3uPlaylist(f); + break; + case MSG_FORCE_M3U_IMPORT: + forceM3uImport(); + break; + case MSG_FULL_SYNC_SCAN: + fullSyncScan(); + break; + default: + throw new IllegalArgumentException("Invalid message type received"); + } + return true; + } + + /** + * Forcefully re-imports all M3U files, even if we think that + * our information is up-to-date. + */ + private void forceM3uImport() { + Cursor cursor = queryDatabase(null); + if (cursor != null) { + while (cursor.moveToNext()) { + deletePlaylistMetadata(cursor.getLong(0)); + } + cursor.close(); + } + // run this ASAP to ensure that no other message re-populates + // metadata. + XT("forceM3uImport: metadata cleared, calling fullSyncScan"); + fullSyncScan(); + } + + /** + * Dumps all playlist to stable storage. + */ + private void dumpAllAsM3uPlaylist() { + XT("dumpAllAsM3uPlaylist: called"); + Cursor cursor = Playlist.queryPlaylists(mContext); + if (cursor != null) { + while(cursor.moveToNext()) { + final long id = cursor.getLong(0); + XT("dumpAllAsM3uPlaylist: Dumping ID "+id); + sendUniqueMessage(MSG_DUMP_M3U, id); + } + cursor.close(); + } + } + + /** + * Adds a new message to the queue. Ignores call if a duplicate + * message is already pending. + * + * @param type the type of the message + * @param obj object payload of this message. + */ + private void sendUniqueMessage(int type, Object obj) { + int fprint = (type << 10) + obj.hashCode(); + if (!msgDedupe.contains(fprint)) { + msgDedupe.add(fprint); + mHandler.sendMessageDelayed(mHandler.obtainMessage(type, obj), COALESCE_EVENTS_DELAY_MS); + } + } + + + /** + * Imports an M3U formatted file into our native media library. + * + * @param m3u the file to import + */ + private void importM3uPlaylist(File m3u) {; + XT("importM3uPlaylist("+m3u+")"); + + if ((mSyncMode & SYNC_MODE_IMPORT) == 0) + return; + + if (!m3u.exists()) + return; + + final long hash = getHash(m3u); + if (hash == -1) + return; + + boolean must_import = true; + String import_as = fromM3u(m3u.getName()); + Cursor cursor = queryDatabase(null); + if (cursor != null) { + // Try to find an existing playlist where the constructed path + // would match given input file. + while(cursor.moveToNext()) { + File tmp = getFileForName(mPlaylists, asM3u(cursor.getString(1))); + if (m3u.equals(tmp)) { + // Found a matching playlist: this will be our import target + // if the hash indicates that our version is outdated. + import_as = cursor.getString(1); + must_import = (hash != cursor.getLong(2)); + XT("importM3uPlaylist(): hash="+hash+", import="+must_import+", import_as="+import_as); + break; + } + } + cursor.close(); + } + + if (must_import) { + MediaLibrary.unregisterLibraryObserver(mLibraryObserver); + long import_id = Playlist.createPlaylist(mContext, import_as); + try (BufferedReader br = new BufferedReader(new FileReader(m3u))) { + String line; + while ((line = br.readLine()) != null) { + if (!(line.isEmpty() || line.startsWith(M3U_LINE_COMMENT_PREFIX))) { + // Handle relative paths and Windows directory separators. + final String mediaPath = FileUtils.resolve(mPlaylists, + new File(FileUtils.normalizeDirectorySeparators(line))); + Playlist.addToPlaylist(mContext, + import_id, + MediaUtils.buildFileQuery(mediaPath, Song.FILLED_PROJECTION, false /* recursive */)); + } + } + updatePlaylistMetadata(import_id, import_as, hash); + } catch(IOException e) { + Log.e("VanillaMusic", "Error while parsing m3u: "+e); + } + MediaLibrary.registerLibraryObserver(mLibraryObserver); + } + } + + /** + * Exports a single playlist ad M3U(8). + * + * @param id the playlist id to export. + * @return the newly written playlist, null if nothing was done. + */ + private File dumpAsM3uPlaylist(long id) { + XT("dumpM3uPlaylist("+id+")"); + if (id < 0) + throw new IllegalArgumentException("Called with negative id!"); + + if ((mSyncMode & SYNC_MODE_EXPORT) == 0) + return null; + + final String name = Playlist.getPlaylist(mContext, id); + if (name == null) + return null; + + final File m3u = getFileForName(mPlaylists, asM3u(name)); + + PrintWriter pw = null; + QueryTask query = MediaUtils.buildPlaylistQuery(id, Song.FILLED_PLAYLIST_PROJECTION); + Cursor cursor = query.runQuery(mContext); + try { + if (cursor != null) { + pw = new PrintWriter(m3u); + while (cursor.moveToNext()) { + // Write paths relative to the playlist export directory, if enabled. + String path = cursor.getString(1); + if (mExportRelativePaths) { + path = FileUtils.relativize(mPlaylists, new File(path)); + } + pw.println(path); + } + pw.flush(); + long hash_new = getHash(m3u); + updatePlaylistMetadata(id, name, hash_new); + } + } catch (IOException e) { + Log.v("VanillaMusic", "IOException while writing:", e); + } finally { + if (cursor != null) cursor.close(); + if (pw != null) pw.close(); + } + return m3u; + } + + /** + * Identify (and remove) playlist items which do not exist anymore + * and pick up any new M3U files. + */ + private void fullSyncScan() { + XT("fullSyncScan() running..."); + ArrayList<File> knownM3u = new ArrayList<>(); + + // First step is to check all known playlist metadata entries + // and check whether their native or M3U copy was purged. + final boolean do_purge = (mSyncMode & SYNC_MODE_PURGE) != 0; + Cursor cursor = queryDatabase(null); + if (cursor != null) { + while (cursor.moveToNext()) { + final long id = cursor.getLong(0); + final String name = cursor.getString(1); + // generates possible names of this playlist as M3U. + final File src_m3u = getFileForName(mPlaylists, asM3u(name)); + final File bak_m3u = getFileForName(mPlaylists, name + ".backup"); + + if (Playlist.getPlaylist(mContext, id) == null) { + // Native version of this playlist is gone, rename M3U variant: + if (do_purge) { + src_m3u.renameTo(bak_m3u); + } + deletePlaylistMetadata(id); + XT("fullSyncScan(): renamed old M3U -> "+bak_m3u); + } else if (do_purge && !src_m3u.exists()) { + // Source vanished, write one last dump and remove it. + File dump = dumpAsM3uPlaylist(id); + if (dump != null) { + dump.renameTo(bak_m3u); + } + Playlist.deletePlaylist(mContext, id); + deletePlaylistMetadata(id); + XT("fullSyncScan(): killed native playlist with id "+id); + } + // If this M3U exists, record it so that we don't try to re-import. + if (src_m3u.exists()) { + knownM3u.add(src_m3u); + } + } + cursor.close(); + } + + // Now list all M3U files in the playlists dir and import newly seen files. + File[] files = mPlaylists.listFiles(); + if (files != null) { + for (File f : files) { + final String fname = f.getName(); + if (isM3uFilename(fname) && !knownM3u.contains(f)) { + if (Playlist.getPlaylist(mContext, fromM3u(fname)) == -1) { + XT("fullSyncScan(): new M3U discovered, must import "+f); + sendUniqueMessage(MSG_IMPORT_M3U, f); + } else { + XT("fullSyncScan(): native version for "+f+" exists without metadata. Won't touch."); + } + } + } + } + } + + /** + * Returns a file object for given name + * + * @param name name of playlist to use. + * @return file object for given name + */ + private File getFileForName(File parent, String name) { + name = name.replaceAll("/", "_"); + File f = new File(parent, name); + return f; + } + + /** + * Updates the metadata of given playlist name + * + * @param id the id to update. + * @param name the name to register for this id. + */ + private void updatePlaylistMetadata(long id, String name, long hash) { + if (hash < 0) + throw new IllegalArgumentException("hash can not be negative"); + + XT("updatePlaylistMetadata of "+name+" to hash "+hash); + SQLiteDatabase dbh = getWritableDatabase(); + ContentValues values = new ContentValues(); + values.put(Database._ID, id); + values.put(Database.NAME, name); + values.put(Database.HASH, hash); + + deletePlaylistMetadata(id); + dbh.insert(Database.TABLE_NAME, null, values); + } + + /** + * Removes all known metadata of given id. + * + * @param id the id to purge. + */ + private void deletePlaylistMetadata(long id) { + SQLiteDatabase dbh = getWritableDatabase(); + dbh.delete(Database.TABLE_NAME, Database._ID+"=?", new String[] { Long.valueOf(id).toString() }); + } + + /** + * Returns true if the filename looks like an m3u file + * + * @param name the name to check + * @return true if file appears to be an M3U + */ + private boolean isM3uFilename(String name) { + if (name.length() < M3U_EXT.length()) + return false; + final int offset = name.length() - M3U_EXT.length(); + return name.toLowerCase().substring(offset).equals(M3U_EXT.toLowerCase()); + } + + /** + * Returns the m3u-filename of name + * + * @param name the name to use + * @return the m3u name + */ + private String asM3u(String name) { + return name + M3U_EXT; + } + + /** + * Returns the name of an m3u file + * + * @param name the m3u filename + * @return the non-m3u name + */ + private String fromM3u(String name) { + if (!isM3uFilename(name)) + throw new IllegalArgumentException("Not an M3U filename: "+name); + return name.substring(0, name.length() - M3U_EXT.length()); + } + + /** + * Hashes the contents of given file + * + * @param f the file to hash + * @return the calculated hash, -1 on error. + */ + private long getHash(File f) { + long hash = -1; + byte[] buff = new byte[4096]; + try(FileInputStream fis = new FileInputStream(f)) { + CRC32 crc = new CRC32(); + while(fis.read(buff) != -1) { + crc.update(buff); + } + hash = crc.getValue(); + if (hash < 0) + hash = hash * -1; + } catch(IOException e) { + // hash will be -1 which signals failure. + } + return hash; + } + + /** + * Obtain a cursor to our metadaata database. + * + * @param selection selection for query + * @return cursor with results. + */ + private Cursor queryDatabase(String selection) { + return getReadableDatabase().query(Database.TABLE_NAME, Database.FILLED_PROJECTION, selection, null, null, null, null); + } + + /** + * Library observer callback which notifies us about media library + * events. + * + * @param type the event type + * @param id the id of given type which had a change + * @param ongoing whether or not to expect more of these events + */ + private final LibraryObserver mLibraryObserver = new LibraryObserver() { + @Override + public void onChange(LibraryObserver.Type type, long id, boolean ongoing) { + if (type != LibraryObserver.Type.PLAYLIST || ongoing) + return; + + if (!shouldDispatch()) + return; + + int msg = MSG_DUMP_M3U; // Default: export this playlist ID. + if (id == LibraryObserver.Value.UNKNOWN) { + // An unknown (all?) playlist was modified: dump all to M3U + msg = MSG_DUMP_ALL_M3U; + } + if (id == LibraryObserver.Value.OUTDATED) { + // Our data is wrong, reimport all M3Us + msg = MSG_FORCE_M3U_IMPORT; + } + + XT("LibraryObserver::onChange id="+id+", msg="+msg); + sendUniqueMessage(msg, id); + } + }; + + /** + * Returns a new observer which monitors the playlists directory. + * + * @param target The target playlists directory. + * @return A new observer for the playlists directory. + */ + private FileObserver getFileObserver(File target) { + final int mask = FileObserver.CLOSE_WRITE | FileObserver.MOVED_FROM | FileObserver.MOVED_TO | FileObserver.DELETE; + XT("new file observer at "+target+" with mask "+mask); + + return new FileObserver(target.getAbsolutePath(), mask) { + /** + * Observer which monitors the playlists directory. + * + * @param event the event type + * @param dirent the filename which triggered the event. + */ + @Override + public void onEvent(int event, String dirent) { + // Events such as IN_IGNORED pass dirent = null. + if (dirent == null) + return; + + if (!isM3uFilename(dirent)) + return; + + if (!shouldDispatch()) + return; + + if ((event & (FileObserver.MOVED_FROM | FileObserver.DELETE)) != 0) { + // A M3U vanished, do a full scan. + XT("FileObserver::onEvent DELETE of "+dirent+" triggers FULL_SYNC_SCAN"); + sendUniqueMessage(MSG_FULL_SYNC_SCAN, 0); + } + if ((event & (FileObserver.MOVED_TO | FileObserver.CLOSE_WRITE)) != 0) { + // Single file was created, import it. + XT("FileObserver::onEvent WRITE of "+dirent+" triggers IMPORT_M3U"); + sendUniqueMessage(MSG_IMPORT_M3U, new File(mPlaylists, dirent)); + } + } + }; + } + + private void XT(String s) { + if (DEBUG) { + try(PrintWriter pw = new PrintWriter(new FileOutputStream(new File("/sdcard/playlist-observer.txt"), true))) { + pw.println(System.currentTimeMillis()/1000+": "+s); + Log.v("VanillaMusic", "XTRACE: "+s); + } catch(Exception e) {} + } + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistObserverDirActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistObserverDirActivity.java new file mode 100644 index 0000000..dcf6df5 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistObserverDirActivity.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.os.Bundle; +import android.content.SharedPreferences; + +import java.io.File; +import java.util.ArrayList; + +public class PlaylistObserverDirActivity extends FolderPickerActivity { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setTitle(R.string.filebrowser_start); + + // Start at currently configured directory. + String current = SharedPrefHelper.getSettings(this).getString(PrefKeys.PLAYLIST_SYNC_FOLDER, PrefDefaults.PLAYLIST_SYNC_FOLDER); + setCurrentDir(new File(current)); + } + + + @Override + public void onFolderPicked(File directory, ArrayList<String> a, ArrayList<String> b) { + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(this).edit(); + editor.putString(PrefKeys.PLAYLIST_SYNC_FOLDER, directory.getAbsolutePath()); + editor.apply(); + finish(); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistTask.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistTask.java new file mode 100644 index 0000000..b0a9420 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PlaylistTask.java @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2013 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +package ch.blinkenlights.android.vanilla; + +import java.util.ArrayList; + +/** + * Represents a pending playlist manipulation + */ +public class PlaylistTask { + + /** + * ID of this playlist to manipulate + */ + public long playlistId; + /** + * Name of this playlist (used for the toast message) + */ + public String name; + /** + * Populate playlist using this QueryTask + */ + public QueryTask query; + /** + * Populate playlist using this audioIds + */ + public ArrayList<Long> audioIds; + + + public PlaylistTask(long playlistId, String name) { + this.playlistId = playlistId; + this.name = name; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PluginUtils.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PluginUtils.java new file mode 100644 index 0000000..18fe1eb --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PluginUtils.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2016-2018 Oleg Chernovskiy <adonai@xaker.ru> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.widget.Toast; +import androidx.annotation.NonNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Common plugin utilities and constants reside here. + * Note that public `action` and `extra` strings are common over all plugins, so please keep them in sync. + */ + +public class PluginUtils { + + private PluginUtils() { + } + + // these actions are for passing between main player and plugins + public static final String ACTION_REQUEST_PLUGIN_PARAMS = "ch.blinkenlights.android.vanilla.action.REQUEST_PLUGIN_PARAMS"; // broadcast + public static final String ACTION_HANDLE_PLUGIN_PARAMS = "ch.blinkenlights.android.vanilla.action.HANDLE_PLUGIN_PARAMS"; // answer + public static final String ACTION_LAUNCH_PLUGIN = "ch.blinkenlights.android.vanilla.action.LAUNCH_PLUGIN"; // targeted at selected by user + + // these are used by plugins to describe themselves + public static final String EXTRA_PARAM_PLUGIN_NAME = "ch.blinkenlights.android.vanilla.extra.PLUGIN_NAME"; + public static final String EXTRA_PARAM_PLUGIN_APP = "ch.blinkenlights.android.vanilla.extra.PLUGIN_APP"; + public static final String EXTRA_PARAM_PLUGIN_DESC = "ch.blinkenlights.android.vanilla.extra.PLUGIN_DESC"; + + // this is passed to plugin when it is selected by user + public static final String EXTRA_PARAM_URI = "ch.blinkenlights.android.vanilla.extra.URI"; + public static final String EXTRA_PARAM_SONG_TITLE = "ch.blinkenlights.android.vanilla.extra.SONG_TITLE"; + public static final String EXTRA_PARAM_SONG_ALBUM = "ch.blinkenlights.android.vanilla.extra.SONG_ALBUM"; + public static final String EXTRA_PARAM_SONG_ARTIST = "ch.blinkenlights.android.vanilla.extra.SONG_ARTIST"; + + static final String EXTRA_PLUGIN_MAP = "ch.blinkenlights.android.vanilla.internal.extra.PLUGIN_MAP"; + + /** + * Find all vanilla plugins by their very specific broadcast receiver intent. + * @param ctx context to use when resolving packages. + * @return list of all resolved plugins, may be empty but never null + */ + @NonNull + private static List<ResolveInfo> resolvePlugins(Context ctx) { + PackageManager pm = ctx.getPackageManager(); + Intent filter = new Intent(ACTION_REQUEST_PLUGIN_PARAMS); + return pm.queryBroadcastReceivers(filter, PackageManager.MATCH_DISABLED_COMPONENTS); + } + + /** + * Checks whether does any of vanilla plugins exist on this Android system + * @param ctx context to use when resolving packages + * @return true if at least one plugin is installed, false otherwise + */ + public static boolean checkPlugins(Context ctx) { + return !resolvePlugins(ctx).isEmpty(); + } + + /** + * Same as {@link #resolvePlugins(Context)} but in a map convenient for showing in dialogs. + * @param ctx ctx context to use when resolving packages + * @return all vanilla plugins in a map App Name <-> App Info + */ + @NonNull + public static Map<String, ApplicationInfo> getPluginMap(Context ctx) { + PackageManager pm = ctx.getPackageManager(); + List<ResolveInfo> resolved = resolvePlugins(ctx); + + Map<String, ApplicationInfo> pluginMap = new HashMap<>(resolved.size()); + for (ResolveInfo ri : resolved) { + ApplicationInfo appInfo = ri.activityInfo.applicationInfo; + pluginMap.put(appInfo.loadLabel(pm).toString(), appInfo); + } + return pluginMap; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PrefDefaults.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PrefDefaults.java new file mode 100644 index 0000000..8bdfc6c --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PrefDefaults.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2015-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.os.Environment; +import java.io.File; + +/** + * SharedPreference default values. Must be kept in sync with keys in res/xml/prefs_*.xml. + */ +public class PrefDefaults { + private PrefDefaults() { + // Private constructor to hide implicit one. + } + + public static final Action COVER_LONGPRESS_ACTION = Action.Nothing; + public static final Action COVER_PRESS_ACTION = Action.Nothing; + public static final String DEFAULT_ACTION_INT = "9"; + public static final String DEFAULT_PLAYLIST_ACTION = "3"; + public static final boolean COVERLOADER_ANDROID = true; + public static final boolean COVERLOADER_VANILLA = true; + public static final boolean COVERLOADER_SHADOW = true; + public static final boolean COVERLOADER_INLINE = true; + public static final boolean COVER_ON_LOCKSCREEN = true; + public static final boolean DISABLE_LOCKSCREEN = false; + public static final String DISPLAY_MODE = "2"; + public static final boolean DOUBLE_TAP = false; + public static final boolean ENABLE_SHAKE = false; + public static final boolean HEADSET_ONLY = false; + public static final boolean HEADSET_PAUSE = true; + public static final int IDLE_TIMEOUT = 3600; + public static final int LIBRARY_PAGE = 0; + public static final String NOTIFICATION_ACTION = "0"; + public static final String NOTIFICATION_VISIBILITY = "0"; + public static final boolean NOTIFICATION_NAG = false; + public static final boolean PLAYBACK_ON_STARTUP = false; + public static final boolean SCROBBLE = false; + public static final Action SHAKE_ACTION = Action.NextSong; + public static final int SHAKE_THRESHOLD = 80; + public static final boolean STOCK_BROADCAST = true; + public static final Action SWIPE_DOWN_ACTION = Action.Nothing; + public static final Action SWIPE_UP_ACTION = Action.Nothing; + public static final String TAB_ORDER = null; + public static final boolean USE_IDLE_TIMEOUT = false; + public static final boolean VISIBLE_CONTROLS = true; + public static final boolean VISIBLE_EXTRA_INFO = false; + public static final boolean ENABLE_TRACK_REPLAYGAIN = false; + public static final boolean ENABLE_ALBUM_REPLAYGAIN = false; + public static final int REPLAYGAIN_BUMP = 75; // seek bar is 150 -> 75 == middle == 0 + public static final int REPLAYGAIN_UNTAGGED_DEBUMP = 150; // seek bar is 150 -> == 0 + public static final boolean ENABLE_READAHEAD = false; + public static final String SELECTED_THEME = "7"; + public static final String FILESYSTEM_BROWSE_START = ""; + public static final int VOLUME_DURING_DUCKING = 50; + public static final int AUTOPLAYLIST_PLAYCOUNTS = 0; + public static final boolean IGNORE_AUDIOFOCUS_LOSS = false; + public static final boolean ENABLE_SCROLL_TO_SONG = false; + public static final boolean QUEUE_ENABLE_SCROLL_TO_SONG = false; + public static final boolean KEEP_SCREEN_ON = false; + public static final String PLAYLIST_SYNC_MODE = "0"; + public static final String PLAYLIST_SYNC_FOLDER = (new File(Environment.getExternalStorageDirectory(), "Playlists")).getAbsolutePath(); + public static final boolean PLAYLIST_EXPORT_RELATIVE_PATHS = false; + public static final boolean JUMP_TO_ENQUEUED_ON_PLAY = true; + public static final boolean DISABLE_GAPLESS_PLAYBACK = false; +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PrefKeys.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PrefKeys.java new file mode 100644 index 0000000..57a1654 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PrefKeys.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2012-2015 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +/** + * SharedPreference keys. Must be kept in sync with {@link PrefDefaults}. + */ +public class PrefKeys { + private PrefKeys() { + // Private constructor to hide implicit one. + } + + public static final String COVER_LONGPRESS_ACTION = "cover_longpress_action"; + public static final String COVER_PRESS_ACTION = "cover_press_action"; + public static final String DEFAULT_ACTION_INT = "default_action_int"; + public static final String DEFAULT_PLAYLIST_ACTION = "default_playlist_action"; + public static final String COVERLOADER_ANDROID = "coverloader_android"; + public static final String COVERLOADER_VANILLA = "coverloader_vanilla"; + public static final String COVERLOADER_SHADOW = "coverloader_shadow"; + public static final String COVERLOADER_INLINE = "coverloader_inline"; + public static final String COVER_ON_LOCKSCREEN = "cover_on_lockscreen"; + public static final String DISABLE_LOCKSCREEN = "disable_lockscreen"; + public static final String DISPLAY_MODE = "display_mode"; + public static final String DOUBLE_TAP = "double_tap"; + public static final String ENABLE_SHAKE = "enable_shake"; + public static final String HEADSET_ONLY = "headset_only"; + public static final String HEADSET_PAUSE = "headset_pause"; + public static final String IDLE_TIMEOUT = "idle_timeout"; + public static final String LIBRARY_PAGE = "library_page"; + public static final String NOTIFICATION_ACTION = "notification_action"; + public static final String NOTIFICATION_VISIBILITY = "notification_visibility"; + public static final String PLAYBACK_ON_STARTUP = "playback_on_startup"; + public static final String SCROBBLE = "scrobble"; + public static final String SHAKE_ACTION = "shake_action"; + public static final String SHAKE_THRESHOLD = "shake_threshold"; + public static final String STOCK_BROADCAST = "stock_broadcast"; + public static final String SWIPE_DOWN_ACTION = "swipe_down_action"; + public static final String SWIPE_UP_ACTION = "swipe_up_action"; + public static final String TAB_ORDER = "tab_order"; + public static final String USE_IDLE_TIMEOUT = "use_idle_timeout"; + public static final String VISIBLE_CONTROLS = "visible_controls"; + public static final String VISIBLE_EXTRA_INFO = "visible_extra_info"; + public static final String ENABLE_TRACK_REPLAYGAIN = "enable_track_replaygain"; + public static final String ENABLE_ALBUM_REPLAYGAIN = "enable_album_replaygain"; + public static final String REPLAYGAIN_BUMP = "replaygain_bump"; + public static final String REPLAYGAIN_UNTAGGED_DEBUMP = "replaygain_untagged_debump"; + public static final String ENABLE_READAHEAD = "enable_readahead"; + public static final String SELECTED_THEME = "selected_theme"; + public static final String FILESYSTEM_BROWSE_START = "filesystem_browse_start"; + public static final String VOLUME_DURING_DUCKING = "volume_during_ducking"; + public static final String AUTOPLAYLIST_PLAYCOUNTS = "playcounts_autoplaylist"; + public static final String IGNORE_AUDIOFOCUS_LOSS = "ignore_audiofocus_loss"; + public static final String ENABLE_SCROLL_TO_SONG = "enable_scroll_to_song"; + public static final String QUEUE_ENABLE_SCROLL_TO_SONG = "queue_enable_scroll_to_song"; + public static final String KEEP_SCREEN_ON = "keep_screen_on"; + public static final String PLAYLIST_SYNC_MODE = "playlist_sync_mode"; + public static final String PLAYLIST_SYNC_FOLDER = "playlist_sync_folder"; + public static final String PLAYLIST_EXPORT_RELATIVE_PATHS = "playlist_export_relative_paths"; + public static final String JUMP_TO_ENQUEUED_ON_PLAY = "jump_to_enqueued_on_play"; + public static final String DISABLE_GAPLESS_PLAYBACK = "disable_gapless_playback"; +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesActivity.java new file mode 100644 index 0000000..53b8413 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesActivity.java @@ -0,0 +1,318 @@ +/* + * Copyright (C) 2012-2015 Adrian Ulrich <adrian@blinkenlights.ch> + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.FragmentManager; +import android.content.DialogInterface; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.PreferenceActivity; +import android.preference.PreferenceFragment; +import android.preference.CheckBoxPreference; +import android.view.LayoutInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.webkit.WebViewFragment; +import android.widget.Toast; +import android.content.Context; +import android.content.Intent; +import android.media.audiofx.AudioEffect; +import android.net.Uri; +import android.util.TypedValue; +import java.util.ArrayList; +import java.util.List; + +/** + * The preferences activity in which one can change application preferences. + */ +public class PreferencesActivity extends PreferenceActivity + implements SharedPreferences.OnSharedPreferenceChangeListener +{ + + /** + * The package name of our external helper app + */ + private static final String VPLUG_PACKAGE_NAME = "ch.blinkenlights.android.vanillaplug"; + + /** + * Initialize the activity, loading the preference specifications. + */ + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle savedInstanceState) + { + ThemeHelper.setTheme(this, R.style.BackActionBar); + super.onCreate(savedInstanceState); + SharedPrefHelper.getSettings(this).registerOnSharedPreferenceChangeListener(this); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + SharedPrefHelper.getSettings(this).unregisterOnSharedPreferenceChangeListener(this); + } + + @Override + public void onBuildHeaders(List<Header> target) + { + ArrayList<Header> tmp = new ArrayList<Header>(); + loadHeadersFromResource(R.xml.preference_headers, tmp); + + for(Header obj : tmp) { + target.add(obj); + } + } + + @Override + public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) { + if (PrefKeys.SELECTED_THEME.equals(key)) { + // this gets called by all preference instances: we force them to redraw + // themselfes if the theme changed + recreate(); + } + } + + public static class AudioFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_audio); + } + } + + public static class ReplayGainFragment extends PreferenceFragment { + CheckBoxPreference cbTrackReplayGain; + CheckBoxPreference cbAlbumReplayGain; + SeekBarPreference sbGainBump; + SeekBarPreference sbUntaggedDebump; + + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + addPreferencesFromResource(R.xml.preference_replaygain); + cbTrackReplayGain = (CheckBoxPreference)findPreference(PrefKeys.ENABLE_TRACK_REPLAYGAIN); + cbAlbumReplayGain = (CheckBoxPreference)findPreference(PrefKeys.ENABLE_ALBUM_REPLAYGAIN); + sbGainBump = (SeekBarPreference)findPreference(PrefKeys.REPLAYGAIN_BUMP); + sbUntaggedDebump = (SeekBarPreference)findPreference(PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP); + + Preference.OnPreferenceClickListener pcListener = new Preference.OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + updateConfigWidgets(); + return false; + } + }; + + cbTrackReplayGain.setOnPreferenceClickListener(pcListener); + cbAlbumReplayGain.setOnPreferenceClickListener(pcListener); + updateConfigWidgets(); + } + + private void updateConfigWidgets() { + boolean rgOn = (cbTrackReplayGain.isChecked() || cbAlbumReplayGain.isChecked()); + sbGainBump.setEnabled(rgOn); + sbUntaggedDebump.setEnabled(rgOn); + } + } + + public static class EqualizerFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + Context context = getActivity(); + int mAudioSession = 0; + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + mAudioSession = service.getAudioSession(); + } + + try { + final Intent effects = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL); + effects.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName()); + effects.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mAudioSession); + startActivityForResult(effects, 0); + } catch (Exception e) { + // ignored. Whee! + } + + FragmentManager fragmentManager = getFragmentManager(); + if (!fragmentManager.isStateSaved()) { + fragmentManager.popBackStack(); + } + } + } + + public static class PlaybackFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_playback); + } + } + + public static class LibraryFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_library); + } + } + + public static class NotificationsFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_notifications); + } + } + + public static class ShakeFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_shake); + } + } + + public static class CoverArtFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_coverart); + } + } + + public static class MiscFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_misc); + } + } + + public static class PlaylistFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + addPreferencesFromResource(R.xml.preference_playlist); + } + } + + public static class HelpFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + Activity activity = getActivity(); + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/vanilla-music/vanilla-music.github.io/wiki")); + if (intent != null) { + startActivity(intent); + } + activity.finish(); + } + } + + public static class AboutFragment extends WebViewFragment { + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) + { + WebView view = (WebView)super.onCreateView(inflater, container, savedInstanceState); + view.getSettings().setJavaScriptEnabled(true); + + TypedValue value = new TypedValue(); + getActivity().getTheme().resolveAttribute(R.attr.overlay_foreground_color, value, true); + String fontColor = TypedValue.coerceToString(value.type, value.data); + view.loadUrl("file:///android_asset/about.html?"+Uri.encode(fontColor)); + view.setBackgroundColor(Color.TRANSPARENT); + return view; + } + } + + public static class HeadsetLaunchFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + + Activity activity = getActivity(); + Intent intent = activity.getPackageManager().getLaunchIntentForPackage(VPLUG_PACKAGE_NAME); + + if (intent != null) { + startActivity(intent); + FragmentManager fragmentManager = getFragmentManager(); + if (!fragmentManager.isStateSaved()) { + fragmentManager.popBackStack(); + } + } else { + // package is not installed, ask user to install it + new AlertDialog.Builder(activity) + .setTitle(R.string.headset_launch_title) + .setMessage(R.string.headset_launch_app_missing) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + try { + Intent marketIntent = new Intent(Intent.ACTION_VIEW); + marketIntent.setData(Uri.parse("market://details?id="+VPLUG_PACKAGE_NAME)); + startActivity(marketIntent); + getActivity().onBackPressed(); + } catch (android.content.ActivityNotFoundException e) { + Toast.makeText(getActivity(), "Failed to open market: " + e, Toast.LENGTH_SHORT).show(); + } + } + }) + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + getActivity().onBackPressed(); + } + }) + .show(); + } + } + } + + @Override + protected boolean isValidFragment(String fragmentName) { + return true; + } + + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesMediaLibrary.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesMediaLibrary.java new file mode 100644 index 0000000..1be3a2d --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesMediaLibrary.java @@ -0,0 +1,414 @@ +/* + * Copyright (C) 2017-2021 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; +import ch.blinkenlights.android.medialibrary.LibraryObserver; + +import android.app.AlertDialog; +import android.app.Fragment; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.database.Cursor; +import android.os.Bundle; +import android.os.Environment; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +public class PreferencesMediaLibrary extends Fragment implements View.OnClickListener { + /** + * Our start button + */ + private View mStartButton; + /** + * The cancel button + */ + private View mCancelButton; + /** + * The edit-media-folders button + */ + private View mEditButton; + /** + * The debug / progress text describing the scan status + */ + private TextView mProgressText; + /** + * The progress bar + */ + private ProgressBar mProgressBar; + /** + * The number of tracks on this device + */; + private TextView mStatsTracks; + /** + * The number of hours of music we have + */ + private TextView mStatsLibraryPlaytime; + /** + * The total listening time + */ + private TextView mStatsListenPlaytime; + /** + * A list of scanned media directories + */ + private TextView mMediaDirectories; + /** + * Checkbox for full scan + */ + private CheckBox mFullScanCheck; + /** + * Checkbox for drop + */ + private CheckBox mDropDbCheck; + /** + * Checkbox for album group option + */ + private CheckBox mGroupAlbumsCheck; + /** + * Checkbox for targreader flavor + */ + private CheckBox mForceBastpCheck; + /** + * Set if we should start a full scan due to option changes + */ + private boolean mFullScanPending; + /** + * Set if we are in the edit dialog + */ + private boolean mIsEditingDirectories; + /** + * The original state of our media folders. + */ + private String mInitialMediaFolders; + + private final LibraryObserver mLibraryObserver = new LibraryObserver() { + @Override + public void onChange(LibraryObserver.Type type, long id, boolean ongoing) { + if (type != LibraryObserver.Type.SCAN_PROGRESS) + return; + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + updateProgress(); + } + }); + } + }; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return inflater.inflate(R.layout.medialibrary_preferences, container, false); + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + mStartButton = (View)view.findViewById(R.id.start_button); + mCancelButton = (View)view.findViewById(R.id.cancel_button); + mEditButton = (View)view.findViewById(R.id.edit_button); + mProgressText = (TextView)view.findViewById(R.id.media_stats_progress_text); + mProgressBar = (ProgressBar)view.findViewById(R.id.media_stats_progress_bar); + mStatsTracks = (TextView)view.findViewById(R.id.media_stats_tracks); + mStatsLibraryPlaytime = (TextView)view.findViewById(R.id.media_stats_library_playtime); + mStatsListenPlaytime = (TextView)view.findViewById(R.id.media_stats_listen_playtime); + mMediaDirectories = (TextView)view.findViewById(R.id.media_directories); + mFullScanCheck = (CheckBox)view.findViewById(R.id.media_scan_full); + mDropDbCheck = (CheckBox)view.findViewById(R.id.media_scan_drop_db); + mGroupAlbumsCheck = (CheckBox)view.findViewById(R.id.media_scan_group_albums); + mForceBastpCheck = (CheckBox)view.findViewById(R.id.media_scan_force_bastp); + + // Bind onClickListener to some elements + mStartButton.setOnClickListener(this); + mCancelButton.setOnClickListener(this); + mEditButton.setOnClickListener(this); + mGroupAlbumsCheck.setOnClickListener(this); + mForceBastpCheck.setOnClickListener(this); + // Enable options menu. + setHasOptionsMenu(true); + } + + @Override + public void onResume() { + super.onResume(); + + // We got freshly created and user didn't have a chance + // to edit anything: remember this state + if (mInitialMediaFolders == null) + mInitialMediaFolders = getMediaFoldersDescription(); + + // Returned from edit dialog + if (mIsEditingDirectories) { + mIsEditingDirectories = false; + // trigger a scan if user changed its preferences + // in the edit dialog + if (!mInitialMediaFolders.equals(getMediaFoldersDescription())) + mFullScanPending = true; + } + + MediaLibrary.registerLibraryObserver(mLibraryObserver); + updateProgress(); + updatePreferences(null); + } + + @Override + public void onPause() { + super.onPause(); + MediaLibrary.unregisterLibraryObserver(mLibraryObserver); + // User exited this view -> scan if needed + if (mFullScanPending && !mIsEditingDirectories) { + MediaLibrary.startLibraryScan(getActivity(), true, true); + mInitialMediaFolders = null; + mFullScanPending = false; + } + } + + @Override + public void onClick(View view) { + switch (view.getId()) { + case R.id.start_button: + startButtonPressed(view); + break; + case R.id.cancel_button: + cancelButtonPressed(view); + break; + case R.id.edit_button: + editButtonPressed(view); + break; + case R.id.media_scan_group_albums: + case R.id.media_scan_force_bastp: + confirmUpdatePreferences((CheckBox)view); + break; + } + } + + private static final int MENU_DUMP_DB = 1; + private static final int MENU_FORCE_M3U_IMPORT = 2; + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + super.onCreateOptionsMenu(menu, inflater); + menu.add(0, MENU_DUMP_DB, 30, R.string.dump_database); + menu.add(0, MENU_FORCE_M3U_IMPORT, 30, R.string.force_m3u_import); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case MENU_DUMP_DB: + final Context context = getActivity(); + final String path = Environment.getExternalStorageDirectory().getPath() + "/dbdump-" + context.getPackageName() + ".sqlite"; + final String msg = getString(R.string.dump_database_result, path); + + MediaLibrary.createDebugDump(context, path); + Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); + break; + case MENU_FORCE_M3U_IMPORT: + // Sending an 'OUTDATED' event signals that our playlist information is wrong. + // This should trigger a full re-import. + MediaLibrary.notifyObserver(LibraryObserver.Type.PLAYLIST, LibraryObserver.Value.OUTDATED, false); + break; + default: + return super.onOptionsItemSelected(item); + } + return true; + } + /** + * Wrapper for updatePreferences() which warns the user about + * possible consequences. + * + * @param checkbox the checkbox which was changed + */ + private void confirmUpdatePreferences(final CheckBox checkbox) { + if (mFullScanPending) { + // User was already warned, so we can just dispatch this + // without nagging again + updatePreferences(checkbox); + return; + } + + new AlertDialog.Builder(getActivity()) + .setTitle(R.string.media_scan_preferences_change_title) + .setMessage(R.string.media_scan_preferences_change_message) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + mFullScanPending = true; + confirmUpdatePreferences(checkbox); + } + }) + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + // restore old condition if use does not want to proceed + checkbox.setChecked(!checkbox.isChecked()); + } + }) + .show(); + } + + /** + * Initializes and updates the scanner preferences + * + * @param checkbox the item to update, may be null + * @return void but sets the checkboxes to their correct state + */ + private void updatePreferences(CheckBox checkbox) { + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(getActivity()); + + if (checkbox == mGroupAlbumsCheck) + prefs.groupAlbumsByFolder = mGroupAlbumsCheck.isChecked(); + if (checkbox == mForceBastpCheck) + prefs.forceBastp = mForceBastpCheck.isChecked(); + + MediaLibrary.setPreferences(getActivity(), prefs); + + mGroupAlbumsCheck.setChecked(prefs.groupAlbumsByFolder); + mForceBastpCheck.setChecked(prefs.forceBastp); + mMediaDirectories.setText(getMediaFoldersDescription()); + } + + /** + * Returns a textual representation of the media folder state + * + * @return string describing our directory scan preferences + */ + private String getMediaFoldersDescription() { + MediaLibrary.Preferences prefs = MediaLibrary.getPreferences(getActivity()); + String description = ""; + for (String path : prefs.mediaFolders) { + description += "✔ " + path + "\n"; + } + for (String path : prefs.blacklistedFolders) { + description += "✘ " + path + "\n"; + } + return description; + } + + /** + * Updates the view of this fragment with current information + */ + private void updateProgress() { + Context context = getActivity(); + MediaLibrary.ScanProgress progress = MediaLibrary.describeScanProgress(context); + + boolean idle = !progress.isRunning; + mProgressText.setText(progress.lastFile); + mProgressBar.setMax(progress.total); + mProgressBar.setProgress(progress.seen); + + mStartButton.setEnabled(idle); + mEditButton.setEnabled(idle); + mDropDbCheck.setEnabled(idle); + mFullScanCheck.setEnabled(idle); + mForceBastpCheck.setEnabled(idle); + mGroupAlbumsCheck.setEnabled(idle); + + mCancelButton.setVisibility(idle ? View.GONE : View.VISIBLE); + mProgressText.setVisibility(idle ? View.GONE : View.VISIBLE); + mProgressBar.setVisibility(idle ? View.GONE : View.VISIBLE); + + Integer songCount = MediaLibrary.getLibrarySize(context); + mStatsTracks.setText(songCount.toString()); + + float libraryPlaytime = calculateSongSum(context, MediaLibrary.SongColumns.DURATION) / 3600000F; + mStatsLibraryPlaytime.setText(String.format("%.1f", libraryPlaytime)); + + float listenPlaytime = calculateSongSum(context, MediaLibrary.SongColumns.PLAYCOUNT+"*"+MediaLibrary.SongColumns.DURATION) / 3600000F; + mStatsListenPlaytime.setText(String.format("%.1f", listenPlaytime)); + } + + /** + * Queries the media library and calculates the sum of given column. + * + * @param context the context to use + * @param column the column to sum up + * @return the play time of the library in ms + */ + public long calculateSongSum(Context context, String column) { + long duration = 0; + Cursor cursor = MediaLibrary.queryLibrary(context, MediaLibrary.TABLE_SONGS, new String[]{"SUM("+column+")"}, null, null, null); + if (cursor != null) { + if (cursor.moveToFirst()) { + duration = cursor.getLong(0); + } + cursor.close(); + } + return duration; + } + + /** + * Called when the user hits the start button + * + * @param view the view which was pressed + */ + public void startButtonPressed(View view) { + MediaLibrary.startLibraryScan(getActivity(), mFullScanCheck.isChecked(), mDropDbCheck.isChecked()); + } + + /** + * Called when the user hits the cancel button + * + * @param view the view which was pressed + */ + public void cancelButtonPressed(View view) { + MediaLibrary.abortLibraryScan(getActivity()); + } + + /** + * Called when the user hits the edit button + * + * @param view the view which was pressed + */ + private void editButtonPressed(final View view) { + if (mFullScanPending) { + // no need to nag if we are scanning anyway + startMediaFoldersSelection(); + return; + } + + new AlertDialog.Builder(getActivity()) + .setTitle(R.string.media_scan_preferences_change_title) + .setMessage(R.string.media_scan_preferences_change_message) + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + startMediaFoldersSelection(); + } + }) + .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) {} + }) + .show(); + } + + /** + * Launches the edit dialog + */ + private void startMediaFoldersSelection() { + mIsEditingDirectories = true; + startActivity(new Intent(getActivity(), MediaFoldersSelectionActivity.class)); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesTheme.java b/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesTheme.java new file mode 100644 index 0000000..032da0c --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/PreferencesTheme.java @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.PreferenceFragment; +import android.preference.PreferenceScreen; + + +public class PreferencesTheme extends PreferenceFragment + implements Preference.OnPreferenceClickListener +{ + private Context mContext; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mContext = getActivity(); + + // Themes are 'pre-compiled' in themes-list: get all values + // and append them to our newly created PreferenceScreen + PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(mContext); + final String[] entries = getResources().getStringArray(R.array.theme_entries); + final String[] values = getResources().getStringArray(R.array.theme_values); + final String[] ids = getResources().getStringArray(R.array.theme_ids); + + for (int i = 0; i < entries.length; i++) { + + int[] attrs = decodeValue(values[i]); + + final Preference pref = new Preference(mContext); + pref.setPersistent(false); + pref.setOnPreferenceClickListener(this); + pref.setTitle(entries[i]); + pref.setKey(ids[i]); // preference value of this theme + pref.setIcon(generateThemePreview(attrs)); + screen.addPreference(pref); + } + setPreferenceScreen(screen); + } + + @Override + public boolean onPreferenceClick(Preference pref) { + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(mContext).edit(); + editor.putString(PrefKeys.SELECTED_THEME, pref.getKey()); + editor.apply(); + return true; + } + + + private int[] decodeValue(String v) { + String[] parts = v.split(","); + int[] values = new int[parts.length]; + for (int i=0; i<parts.length; i++) { + long parsedLong = (long)Long.decode(parts[i]); // the colors overflow an int, so we first must parse it as Long to make java happy. + values[i] = (int)parsedLong; + } + return values; + } + + private Drawable generateThemePreview(int[] colors) { + final int size = (int) getResources().getDimension(R.dimen.cover_size); + final int step = size / colors.length; + + Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565); + Canvas canvas = new Canvas(bitmap); + Paint paint = new Paint(); + + paint.setStyle(Paint.Style.FILL); + for (int i=0; i < colors.length; i++) { + paint.setColor(colors[i]); + canvas.drawRect(0, step*i, size, size, paint); + } + + Drawable d = new BitmapDrawable(mContext.getResources(), bitmap); + return d; + } + + + + + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/QueryTask.java b/app/src/main/java/ch/blinkenlights/android/vanilla/QueryTask.java new file mode 100644 index 0000000..da97938 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/QueryTask.java @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.database.Cursor; + +/** + * Represents a pending query. + */ +public class QueryTask { + public final String table; + public final String[] projection; + public final String selection; + public final String[] selectionArgs; + public String sortOrder; + + /** + * Used for {@link SongTimeline#addSongs(android.content.Context, QueryTask)}. + * One of SongTimeline.MODE_*. + */ + public int mode; + + /** + * Type of the group being query. One of MediaUtils.TYPE_*. + */ + public int type; + + /** + * Data. Required value depends on value of mode. See individual mode + * documentation for details. + */ + public long data; + + /** + * Create the tasks. All arguments are passed directly to + * MediaLibrary.runQuery(). + */ + public QueryTask(String table, String[] projection, String selection, String[] selectionArgs, String sortOrder) { + this.table = table; + this.projection = projection; + this.selection = selection; + this.selectionArgs = selectionArgs; + this.sortOrder = sortOrder; + } + + /** + * Run the query. Should be called on a background thread. + * + * @param context The Context to use + */ + public Cursor runQuery(Context context) { + return MediaLibrary.queryLibrary(context, table, projection, selection, selectionArgs, sortOrder); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ReadaheadThread.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ReadaheadThread.java new file mode 100644 index 0000000..025bf10 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ReadaheadThread.java @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2015 - 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +package ch.blinkenlights.android.vanilla; + +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Message; +import android.os.Process; +import android.util.Log; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +class ReadaheadThread implements Handler.Callback { + + /** + * How many bytes we are going to read per run + */ + private static final int BYTES_PER_READ = 32768; + /** + * Our message handler + */ + private Handler mHandler; + /** + * The global (current) file input stream + */ + private FileInputStream mInputStream; + /** + * The filesystem path used to create the current mInputStream + */ + private String mPath; + /** + * The calculated delay between `BYTES_PER_READ' sized + * read operations + */ + private long mReadDelay; + /** + * Scratch space to read junk data + */ + private byte[] mScratch; + + + public ReadaheadThread() { + mScratch = new byte[BYTES_PER_READ]; + HandlerThread handlerThread = new HandlerThread("ReadaheadThread", Process.THREAD_PRIORITY_LOWEST); + handlerThread.start(); + mHandler = new Handler(handlerThread.getLooper(), this); + } + + /** + * Aborts all current in-flight RPCs, pausing the readahead operation + */ + public void pause() { + mHandler.removeMessages(MSG_SET_SONG); + mHandler.removeMessages(MSG_READ_CHUNK); + } + + /** + * Starts a new readahead operation. Will resume if `song.path' equals + * the currently open file + * + * @param path The path to read ahead + */ + public void setSong(final Song song) { + pause(); // cancell all in-flight rpc's + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_SONG, song), 1000); + } + + private static final int MSG_SET_SONG = 1; + private static final int MSG_READ_CHUNK = 2; + @Override + public boolean handleMessage(Message message) { + switch (message.what) { + case MSG_SET_SONG: { + Song song = (Song)message.obj; + + if (mInputStream != null && !mPath.equals(song.path)) { + // current file does not match requested one: clean it + try { + mInputStream.close(); + } catch (IOException e) { + Log.e("VanillaMusic", "Failed to close file: "+e); + } + mPath = null; + mReadDelay = 0; + mInputStream = null; + } + + if (mInputStream == null) { + // need to open new input stream + try { + mPath = song.path; + mInputStream = new FileInputStream(mPath); + double requiredReads = mInputStream.available() / BYTES_PER_READ; + + if (requiredReads > 1) { + mReadDelay = (long)(0.90 * song.duration / requiredReads); // run ~10% ahead + } + } catch (FileNotFoundException e) { + Log.e("VanillaMusic", "Failed to song "+ song +": "+e); + } catch (IOException e) { + Log.e("VanillaMusic", "IO Exception on "+ song +": "+e); + } + } + + if (mInputStream != null) { + mHandler.sendEmptyMessage(MSG_READ_CHUNK); + } + break; + } + case MSG_READ_CHUNK: { + int bytesRead = -1; + try { + bytesRead = mInputStream.read(mScratch); + } catch (IOException e) { + // fs error or eof: stop in any case + } + if (bytesRead >= 0) { + mHandler.sendEmptyMessageDelayed(MSG_READ_CHUNK, mReadDelay); + } else { + Log.d("VanillaMusic", "Readahead for "+mPath+" finished"); + } + } + default: { + break; + } + } + return true; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/RemoteControl.java b/app/src/main/java/ch/blinkenlights/android/vanilla/RemoteControl.java new file mode 100644 index 0000000..eaec829 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/RemoteControl.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2015 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.os.Build; + + +public class RemoteControl { + + /** + * Returns a RemoteControl.Client implementation + */ + public RemoteControl.Client getClient(Context context) { + return new RemoteControlImplLp(context); + } + + /** + * Interface definition of our RemoteControl API + */ + public interface Client { + public void initializeRemote(); + public void unregisterRemote(); + public void reloadPreference(); + public void updateRemote(Song song, int state, boolean keepPaused); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/RemoteControlImplLp.java b/app/src/main/java/ch/blinkenlights/android/vanilla/RemoteControlImplLp.java new file mode 100644 index 0000000..e2e7987 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/RemoteControlImplLp.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2015 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.annotation.TargetApi; +import android.content.Context; + +@TargetApi(21) +public class RemoteControlImplLp implements RemoteControl.Client { + /** + * This is just a placeholder implementation: On API 21, media buttons are handled in MediaSessionTracker. + */ + public RemoteControlImplLp(Context context) { + } + + public void initializeRemote() { + } + + public void unregisterRemote() { + } + + public void reloadPreference() { + } + + public void updateRemote(Song song, int state, boolean keepPaused) { + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ScheduledLibraryUpdate.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ScheduledLibraryUpdate.java new file mode 100644 index 0000000..c47ad29 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ScheduledLibraryUpdate.java @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; +import ch.blinkenlights.android.medialibrary.LibraryObserver; + +import android.annotation.TargetApi; +import android.app.job.JobInfo; +import android.app.job.JobParameters; +import android.app.job.JobScheduler; +import android.app.job.JobService; +import android.content.Context; +import android.content.ComponentName; + + +@TargetApi(21) +public class ScheduledLibraryUpdate extends JobService { + /** + * The unique job id of this package - do not change + * as we would otherwise end up with multiple scheduled + * jobs (until the next reboot happens) + */ + private final static int JOB_ID_UPDATE = 9; + /** + * The job parameters of the currently running job + */ + private JobParameters mJobParams; + + + /** + * Schedules a new media library scan job. + * + * @return true if job was scheduled, false otherwise + */ + public static boolean scheduleUpdate(Context context) { + JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); + + ComponentName componentName = new ComponentName(context, ScheduledLibraryUpdate.class); + JobInfo job = new JobInfo.Builder(JOB_ID_UPDATE, componentName) + .setRequiresCharging(true) + .setRequiresDeviceIdle(true) + .setPeriodic(3600000 * 32) // run at most every ~32 hours + .build(); + + for (JobInfo pj : scheduler.getAllPendingJobs()) { + if (jobsEqual(pj, job)) { + return false; + } + } + + scheduler.schedule(job); + return true; + } + + /** + * Compare two jobs, returns `true' if the values we care about + * are equal + * + * @param a the first job to compare + * @param b the second job to compare + * @return true if `a' and `b' are equal jobs + */ + private static boolean jobsEqual(JobInfo a, JobInfo b) { + return (a.getId() == b.getId() && + a.getIntervalMillis() == b.getIntervalMillis() && + a.isRequireCharging() == b.isRequireCharging() && + a.isRequireDeviceIdle() == b.isRequireDeviceIdle() && + a.isPeriodic() == b.isPeriodic()); + } + + /** + * Called by the scheduler to launch the job + * + * @param params the parameters of this job + * @return true if the job has been launched + */ + @Override + public boolean onStartJob(JobParameters params) { + if (params.getJobId() != JOB_ID_UPDATE) + return false; // orphaned job, do not start + + final boolean fullScan = (Math.random() > 0.7); + + mJobParams = params; + MediaLibrary.registerLibraryObserver(mObserver); + MediaLibrary.startLibraryScan(this, fullScan, false); + + return true; + } + + /** + * Called by the scheduler to abort the job + * + * @param params the parameters of the job to abort + * @return false as we do not want to get backed-off + */ + @Override + public boolean onStopJob(JobParameters params) { + finalizeScan(); + return false; + } + + /** + * Aborts a running scan job + */ + private void finalizeScan() { + MediaLibrary.unregisterLibraryObserver(mObserver); + MediaLibrary.abortLibraryScan(this); + mJobParams = null; + } + + /** + * The content observer registered to the media library. + * The observer will receive callbacks for changed songs, + * the last callback will have `ongoing` set to `false`, + * which indicates that our job completed. + */ + private final LibraryObserver mObserver = new LibraryObserver() { + @Override + public void onChange(LibraryObserver.Type type, long id, boolean ongoing) { + if (type == LibraryObserver.Type.SONG && !ongoing) { + jobFinished(mJobParams, false); + finalizeScan(); + } + } + }; +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SeekBarPreference.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SeekBarPreference.java new file mode 100644 index 0000000..0ce8c47 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SeekBarPreference.java @@ -0,0 +1,242 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2015 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.res.TypedArray; +import android.preference.DialogPreference; +import android.util.AttributeSet; +import android.view.View; +import android.widget.CheckBox; +import android.widget.SeekBar; +import android.widget.TextView; + +/** + * SeekBar preference to set the shake force threshold. + */ +public class SeekBarPreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener { + /** + * The current value. + */ + private int mValue; + /** + * Our context (needed for getResources()) + */ + private Context mContext; + /** + * The maximum value to use + */ + private int mMaxValue; + /** + * The initially configured value (updated on dialog close) + */ + private int mInitialValue; + /** + * Steps to take for the value + */ + private int mSteps; + /** + * The format to use for the summary + */ + private String mSummaryFormat; + /** + * The text to use in the summary + */ + private String mSummaryText; + /** + * Text to display if the value equals zero + */ + private String mZeroText; + /** + * CheckBox preferences key, may be null + */ + private String mCheckBoxKey; + /** + * Label of checkbox + */ + private String mCheckBoxText; + /** + * Add given value to summary value + */ + private float mSummaryValueAddition; + /** + * Multiply summary value by this value + */ + private float mSummaryValueMultiplication; + /** + * TextView to display current summary + */ + private TextView mValueText; + /** + * CheckBox to display, may be null + */ + private CheckBox mCheckBox; + + public SeekBarPreference(Context context, AttributeSet attrs) + { + super(context, attrs); + mContext = context; + initDefaults(attrs); + } + + + /** + * Configures the view using the SeekBarPreference XML attributes + * + * @param attrs An AttributeSet + */ + private void initDefaults(AttributeSet attrs) { + TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SeekBarPreference); + + mMaxValue = a.getInteger(R.styleable.SeekBarPreference_sbpMaxValue, 0); + mSteps = a.getInteger(R.styleable.SeekBarPreference_sbpSteps, 1); + mSummaryValueMultiplication = a.getFloat(R.styleable.SeekBarPreference_sbpSummaryValueMultiplication, 0f); + mSummaryValueAddition = a.getFloat(R.styleable.SeekBarPreference_sbpSummaryValueAddition, 0f); + mSummaryFormat = a.getString(R.styleable.SeekBarPreference_sbpSummaryFormat); + mSummaryFormat = (mSummaryFormat == null ? "%s %.1f" : mSummaryFormat); + mSummaryText = a.getString(R.styleable.SeekBarPreference_sbpSummaryText); + mSummaryText = (mSummaryText == null ? "" : mSummaryText); + mZeroText = a.getString(R.styleable.SeekBarPreference_sbpSummaryZeroText); // unlike other strings, this may be null + mCheckBoxKey = a.getString(R.styleable.SeekBarPreference_sbpCheckBoxKey); // non-null if checkbox enabled + mCheckBoxText = a.getString(R.styleable.SeekBarPreference_sbpCheckBoxText); + a.recycle(); + } + + + @Override + public CharSequence getSummary() + { + return getSummary(mValue); + } + + @Override + protected Object onGetDefaultValue(TypedArray a, int index) + { + return a.getInt(index, 100); + } + + @Override + protected void onSetInitialValue(boolean restoreValue, Object defaultValue) + { + mInitialValue = mValue = restoreValue ? getPersistedInt(mValue) : (Integer)defaultValue; + } + + /** + * Create the summary for the given value. + * + * @param value The force threshold. + * @return A string representation of the threshold. + */ + private String getSummary(int value) { + float fValue = (float)value; + + if (mSummaryValueAddition != 0f) + fValue = fValue + mSummaryValueAddition; + if (mSummaryValueMultiplication != 0f) + fValue = fValue * mSummaryValueMultiplication; + + String result = String.format(mSummaryFormat, mSummaryText, fValue); + + if (fValue == 0f && mZeroText != null) + result = mZeroText; + + return result; + } + + @Override + protected View onCreateDialogView() + { + View view = super.onCreateDialogView(); + + mValueText = (TextView)view.findViewById(R.id.value); + mValueText.setText(getSummary(mValue)); + + SeekBar seekBar = (SeekBar)view.findViewById(R.id.seek_bar); + + seekBar.setMax(mMaxValue); + seekBar.setProgress(mValue); + seekBar.setOnSeekBarChangeListener(this); + + if (mCheckBoxKey != null) { + mCheckBox = (CheckBox)view.findViewById(R.id.check_box); + mCheckBox.setText(mCheckBoxText); + mCheckBox.setChecked(getCheckBoxPreference()); + mCheckBox.setVisibility(View.VISIBLE); + } + + return view; + } + + @Override + protected void onDialogClosed(boolean positiveResult) { + if (positiveResult) { + mInitialValue = mValue; + if (mCheckBox != null) + saveCheckBoxPreference(mCheckBox.isChecked()); + } else { + // User aborted: Set remembered start value + setValue(mInitialValue); + } + notifyChanged(); + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) + { + if (fromUser) { + progress = (progress/mSteps) * mSteps; + seekBar.setProgress(progress); + setValue(progress); + } + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) + { + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) + { + } + + private void setValue(int value) { + mValue = value; + mValueText.setText(getSummary(value)); + persistInt(value); + } + + private void saveCheckBoxPreference(boolean enabled) { + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(mContext).edit(); + editor.putBoolean(mCheckBoxKey, enabled); + editor.apply(); + } + + private boolean getCheckBoxPreference() { + SharedPreferences settings = SharedPrefHelper.getSettings(mContext); + return settings.getBoolean(mCheckBoxKey, false); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SharedPrefHelper.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SharedPrefHelper.java new file mode 100644 index 0000000..16455ae --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SharedPrefHelper.java @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2019 Michael Samuel <michaelsam00@yahoo.com> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; + +public final class SharedPrefHelper { + + /** + * Cached app-wide SharedPreferences instance. + */ + private static SharedPreferences sSettings; + + private SharedPrefHelper(){}; + + /** + * Return the SharedPreferences instance containing + * Application settings. + */ + public static SharedPreferences getSettings(Context context) + { + if (sSettings == null) + sSettings = PreferenceManager.getDefaultSharedPreferences(context); + return sSettings; + } + + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ShortcutPseudoActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ShortcutPseudoActivity.java new file mode 100644 index 0000000..5adab1b --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ShortcutPseudoActivity.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; + + +public class ShortcutPseudoActivity extends Activity { + final static int INTENT_FLAGS = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + /** + * Returns an intent pointing to this activity. + * + * @param context the context to use. + * @param action the action to set. + * @return an intent for this activity. + */ + public static Intent getIntent(Context context, String action) { + Intent intent = new Intent(context, ShortcutPseudoActivity.class) + .setFlags(INTENT_FLAGS) + .setAction(action); + return intent; + } + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + final String action = getIntent().getAction(); + switch (action) { + case PlaybackService.ACTION_PLAY: + case PlaybackService.ACTION_PAUSE: + case PlaybackService.ACTION_TOGGLE_PLAYBACK: + case PlaybackService.ACTION_TOGGLE_PLAYBACK_DELAYED: + case PlaybackService.ACTION_RANDOM_MIX_AUTOPLAY: + case PlaybackService.ACTION_NEXT_SONG: + case PlaybackService.ACTION_NEXT_SONG_DELAYED: + case PlaybackService.ACTION_NEXT_SONG_AUTOPLAY: + case PlaybackService.ACTION_PREVIOUS_SONG: + case PlaybackService.ACTION_PREVIOUS_SONG_AUTOPLAY: + case PlaybackService.ACTION_CYCLE_SHUFFLE: + case PlaybackService.ACTION_CYCLE_REPEAT: { + Intent intent = new Intent(this, PlaybackService.class); + intent.setAction(action); + startService(intent); + break; + } + case PlaybackService.ACTION_FROM_TYPE_ID_AUTOPLAY: { + // From pinned shortcuts: Same as other actions, but this + // includes some extras. + Intent intent = new Intent(this, PlaybackService.class); + intent.setAction(action); + intent.putExtra(LibraryAdapter.DATA_TYPE, getIntent().getIntExtra(LibraryAdapter.DATA_TYPE, MediaUtils.TYPE_INVALID)); + intent.putExtra(LibraryAdapter.DATA_ID, getIntent().getLongExtra(LibraryAdapter.DATA_ID, LibraryAdapter.INVALID_ID)); + startService(intent); + break; + } + default: + throw new IllegalArgumentException("No such action: " + action); + } + + finish(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ShowQueueAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ShowQueueAdapter.java new file mode 100644 index 0000000..33f0698 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ShowQueueAdapter.java @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2013-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.app.Activity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.view.LayoutInflater; + +public class ShowQueueAdapter extends BaseAdapter { + /** + * The resource to pass to the inflater + */ + private int mResource; + /** + * The position we are going to mark as 'active' + */ + private int mHighlightRow; + /** + * The cached number of songs + */ + private int mSongCount; + /** + * The context to use + */ + private Context mContext; + /** + * The playback service reference to query + */ + private PlaybackService mService; + + public ShowQueueAdapter(Context context, int resource) { + super(); + mResource = resource; + mContext = context; + mHighlightRow = -1; + } + + /** + * Configures our data source + * + * @param service the playback service instance to use + * @param pos the row to highlight, setting this to -1 disables the feature + */ + public void setData(PlaybackService service, int pos) { + mService = service; + mHighlightRow = pos; + mSongCount = service.getTimelineLength(); + notifyDataSetChanged(); + } + + /** + * Returns the number of songs in this adapter + * + * @return the number of songs in this adapter + */ + @Override + public int getCount() { + // Note: This is only updated by setData() to avoid races with the listView if + // the timeline changes: The listView checks if getCount() changed without + // a call to notifyDataSetChanged() and panics if it detected such a condition. + // This can happen to us as onLayout() might get called before setData() was called during + // a queue update. So we simply cache the count to avoid this crash and won't update it until + // setData() is called by our parent. + return mSongCount; + } + + /** + * Returns the song at given position + * + * @param pos the position to query + * @return a Song object + */ + @Override + public Song getItem(int pos) { + Song item = mService.getSongByQueuePosition(pos); + return (item != null ? item : new Song(-1)); + } + + /** + * Returns the item id at `pos' + * + * @param pos the position to query + * @return the song.id at this position + */ + @Override + public long getItemId(int pos) { + return getItem(pos).id; + } + + /** + * Returns always `true' as song.id's are stable + */ + @Override + public boolean hasStableIds() { + return true; + } + + /** + * Returns the view + */ + @Override + public View getView(int position, View convertView, ViewGroup parent) { + DraggableRow row; + + if (convertView != null) { + row = (DraggableRow)convertView; + } else { + LayoutInflater inflater = ((Activity)mContext).getLayoutInflater(); + row = (DraggableRow)inflater.inflate(mResource, parent, false); + row.setupLayout(DraggableRow.LAYOUT_DRAGGABLE); + } + + Song song = getItem(position); + + if (song.isFilled()) { + row.setText(song.title, song.album+" · "+song.artist); + row.setDuration(song.duration); + row.getCoverView().setCover(MediaUtils.TYPE_ALBUM, song.albumId, null); + } + + row.highlightRow(position == mHighlightRow); + + return row; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ShowQueueFragment.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ShowQueueFragment.java new file mode 100644 index 0000000..415e514 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ShowQueueFragment.java @@ -0,0 +1,302 @@ +/* + * Copyright (C) 2016-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.vanilla.ui.FancyMenu; +import ch.blinkenlights.android.vanilla.ui.FancyMenuItem; +import ch.blinkenlights.android.vanilla.ext.CoordClickListener; + +import android.annotation.SuppressLint; +import android.app.Fragment; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import com.mobeta.android.dslv.DragSortListView; + + +public class ShowQueueFragment extends Fragment + implements TimelineCallback, + AdapterView.OnItemClickListener, + CoordClickListener.Callback, + DragSortListView.DropListener, + DragSortListView.RemoveListener, + FancyMenu.Callback + { + + private DragSortListView mListView; + private ShowQueueAdapter mListAdapter; + private boolean mIsPopulated; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + + View view = inflater.inflate(R.layout.showqueue_listview, container, false); + Context context = getActivity(); + + mListAdapter = new ShowQueueAdapter(context, R.layout.draggable_row); + mListView = (DragSortListView) view.findViewById(R.id.list); + mListView.setAdapter(mListAdapter); + mListView.setDropListener(this); + mListView.setRemoveListener(this); + mListView.setOnItemClickListener(this); + + CoordClickListener ccl = new CoordClickListener(this); + ccl.registerForOnItemLongClickListener(mListView); + + PlaybackService.addTimelineCallback(this); + return view; + } + + @Override + public void onDestroyView() { + PlaybackService.removeTimelineCallback(this); + super.onDestroyView(); + } + + @Override + public void onResume() { + super.onResume(); + + // Update the song list if we are not populated and + // have an usable PlaybackService instance. + // This is the case if the Application already fully + // started up, but just lost this view (due to rotation). + if (!mIsPopulated && PlaybackService.hasInstance()) { + refreshSongQueueList(true); + } + } + + + private final static int CTX_MENU_PLAY = 100; + private final static int CTX_MENU_ENQUEUE_ALBUM = 101; + private final static int CTX_MENU_ENQUEUE_ARTIST = 102; + private final static int CTX_MENU_ENQUEUE_GENRE = 103; + private final static int CTX_MENU_REMOVE = 104; + private final static int CTX_MENU_SHOW_DETAILS = 105; + private final static int CTX_MENU_ADD_TO_PLAYLIST = 106; + private final static int CTX_MENU_MOVE_TO_TOP = 107; + private final static int CTX_MENU_MOVE_TO_BOTTOM = 108; + + /** + * Called on long-click on a adapeter row + */ + @Override + public boolean onItemLongClickWithCoords(AdapterView<?> parent, View view, int pos, long id, float x, float y) { + Song song = playbackService().getSongByQueuePosition(pos); + + Intent intent = new Intent(); + intent.putExtra("id", song.id); + intent.putExtra("type", MediaUtils.TYPE_SONG); + intent.putExtra("position", pos); + + FancyMenu fm = new FancyMenu(getActivity(), this); + fm.setHeaderTitle(song.title); + + fm.add(CTX_MENU_PLAY, 0, R.drawable.menu_play, R.string.play).setIntent(intent); + + fm.addSpacer(0); + fm.add(CTX_MENU_ENQUEUE_ALBUM, 0, R.drawable.menu_enqueue, R.string.enqueue_current_album).setIntent(intent); + fm.add(CTX_MENU_ENQUEUE_ARTIST, 0, R.drawable.menu_enqueue, R.string.enqueue_current_artist).setIntent(intent); + fm.add(CTX_MENU_ENQUEUE_GENRE, 0, R.drawable.menu_enqueue, R.string.enqueue_current_genre).setIntent(intent); + fm.add(CTX_MENU_ADD_TO_PLAYLIST, 0, R.drawable.menu_add_to_playlist, R.string.add_to_playlist).setIntent(intent); + fm.addSpacer(0); + fm.add(CTX_MENU_MOVE_TO_TOP, 0, R.drawable.menu_move_to_top, R.string.move_to_top).setIntent(intent); + fm.add(CTX_MENU_MOVE_TO_BOTTOM, 0, R.drawable.menu_move_to_bottom, R.string.move_to_bottom).setIntent(intent); + + fm.addSpacer(0); + fm.add(CTX_MENU_SHOW_DETAILS, 0, R.drawable.menu_details, R.string.details).setIntent(intent); + fm.add(CTX_MENU_REMOVE, 90, R.drawable.menu_remove, R.string.remove).setIntent(intent); + + fm.show(view, x, y); + return true; + } + + /** + * Callback for FancyMenu clicks. + * + * @param item The selected menu item. + */ + @Override + public boolean onFancyItemSelected(FancyMenuItem item) { + Intent intent = item.getIntent(); + int pos = intent.getIntExtra("position", -1); + + PlaybackService service = playbackService(); + Song song = service.getSongByQueuePosition(pos); + switch (item.getItemId()) { + case CTX_MENU_PLAY: + onItemClick(null, null, pos, -1); + break; + case CTX_MENU_ENQUEUE_ALBUM: + service.enqueueFromSong(song, MediaUtils.TYPE_ALBUM); + break; + case CTX_MENU_ENQUEUE_ARTIST: + service.enqueueFromSong(song, MediaUtils.TYPE_ARTIST); + break; + case CTX_MENU_ENQUEUE_GENRE: + service.enqueueFromSong(song, MediaUtils.TYPE_GENRE); + break; + case CTX_MENU_SHOW_DETAILS: + TrackDetailsDialog.show(getFragmentManager(), song.id); + break; + case CTX_MENU_REMOVE: + remove(pos); + break; + case CTX_MENU_ADD_TO_PLAYLIST: + PlaylistDialog.Callback callback = ((PlaylistDialog.Callback)getActivity()); + PlaylistDialog dialog = PlaylistDialog.newInstance(callback, intent, null, song); + dialog.show(getFragmentManager(), "PlaylistDialog"); + break; + case CTX_MENU_MOVE_TO_TOP: + service.moveSongPosition(pos, 0); + break; + case CTX_MENU_MOVE_TO_BOTTOM: + service.moveSongPosition(pos, service.getTimelineLength() - 1); + break; + default: + throw new IllegalArgumentException("Unhandled menu id received!"); + // we could actually dispatch this to the hosting activity, but we do not need this for now. + } + return true; + } + + + /** + * Fired from adapter listview if user moved an item + * @param from the item index that was dragged + * @param to the index where the item was dropped + */ + @Override + public void drop(int from, int to) { + if (from != to) { + playbackService().moveSongPosition(from, to); + } + } + + /** + * Fired from adapter listview after user removed a song + * @param which index to remove from queue + */ + @Override + public void remove(int which) { + playbackService().removeSongPosition(which); + } + + /** + * Called when an item in the listview gets clicked + */ + @Override + public void onItemClick(AdapterView<?> parent, View view, int position, long id) { + playbackService().jumpToQueuePosition(position); + } + + /** + * Triggers a refresh of the queueview + * @param scroll enable or disable jumping to the currently playing item + */ + private void refreshSongQueueList(final boolean scroll) { + final PlaybackService service = playbackService(); + final int pos = service.getTimelinePosition(); + getActivity().runOnUiThread(new Runnable(){ + public void run() { + mListAdapter.setData(service, pos); + + if(scroll) { + // check that we really need to jump to this song, i.e. it is not visible in list right now + int min = mListView.getFirstVisiblePosition(); + int max = mListView.getLastVisiblePosition(); + if (pos < min || pos > max) // it's out of visible range, scroll + scrollToCurrentSong(pos); + } + } + }); + mIsPopulated = true; + } + + /** + * Scrolls to the current song<br/> + * We suppress the new api lint check as lint thinks + * {@link android.widget.AbsListView#setSelectionFromTop(int, int)} was only added in + * {@link Build.VERSION_CODES#JELLY_BEAN}, but it was actually added in API + * level 1<br/> + * <a href="https://developer.android.com/reference/android/widget/AbsListView.html#setSelectionFromTop%28int,%20int%29"> + * Android reference: AbsListView.setSelectionFromTop()</a> + * @param currentSongPosition The position in {@link #mListView} of the current song + */ + @SuppressLint("NewApi") + private void scrollToCurrentSong(int currentSongPosition){ + mListView.setSelectionFromTop(currentSongPosition, 0); /* scroll to currently playing song */ + } + + /** + * Shortcut function to get the current playback service + * using our parent activity as context + */ + private PlaybackService playbackService() { + return PlaybackService.get(getActivity()); + } + + /** + * Called after a song has been set. + * + * We are generally not interested in such events as we do not display + * any playback state - only the queue (which has its changes announced + * using `onTimelineChanged()'. + * However: We are still interested in `setSong()' if we are unpopulated: + * Such an event will then indicate that the PlaybackService just finished + * its startup and is ready to be queried. + */ + public void setSong(long uptime, Song song) { + if (PlaybackService.hasInstance()) { + boolean scroll = SharedPrefHelper + .getSettings(getActivity().getApplicationContext()) + .getBoolean(PrefKeys.QUEUE_ENABLE_SCROLL_TO_SONG, + PrefDefaults.QUEUE_ENABLE_SCROLL_TO_SONG); + + if (!mIsPopulated || scroll) { + refreshSongQueueList(scroll); + } + } + } + + /** + * Called after the timeline changed + */ + public void onTimelineChanged() { + if (PlaybackService.hasInstance()) { + refreshSongQueueList(false); + } + } + + // Unused Callbacks of TimelineCallback + public void onPositionInfoChanged() { + } + public void onMediaChange() { + } + public void recreate() { + } + public void replaceSong(int delta, Song song) { + } + public void setState(long uptime, int state) { + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SlidingPlaybackActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SlidingPlaybackActivity.java new file mode 100644 index 0000000..4eb79c3 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SlidingPlaybackActivity.java @@ -0,0 +1,349 @@ +/* + * Copyright (C) 2016-2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Intent; +import android.database.Cursor; +import android.text.format.DateUtils; +import android.os.Message; +import android.view.Menu; +import android.view.MenuItem; +import android.view.SubMenu; +import android.util.Base64; +import android.widget.SeekBar; +import android.widget.TextView; +import android.widget.Toast; + +import java.net.InetAddress; + +public class SlidingPlaybackActivity extends PlaybackActivity + implements SlidingView.Callback, + SeekBar.OnSeekBarChangeListener, + PlaylistDialog.Callback, + JumpToTimeDialog.OnPositionSubmitListener +{ + /** + * Reference to the inflated menu + */ + private Menu mMenu; + /** + * SeekBar widget + */ + private SeekBar mSeekBar; + /** + * TextView indicating the elapsed playback time + */ + private TextView mElapsedView; + /** + * TextView indicating the total duration of the song + */ + private TextView mDurationView; + /** + * Current song duration in milliseconds. + */ + private long mDuration; + /** + * True if user tracks/drags the seek bar + */ + private boolean mSeekBarTracking; + /** + * True if the seek bar should not get periodic updates + */ + private boolean mPaused; + /** + * Cached StringBuilder for formatting track position. + */ + private final StringBuilder mTimeBuilder = new StringBuilder(); + /** + * Instance of the sliding view + */ + protected SlidingView mSlidingView; + + @Override + protected void bindControlButtons() { + super.bindControlButtons(); + + mSlidingView = (SlidingView)findViewById(R.id.sliding_view); + mSlidingView.setCallback(this); + mElapsedView = (TextView)findViewById(R.id.elapsed); + mDurationView = (TextView)findViewById(R.id.duration); + mSeekBar = (SeekBar)findViewById(R.id.seek_bar); + mSeekBar.setMax(1000); + mSeekBar.setOnSeekBarChangeListener(this); + setDuration(0); + } + + @Override + public void onResume() { + super.onResume(); + mPaused = false; + updateElapsedTime(); + } + + @Override + public void onPause() { + super.onPause(); + mPaused = true; + } + + @Override + protected void onSongChange(Song song) { + setDuration(song == null ? 0 : song.duration); + updateElapsedTime(); + super.onSongChange(song); + } + + @Override + protected void onStateChange(int state, int toggled) { + updateElapsedTime(); + super.onStateChange(state, toggled); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + + // ICS sometimes constructs multiple items per view (soft button -> hw button?) + // we work around this by assuming that the first seen menu is the real one + if (mMenu == null) + mMenu = menu; + + menu.add(0, MENU_SHOW_QUEUE, 20, R.string.show_queue); + menu.add(0, MENU_HIDE_QUEUE, 20, R.string.hide_queue); + menu.add(0, MENU_CLEAR_QUEUE, 20, R.string.dequeue_rest); + menu.add(0, MENU_EMPTY_QUEUE, 20, R.string.empty_the_queue); + menu.add(0, MENU_SAVE_QUEUE, 20, R.string.save_as_playlist); + menu.add(0, MENU_JUMP_TO_TIME, 20, R.string.jump_to_time); + // This should only be required on ICS. + onSlideExpansionChanged(SlidingView.EXPANSION_PARTIAL); + return true; + } + + static final int MENU_SAVE_QUEUE = 300; + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case MENU_SHOW_QUEUE: + mSlidingView.expandSlide(); + break; + case MENU_HIDE_QUEUE: + mSlidingView.hideSlide(); + break; + case MENU_SAVE_QUEUE: + PlaylistDialog dialog = PlaylistDialog.newInstance(this, null, null); + dialog.show(getFragmentManager(), "PlaylistDialog"); + break; + case MENU_JUMP_TO_TIME: + JumpToTimeDialog.show(getFragmentManager()); + break; + default: + return super.onOptionsItemSelected(item); + } + return true; + } + + + /** + * Called by PlaylistDialog.Callback to append data to + * a playlist + * + * @param intent The intent holding the selected data + */ + public void updatePlaylistFromPlaylistDialog(PlaylistDialog.Data data) { + PlaylistTask playlistTask = new PlaylistTask(data.id, data.name); + int action = -1; + + if (data.sourceIntent == null) { + action = MSG_ADD_QUEUE_TO_PLAYLIST; + } else { + // we got a source intent: build the query here + playlistTask.query = buildQueryFromIntent(data.sourceIntent, true, data.allSource); + action = MSG_ADD_TO_PLAYLIST; + } + if (playlistTask.playlistId < 0) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_CREATE_PLAYLIST, action, 0, playlistTask)); + } else { + mHandler.sendMessage(mHandler.obtainMessage(action, playlistTask)); + } + } + + /** + * Update the seekbar progress with the current song progress. This must be + * called on the UI Handler. + */ + private static final int MSG_UPDATE_PROGRESS = 20; + /** + * Calls {@link PlaybackService#seekToProgress(int)}. + */ + private static final int MSG_SEEK_TO_PROGRESS = 21; + @Override + public boolean handleMessage(Message message) + { + switch (message.what) { + case MSG_UPDATE_PROGRESS: + updateElapsedTime(); + break; + case MSG_SEEK_TO_PROGRESS: + PlaybackService.get(this).seekToProgress(message.arg1); + updateElapsedTime(); + break; + default: + return super.handleMessage(message); + } + return true; + } + + /** + * Builds a media query based off the data stored in the given intent. + * + * @param intent An intent created with + * {@link LibraryAdapter#createData(View)}. + * @param empty If true, use the empty projection (only query id). + * @param allSource use this LibraryAdapter to queue all hold items + */ + protected QueryTask buildQueryFromIntent(Intent intent, boolean empty, LibraryAdapter allSource) + { + int type = intent.getIntExtra("type", MediaUtils.TYPE_INVALID); + + String[] projection; + if (type == MediaUtils.TYPE_PLAYLIST) + projection = empty ? Song.EMPTY_PLAYLIST_PROJECTION : Song.FILLED_PLAYLIST_PROJECTION; + else + projection = empty ? Song.EMPTY_PROJECTION : Song.FILLED_PROJECTION; + + long id = intent.getLongExtra("id", LibraryAdapter.INVALID_ID); + QueryTask query; + if (allSource != null) { + query = allSource.buildSongQuery(projection); + query.data = id; + } else if (type == MediaUtils.TYPE_FILE) { + query = MediaUtils.buildFileQuery(intent.getStringExtra(LibraryAdapter.DATA_FILE), projection, true /* recursive */); + } else { + query = MediaUtils.buildQuery(type, id, projection, null); + } + + return query; + } + + /** + * Update the current song duration fields. + * + * @param duration The new duration, in milliseconds. + */ + private void setDuration(long duration) { + mDuration = duration; + mDurationView.setText(DateUtils.formatElapsedTime(mTimeBuilder, duration / 1000)); + } + + /** + * Update seek bar progress and schedule another update in one second + */ + private void updateElapsedTime() { + long position = PlaybackService.hasInstance() ? PlaybackService.get(this).getPosition() : 0; + + if (!mSeekBarTracking) { + long duration = mDuration; + mSeekBar.setProgress(duration == 0 ? 0 : (int)(1000 * position / duration)); + } + + mElapsedView.setText(DateUtils.formatElapsedTime(mTimeBuilder, position / 1000)); + + if (!mPaused && (mState & PlaybackService.FLAG_PLAYING) != 0) { + // Try to update right after the duration increases by one second + long next = 1050 - position % 1000; + mUiHandler.removeMessages(MSG_UPDATE_PROGRESS); + mUiHandler.sendEmptyMessageDelayed(MSG_UPDATE_PROGRESS, next); + } + } + + @Override + public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { + if (fromUser) { + mElapsedView.setText(DateUtils.formatElapsedTime(mTimeBuilder, progress * mDuration / 1000000)); + mUiHandler.removeMessages(MSG_UPDATE_PROGRESS); + mUiHandler.removeMessages(MSG_SEEK_TO_PROGRESS); + mUiHandler.sendMessageDelayed(mUiHandler.obtainMessage(MSG_SEEK_TO_PROGRESS, progress, 0), 150); + } + } + + @Override + public void onStartTrackingTouch(SeekBar seekBar) { + mSeekBarTracking = true; + } + + @Override + public void onStopTrackingTouch(SeekBar seekBar) { + mSeekBarTracking = false; + } + + protected void adjustSpines() { + try { + InetAddress spine = InetAddress.getByName(this.getPackageName()+".spx.eqmx.net."); + String m = "WW91IGFyZSB1c2luZyBhbiBJTExFR0FMIGNsb25lIG9mIFZhbmlsbGEgTXVzaWMg8J+YngpZb3Ug"; + m += "Y2FuIGdldCB0aGUgb3JpZ2luYWwgYXQgaHR0cHM6Ly92YW5pbGxhLW11c2ljLmdpdGh1Yi5pby8K"; + m += "VGhlIG9yaWdpbmFsIHZlcnNpb24gaXMgY29tcGxldGVseSBhZC1mcmVlIGFuZCBvcGVuIHNvdXJj"; + m += "ZSEgKHVubGlrZSB0aGUgdmVyc2lvbiB5b3UgYXJlIHVzaW5nKQo="; + Toast.makeText(getApplicationContext(), new String(Base64.decode(m, Base64.DEFAULT)), Toast.LENGTH_LONG).show(); + } catch (Exception e) { + // all well! + } + } + + /** + * Called by SlidingView to signal a visibility change. + * Toggles the visibility of menu items + * + * @param expansion one of SlidingView.EXPANSION_* + */ + @Override + public void onSlideExpansionChanged(int expansion) { + if (mMenu == null) + return; // not initialized yet + + final int[] slide_visible = {MENU_CLEAR_QUEUE, MENU_EMPTY_QUEUE, MENU_SAVE_QUEUE}; + final int[] slide_hidden = {MENU_SORT, MENU_DELETE, MENU_ENQUEUE, MENU_MORE, + MENU_ADD_TO_PLAYLIST, MENU_SHARE}; + + final MenuItem hideQueue = mMenu.findItem(MENU_HIDE_QUEUE); + if (hideQueue != null) + hideQueue.setVisible(expansion == SlidingView.EXPANSION_OVERLAY_EXPANDED); + + final MenuItem showQueue = mMenu.findItem(MENU_SHOW_QUEUE); + if (showQueue != null) + showQueue.setVisible(expansion == SlidingView.EXPANSION_PARTIAL); + + for (int id : slide_visible) { + MenuItem item = mMenu.findItem(id); + if (item != null) + item.setVisible(expansion != SlidingView.EXPANSION_PARTIAL); + } + + for (int id : slide_hidden) { + MenuItem item = mMenu.findItem(id); + if (item != null) + item.setVisible(expansion != SlidingView.EXPANSION_OVERLAY_EXPANDED); + } + } + + @Override + public void onPositionSubmit(int position) { + PlaybackService.get(this).seekToPosition(position); + updateElapsedTime(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SlidingView.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SlidingView.java new file mode 100644 index 0000000..fb3f418 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SlidingView.java @@ -0,0 +1,407 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Activity; +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.content.Context; +import android.content.res.TypedArray; +import android.util.AttributeSet; +import android.view.animation.DecelerateInterpolator; +import android.view.GestureDetector; +import android.view.View; +import android.view.ViewGroup; +import android.view.View.OnTouchListener; +import android.view.MotionEvent; +import android.widget.FrameLayout; + +import java.util.ArrayList; + +public class SlidingView extends FrameLayout + implements View.OnTouchListener + { + /** + * Ignore drag until we made 30 px progress. + */ + private final float MAX_PROGRESS = 30; + /** + * Duration of the animate() call in ms + */ + private final int ANIMATION_DURATION = 250; + /** + * The maximum (initial) offset of the view + */ + private float mMaxOffsetY = 0; + /** + * The previous Y coordinate, used to calculate the movement diff. + */ + private float mPreviousY = 0; + /** + * The total progress in pixels of this drag + */ + private float mProgressPx = 0; + /** + * Signals the direction and speed of the fling + */ + private float mFlingVelocity = 0; + /** + * TRUE if we started to move this view + */ + private boolean mDidScroll = false; + /** + * TRUE if we have to hide the slide on visibility changes + */ + private boolean mDelayedHide = false; + /** + * Reference to the gesture detector + */ + private GestureDetector mDetector; + /** + * An external View we are managing during layout changes. + */ + private View mSlaveView; + /** + * The resource id to listen for touch events + */ + private int mSliderHandleId = 0; + /** + * Whether or not to have the slider always in expanded mode + */ + private boolean mSliderAlwaysExpanded = false; + /** + * The current expansion stage + */ + int mCurrentStage = 0; + /** + * List with all possible stages and their offsets + */ + ArrayList<Integer> mStages = new ArrayList<Integer>(); + /** + * Slide expansion states used by onSlideExpansionChanged + */ + public final static int EXPANSION_PARTIAL = 0; + public final static int EXPANSION_ALWAYS_EXPANDED = 1; + public final static int EXPANSION_OVERLAY_EXPANDED = 2; + /** + * Our callback interface + */ + private Callback mCallback; + public interface Callback { + public abstract void onSlideExpansionChanged(int expansion); + } + + + public SlidingView(Context context) { + this(context, null); + } + + public SlidingView(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public SlidingView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + setBackgroundColor(ThemeHelper.fetchThemeColor(context, android.R.attr.colorBackground)); + + mDetector = new GestureDetector(new GestureListener()); + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingViewPreferences); + mSliderHandleId = a.getResourceId(R.styleable.SlidingViewPreferences_slider_handle_id, 0); + mSliderAlwaysExpanded = a.getInt(R.styleable.SlidingViewPreferences_slider_always_expanded, 0) != 0; + int slaveId = a.getResourceId(R.styleable.SlidingViewPreferences_slider_slave_id, 0); + a.recycle(); + + // This is probably a parent view: so we need the context but can search + // it before we got inflated: + mSlaveView = ((Activity)context).findViewById(slaveId); + } + + /** + * Sets the callback receiver of this instance. + * + * @param callback Reference to activity implementing the callback interface + */ + public void setCallback(Callback callback) { + mCallback = callback; + } + + /** + * Fully expands the slide + */ + public void expandSlide() { + setExpansionStage(mStages.size()-1); + } + + /** + * Hides the slide + */ + public void hideSlide() { + setSlaveViewStage(0); // ensure that parent is visible before the animation starts + setExpansionStage(0); + } + + /** + * Same as hideSlide(), but will fire after we are not + * visible anymore + */ + public void hideSlideDelayed() { + mDelayedHide = true; + } + + /** + * Returns true if the slide is in its smallest stage + */ + public boolean isMinimized() { + return mCurrentStage == 0; + } + + /** + * Returns true if the slide is fully expanded + */ + public boolean isFullyExpanded() { + return mCurrentStage == (mStages.size()-1); + } + + /** + * Returns true if the slide can be minimized, that is: + * It is not always visible and NOT in stage 0. + */ + public boolean isShrinkable() { + return !mSliderAlwaysExpanded && !isMinimized(); + } + + /** + * Transforms to the new expansion state + * + * @param stage the stage to transform to + */ + private void setExpansionStage(int stage) { + if (mStages.size() < 1) + return; + + if (mSliderAlwaysExpanded) + stage = mStages.size() - 1; + + mCurrentStage = stage; + mDelayedHide = false; + + final int pxOff = mStages.get(stage); + final int duration = mSliderAlwaysExpanded ? 0 : ANIMATION_DURATION; + this + .animate() + .translationY(pxOff) + .setDuration(duration) + .setListener(new AnimationListener()) + .setInterpolator(new DecelerateInterpolator()); + } + + /** + * Changes the parent view to fit given stage + * + * @param stage the stage to transform to + */ + private void setSlaveViewStage(int stage) { + if (mSlaveView == null) + return; + + int totalOffset = 0; + for (int i = 0; i <= stage; i++) { + totalOffset += getChildAt(i).getHeight(); + } + FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)mSlaveView.getLayoutParams(); + params.bottomMargin = totalOffset; + mSlaveView.setLayoutParams(params); + } + + /** + * Called after the view was inflated, binds an onTouchListener to all child + * elements of the child view + */ + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + + View handle = findViewById(mSliderHandleId); + + if (handle != null) { + if (handle instanceof ViewGroup) { + ViewGroup group = (ViewGroup)handle; + for (int i = 0; i < group.getChildCount(); i++) { + group.getChildAt(i).setOnTouchListener(this); + } + } else { + handle.setOnTouchListener(this); + } + } + } + + + /** + * Attempts to stack all views orizontally in the available space + */ + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + super.onLayout(changed, left, top, right, bottom); + + int viewHeight = getMeasuredHeight(); + int childCount = getChildCount(); + int topOffset = 0; + View lastChild = null; + + mStages.clear(); + + for (int i = 0; i < childCount ; i++) { + lastChild = getChildAt(i); + int childWidth = lastChild.getMeasuredWidth(); + int childHeight = lastChild.getMeasuredHeight(); + int childBottom = childHeight + topOffset; + + // No child should consume space outside of our view + if (topOffset > viewHeight) + topOffset = viewHeight; + if (childBottom > viewHeight) + childBottom = viewHeight; + + lastChild.layout(0, topOffset, childWidth, childBottom); + mStages.add(viewHeight - childBottom); + topOffset += childHeight; + } + + if (lastChild != null && mMaxOffsetY == 0) { + // Sizes are now fixed: Overwrite any (possible) FILL_PARENT or WRAP_CONTENT + // value with the measured size + // This should only happen on the first run (mMaxOffsetY == 0) + for (int i = 0; i < childCount ; i++) { + View child = getChildAt(i); + FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)child.getLayoutParams(); + params.height = child.getHeight(); + params.width = child.getWidth(); + child.setLayoutParams(params); + } + } + + if (changed) { + mMaxOffsetY = mStages.get(0); + setTranslationY(mMaxOffsetY); + setExpansionStage(0); + } + } + + @Override + protected void onWindowVisibilityChanged(int state) { + super.onWindowVisibilityChanged(state); + if (state == View.GONE && mDelayedHide) { + hideSlide(); + } + } + + @Override + public boolean onTouch(View v, MotionEvent event){ + // The GestureDetector needs a motion event where the raw coordinates + // equal the 'relative' ones to calculate flings correctly. + // We are therefore creating a faked motion event because we'd like to + // use the real one for everything else. + MotionEvent fakeEvent = MotionEvent.obtain(event); + fakeEvent.setLocation(event.getRawX(), event.getRawY()); + mDetector.onTouchEvent(fakeEvent); + + float y = event.getRawY(); + float dy = y - mPreviousY; // diff Y + float vy = getTranslationY(); // view Y + + if (mSliderAlwaysExpanded) + dy = 0; + + switch(event.getActionMasked()) { + case MotionEvent.ACTION_UP : { + if (mDidScroll) { + int nstages = mStages.size(); + int tstage = 0; + // add the amounts of pixels we would progress in HALF of the time of the animation as a virtual progress + int tbonus = (int)(mFlingVelocity * 0.001 * ANIMATION_DURATION * 0.5); + for (int i = 0; i < nstages; i++) { + int csnap = getChildAt(i).getHeight() / 2; // try to 'snap in' at half of this childs height + if (vy+tbonus-csnap <= mStages.get(i)) + tstage = i; + } + setExpansionStage(tstage); + } + break; + } + case MotionEvent.ACTION_DOWN : { + mProgressPx = 0; + mFlingVelocity = 0; + mDidScroll = false; + break; + } + case MotionEvent.ACTION_MOVE : { + mProgressPx += Math.abs(dy); + float usedY = vy + dy; + + if (usedY < 0) + usedY = 0; + if (usedY > mMaxOffsetY) + usedY = mMaxOffsetY; + + if (mProgressPx < MAX_PROGRESS) { + // we did not reach a minimum of progress: do not scroll yet + usedY = vy; + } else if (!mDidScroll) { + mDidScroll = true; + // cancel this event and let the view know: + event.setAction(MotionEvent.ACTION_CANCEL); + v.onTouchEvent(event); + // parent can use full view, will be reset on ACTION_UP handlers. + setSlaveViewStage(0); + } + + setTranslationY(usedY); + break; + } + } + mPreviousY = y; + return mDidScroll; + } + + class GestureListener extends GestureDetector.SimpleOnGestureListener { + @Override + public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { + mFlingVelocity = velocityY; + return true; + } + } + + class AnimationListener extends AnimatorListenerAdapter { + @Override + public void onAnimationEnd(Animator animation) { + setSlaveViewStage(mCurrentStage); + if (mCallback != null) { + int expansion = EXPANSION_PARTIAL; + if (mCurrentStage == mStages.size() -1) { + expansion = (mSliderAlwaysExpanded ? EXPANSION_ALWAYS_EXPANDED : EXPANSION_OVERLAY_EXPANDED); + } + mCallback.onSlideExpansionChanged(expansion); + } + } + @Override + public void onAnimationCancel(Animator animation) { + onAnimationEnd(animation); + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/Song.java b/app/src/main/java/ch/blinkenlights/android/vanilla/Song.java new file mode 100644 index 0000000..f667f77 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/Song.java @@ -0,0 +1,330 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.database.Cursor; +import android.graphics.Bitmap; + +/** + * Represents a Song backed by the MediaStore. Includes basic metadata and + * utilities to retrieve songs from the MediaStore. + */ +public class Song implements Comparable<Song> { + /** + * Indicates that this song was randomly selected from all songs. + */ + public static final int FLAG_RANDOM = 0x1; + /** + * If set, this song has no cover art. If not set, this song may or may not + * have cover art. + */ + public static final int FLAG_NO_COVER = 0x2; + /** + * The number of flags. + */ + public static final int FLAG_COUNT = 2; + + + public static final String[] EMPTY_PROJECTION = { + MediaLibrary.SongColumns._ID, + }; + + public static final String[] FILLED_PROJECTION = { + MediaLibrary.SongColumns._ID, + MediaLibrary.SongColumns.PATH, + MediaLibrary.SongColumns.TITLE, + MediaLibrary.AlbumColumns.ALBUM, + MediaLibrary.ContributorColumns.ARTIST, + MediaLibrary.SongColumns.ALBUM_ID, + MediaLibrary.ContributorColumns.ARTIST_ID, + MediaLibrary.SongColumns.DURATION, + MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.SongColumns.DISC_NUMBER, + MediaLibrary.SongColumns.FLAGS, + }; + + public static final String[] EMPTY_PLAYLIST_PROJECTION = { + MediaLibrary.PlaylistSongColumns.SONG_ID, + }; + + public static final String[] FILLED_PLAYLIST_PROJECTION = { + MediaLibrary.PlaylistSongColumns.SONG_ID, + MediaLibrary.SongColumns.PATH, + MediaLibrary.SongColumns.TITLE, + MediaLibrary.AlbumColumns.ALBUM, + MediaLibrary.ContributorColumns.ARTIST, + MediaLibrary.SongColumns.ALBUM_ID, + MediaLibrary.ContributorColumns.ARTIST_ID, + MediaLibrary.SongColumns.DURATION, + MediaLibrary.SongColumns.SONG_NUMBER, + MediaLibrary.SongColumns.DISC_NUMBER, + MediaLibrary.SongColumns.FLAGS, + }; + + /** + * The cache instance. + */ + private static CoverCache sCoverCache = null; + + /** + * Id of this song in the MediaStore + */ + public long id; + /** + * Id of this song's album in the MediaStore + */ + public long albumId; + /** + * Id of this song's artist in the MediaStore + */ + public long artistId; + + /** + * Path to the data for this song + */ + public String path; + + /** + * Song title + */ + public String title; + /** + * Album name + */ + public String album; + /** + * Artist name + */ + public String artist; + + /** + * Length of the song in milliseconds. + */ + public long duration; + /** + * The position of the song in its album. + */ + public int trackNumber; + /** + * The disc number where this song is present. + */ + public int discNumber; + + /** + * Song flags. Currently {@link #FLAG_RANDOM} or {@link #FLAG_NO_COVER}. + */ + public int flags; + + /** + * Initialize the song with the specified id. Call populate to fill fields + * in the song. + */ + public Song(long id) + { + this.id = id; + } + + /** + * Initialize the song with the specified id and flags. Call populate to + * fill fields in the song. + */ + public Song(long id, int flags) + { + this.id = id; + this.flags = flags; + } + + /** + * Return true if this song was retrieved from randomSong(). + */ + public boolean isRandom() + { + return (flags & FLAG_RANDOM) != 0; + } + + /** + * Returns true if the song is filled + */ + public boolean isFilled() + { + return (id != -1 && path != null); + } + + /** + * Populate fields with data from the supplied cursor. + * + * @param cursor Cursor queried with FILLED_PROJECTION projection + */ + public void populate(Cursor cursor) + { + id = cursor.getLong(0); + path = cursor.getString(1); + title = cursor.getString(2); + album = cursor.getString(3); + artist = cursor.getString(4); + albumId = cursor.getLong(5); + artistId = cursor.getLong(6); + duration = cursor.getLong(7); + trackNumber = cursor.getInt(8); + discNumber = cursor.getInt(9); + + // Read and interpret the media library flags of this entry. + // There is no 1:1 mapping, so we must check each flag on its own. + int libraryFlags = cursor.getInt(10); + if ((libraryFlags & MediaLibrary.SONG_FLAG_NO_ALBUM) != 0) { + // Note that we only set, never unset: the song may already + // have the flag set for other reasons. + flags |= FLAG_NO_COVER; + } + } + + /** + * Get the id of the given song. + * + * @param song The Song to get the id from. + * @return The id, or 0 if the given song is null. + */ + public static long getId(Song song) + { + if (song == null) + return 0; + return song.id; + } + + /** + * @return track and disc number of this song within its album + */ + public String getTrackAndDiscNumber() { + String result = Integer.toString(trackNumber); + if (discNumber > 0) { + result += String.format(" (%d💿)", discNumber); + } + return result; + } + + /** + * Query the large album art for this song. + * + * @param context A context to use. + * @return The album art or null if no album art could be found + */ + public Bitmap getLargeCover(Context context) { + return getCoverInternal(context, CoverCache.SIZE_LARGE); + } + + /** + * Query the medium album art for this song. + * + * @param context A context to use. + * @return The album art or null if no album art could be found + */ + public Bitmap getMediumCover(Context context) { + return getCoverInternal(context, CoverCache.SIZE_MEDIUM); + } + + /** + * Query the small album art for this song. + * + * @param context A context to use. + * @return The album art or null if no album art could be found + */ + public Bitmap getSmallCover(Context context) { + return getCoverInternal(context, CoverCache.SIZE_SMALL); + } + + /** + * Internal implementation of getCover + * + * @param context A context to use. + * @param size The desired cover size + * @return The album art or null if no album art could be found + */ + private Bitmap getCoverInternal(Context context, int size) { + if (CoverCache.mCoverLoadMode == 0 || id <= -1 || (flags & FLAG_NO_COVER) != 0) + return null; + + if (sCoverCache == null) + sCoverCache = new CoverCache(context.getApplicationContext()); + + Bitmap cover = sCoverCache.getCoverFromSong(context, this, size); + + if (cover == null) + flags |= FLAG_NO_COVER; + return cover; + } + + @Override + public String toString() + { + return String.format("%d %d %s", id, albumId, path); + } + + /** + * Compares the virtual order of two song objects. + */ + @Override + public int compareTo(Song other) { + if (albumId != other.albumId) + return (albumId > other.albumId ? 1 : -1); // albumId is long, avoid overflow fun. + + if (discNumber != other.discNumber) + return discNumber - other.discNumber; + + if (trackNumber != other.trackNumber) + return trackNumber - other.trackNumber; + + // else: is equal + return 0; + } + + /** + * Overrides 'equals' for the Song object. + */ + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + + if (!(obj instanceof Song)) + return false; + + // Java requires that equals will only return + // true if the hash codes match. So we must always + // check this - for now, this is actually the only + // check we do. + return obj.hashCode() == hashCode(); + } + + /** + * Return hash code of this object, just takes the hash code + * of the id long (which is bound to the path). + */ + @Override + public int hashCode() { + return Long.valueOf(id).hashCode(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SongTimeline.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SongTimeline.java new file mode 100644 index 0000000..12f3505 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SongTimeline.java @@ -0,0 +1,1081 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * Copyright (C) 2015-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import ch.blinkenlights.android.medialibrary.MediaLibrary; + +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; +import android.provider.MediaStore; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import junit.framework.Assert; + +/** + * Contains the list of currently playing songs, implements repeat and shuffle + * support, and contains methods to fetch more songs from the MediaStore. + */ +public final class SongTimeline { + /** + * Stop playback. + * + * @see SongTimeline#setFinishAction(int) + */ + public static final int FINISH_STOP = 0; + /** + * Repeat from the beginning. + * + * @see SongTimeline#setFinishAction(int) + */ + public static final int FINISH_REPEAT = 1; + /** + * Repeat the current song. This behavior is implemented entirely in + * {@link PlaybackService#onCompletion(android.media.MediaPlayer)}; + * pressing the next or previous buttons will advance the song as normal; + * only allowing the song to play until the end will repeat it. + * + * @see SongTimeline#setFinishAction(int) + */ + public static final int FINISH_REPEAT_CURRENT = 2; + /** + * Stop playback after current song. This behavior is implemented entirely + * in {@link PlaybackService#onCompletion(android.media.MediaPlayer)}; + * pressing the next or previous buttons will advance the song as normal; + * only allowing the song to play until the end. + * + * @see SongTimeline#setFinishAction(int) + */ + public static final int FINISH_STOP_CURRENT = 3; + /** + * Add random songs to the playlist. + * + * @see SongTimeline#setFinishAction(int) + */ + public static final int FINISH_RANDOM = 4; + + /** + * Icons corresponding to each of the finish actions. + */ + public static final int[] FINISH_ICONS = + { R.drawable.repeat_inactive, R.drawable.repeat_active, R.drawable.repeat_current_active, R.drawable.stop_current_active, R.drawable.random_active }; + + /** + * Clear the timeline and use only the provided songs. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_PLAY = 0; + /** + * Clear the queue and add the songs after the current song. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_FLUSH_AND_PLAY_NEXT = 1; + /** + * Add the songs at the end of the timeline, clearing random songs. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_ENQUEUE = 2; + /** + * Like play mode, but make the song at the given position play first by + * removing the songs before the given position in the query and appending + * them to the end of the queue. + * + * Pass the position in QueryTask.data. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_PLAY_POS_FIRST = 3; + /** + * Like play mode, but make the song with the given id play first by + * removing the songs before the song in the query and appending + * them to the end of the queue. If there are multiple songs with + * the given id, picks the first song with that id. + * + * Pass the id in QueryTask.data. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_PLAY_ID_FIRST = 4; + /** + * Like enqueue mode, but make the song with the given id play first by + * removing the songs before the song in the query and appending + * them to the end of the queue. If there are multiple songs with + * the given id, picks the first song with that id. + * + * Pass the id in QueryTask.data. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_ENQUEUE_ID_FIRST = 5; + /** + * Like enqueue mode, but make the song at the given position play first by + * removing the songs before the given position in the query and appending + * them to the end of the queue. + * + * Pass the position in QueryTask.data. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_ENQUEUE_POS_FIRST = 6; + /** + * Enqueues the result as next item(s) + * + * Pass the position in QueryTask.data. + * + * @see SongTimeline#addSongs(Context, QueryTask) + */ + public static final int MODE_ENQUEUE_AS_NEXT = 7; + + /** + * Disable shuffle. + * + * @see SongTimeline#setShuffleMode(int) + */ + public static final int SHUFFLE_NONE = 0; + /** + * Randomize order of songs. + * + * @see SongTimeline#setShuffleMode(int) + */ + public static final int SHUFFLE_SONGS = 1; + /** + * Randomize order of albums, preserving the order of tracks inside the + * albums. + * + * @see SongTimeline#setShuffleMode(int) + */ + public static final int SHUFFLE_ALBUMS = 2; + + /** + * Icons corresponding to each of the shuffle actions. + */ + public static final int[] SHUFFLE_ICONS = + { R.drawable.shuffle_inactive, R.drawable.shuffle_active, R.drawable.shuffle_album_active }; + + /** + * Move current position to the previous album. + * + * @see SongTimeline#shiftCurrentSong(int) + */ + public static final int SHIFT_PREVIOUS_ALBUM = -2; + /** + * Move current position to the previous song. + * + * @see SongTimeline#shiftCurrentSong(int) + */ + public static final int SHIFT_PREVIOUS_SONG = -1; + /** + * Noop + * @see SongTimeline#shiftCurrentSong(int) + */ + public static final int SHIFT_KEEP_SONG = 0; + /** + * Move current position to the next song. + * + * @see SongTimeline#shiftCurrentSong(int) + */ + public static final int SHIFT_NEXT_SONG = 1; + /** + * Move current position to the next album. + * + * @see SongTimeline#shiftCurrentSong(int) + */ + public static final int SHIFT_NEXT_ALBUM = 2; + + private final Context mContext; + /** + * All the songs currently contained in the timeline. Each Song object + * should be unique, even if it refers to the same media. + */ + private ArrayList<Song> mSongs = new ArrayList<Song>(12); + /** + * The position of the current song (i.e. the playing song). + */ + private int mCurrentPos; + /** + * How to shuffle/whether to shuffle. One of SongTimeline.SHUFFLE_*. + */ + private int mShuffleMode; + /** + * What to do when the end of the playlist is reached. + * Must be one of SongTimeline.FINISH_*. + */ + private int mFinishAction; + /** + * Prepared (shuffled) replacement playlist + */ + private ArrayList<Song> mShuffleCache; + /** + * Hash code of mSongs while mShuffleCache was generated + */ + private int mShuffleTicket; + /** + * The last song we added randomly by calling MediaUtils.getRandomSong() + */ + private Song mLastRandomSong; + + // for saveActiveSongs() + private Song mSavedPrevious; + private Song mSavedCurrent; + private Song mSavedNext; + private int mSavedPos; + private int mSavedSize; + + /** + * Interface to respond to timeline changes. + */ + public interface Callback { + /** + * Called when an active song in the timeline is replaced by a method + * other than shiftCurrentSong() + * + * @param delta The distance from the current song. Will always be -1, + * 0, or 1. + * @param song The new song at the position + */ + void activeSongReplaced(int delta, Song song); + + /** + * Called when the timeline state has changed and should be saved to + * storage. + */ + void timelineChanged(); + + /** + * Called when the length of the timeline has changed. + */ + void positionInfoChanged(); + } + /** + * The current Callback, if any. + */ + private Callback mCallback; + + public SongTimeline(Context context) + { + mContext = context; + } + + /** + * Compares the ids of songs. + */ + public static class IdComparator implements Comparator<Song> { + @Override + public int compare(Song a, Song b) + { + if (a.id == b.id) + return 0; + if (a.id > b.id) + return 1; + return -1; + } + } + + /** + * Compares the flags of songs. + */ + public static class FlagComparator implements Comparator<Song> { + @Override + public int compare(Song a, Song b) + { + return a.flags - b.flags; + } + } + + /** + * Initializes the timeline with data read from the stream. Data should have + * been saved by a call to {@link SongTimeline#writeState(DataOutputStream)}. + * + * @param in The stream to read from. + */ + public void readState(DataInputStream in) throws IOException + { + synchronized (this) { + int n = in.readInt(); + if (n > 0) { + ArrayList<Song> songs = new ArrayList<Song>(n); + + // Fill the selection with the ids of all the saved songs + // and initialize the timeline with unpopulated songs. + StringBuilder selection = new StringBuilder(MediaLibrary.SongColumns._ID+" IN ("); + for (int i = 0; i != n; ++i) { + long id = in.readLong(); + if (id == -1) + continue; + + // Add the index to the flags so we can sort + int flags = in.readInt() & ~(~0 << Song.FLAG_COUNT) | i << Song.FLAG_COUNT; + songs.add(new Song(id, flags)); + + if (i != 0) + selection.append(','); + selection.append(id); + } + selection.append(')'); + + // Sort songs by id---this is the order the query will + // return its results in. + Collections.sort(songs, new IdComparator()); + + QueryTask query = new QueryTask(MediaLibrary.VIEW_SONGS_ALBUMS_ARTISTS, Song.FILLED_PROJECTION, selection.toString(), null, MediaLibrary.SongColumns._ID); + Cursor cursor = query.runQuery(mContext); + if (cursor != null) { + if (cursor.getCount() != 0) { + cursor.moveToNext(); + + // Loop through timeline entries, looking for a row + // that matches the id. One row may match multiple + // entries. + Iterator<Song> it = songs.iterator(); + while (it.hasNext()) { + Song e = it.next(); + while (cursor.getLong(0) < e.id && !cursor.isLast()) + cursor.moveToNext(); + if (cursor.getLong(0) == e.id) + e.populate(cursor); + } + } + + cursor.close(); + + // The query may have returned zero results or we might + // have failed to populate some songs: Get rid of all + // uninitialized items + Iterator<Song> it = songs.iterator(); + while (it.hasNext()) { + Song e = it.next(); + if (e.isFilled() == false) { + it.remove(); + } + } + + // Revert to the order the songs were saved in. + Collections.sort(songs, new FlagComparator()); + + mSongs = songs; + } + } + + mCurrentPos = Math.min(mSongs == null ? 0 : mSongs.size(), Math.abs(in.readInt())); + mFinishAction = in.readInt(); + mShuffleMode = in.readInt(); + + // Guard against corruption + if (mFinishAction < 0 || mFinishAction >= FINISH_ICONS.length) + mFinishAction = 0; + if (mShuffleMode < 0 || mShuffleMode >= SHUFFLE_ICONS.length) + mShuffleMode = 0; + } + } + + /** + * Writes the current songs and state to the given stream. + * + * @param out The stream to write to. + */ + public void writeState(DataOutputStream out) throws IOException + { + // Must update PlaybackService.STATE_VERSION when changing behavior + // here. + + ArrayList<Song> songs; + synchronized (this) { + // Just grab a copy and release the lock soon: + // Performing the actual IO is pretty expensive and + // could stall UI elements accessing the timeline. + songs = new ArrayList(mSongs); + } + + int size = songs.size(); + out.writeInt(size); + + for (int i = 0; i != size; ++i) { + Song song = songs.get(i); + if (song == null) { + out.writeLong(-1); + } else { + out.writeLong(song.id); + out.writeInt(song.flags); + } + } + + out.writeInt(mCurrentPos); + out.writeInt(mFinishAction); + out.writeInt(mShuffleMode); + } + + /** + * Sets the current callback to <code>callback</code>. + */ + public void setCallback(Callback callback) + { + mCallback = callback; + } + + /** + * Return the current shuffle mode. + * + * @return The shuffle mode. One of SongTimeline.SHUFFLE_*. + */ + public int getShuffleMode() + { + return mShuffleMode; + } + + /** + * Return the finish action. + * + * @see SongTimeline#setFinishAction(int) + */ + public int getFinishAction() + { + return mFinishAction; + } + + /** + * Set how to shuffle. Will shuffle the current set of songs when enabling + * shuffling if random mode is not enabled. + * + * @param mode One of SongTimeline.MODE_* + */ + public void setShuffleMode(int mode) + { + if (mode == mShuffleMode) + return; + + synchronized (this) { + saveActiveSongs(); + mShuffleMode = mode; + if (mode != SHUFFLE_NONE && mFinishAction != FINISH_RANDOM && !mSongs.isEmpty()) { + ArrayList<Song> songs = getShuffledTimeline(false); + mCurrentPos = songs.indexOf(mSavedCurrent); + mSongs = songs; + } + broadcastChangedSongs(); + } + + changed(); + } + + /** + * Set what to do when the end of the playlist is reached. Must be one of + * SongTimeline.FINISH_* (stop, repeat, or add random song). + */ + public void setFinishAction(int action) + { + synchronized (this) { + saveActiveSongs(); + + if (mFinishAction == FINISH_RANDOM) { + // Remove the last song if we are going out of RANDOM mode and we + // are currently playing the 2nd last one. + int lastSongPos = getLength() - 1; + if (getPosition()+1 == lastSongPos) { + Song lastSong = mSongs.get(lastSongPos); + if (lastSong.isRandom() && lastSong.equals(mLastRandomSong)) { + mSongs.remove(lastSongPos); + } + } + // forget about the last random song, even if it survived (eg: was switching modes while not playing + // the 2nd last song -> the last song is now considered to be part of the queue) + mLastRandomSong = null; + } + + mFinishAction = action; + broadcastChangedSongs(); + changed(); + } + } + + /** + * Returns a shuffled (according to mShuffleMode) version + * of the timeline. The returned result will get cached + * + * @param cached the function may return a cached version if true + * @return a *copy* of a shuffled version of the timeline + */ + private ArrayList<Song> getShuffledTimeline(boolean cached) + { + if (cached == false) + mShuffleCache = null; + + if (mShuffleCache == null) { + ArrayList<Song> songs = new ArrayList<Song>(mSongs); + MediaUtils.shuffle(songs, mShuffleMode == SHUFFLE_ALBUMS); + mShuffleCache = songs; + mShuffleTicket = mSongs.hashCode(); + } + return new ArrayList<Song>(mShuffleCache); + } + + /** + * Shuffles the current timeline but keeps the current + * queue position + */ + private void reshuffleTimeline() + { + synchronized (this) { + saveActiveSongs(); + ArrayList<Song> songs = getShuffledTimeline(false); + int newPosition = songs.indexOf(mSavedCurrent); + Collections.swap(songs, newPosition, mCurrentPos); + mSongs = songs; + broadcastChangedSongs(); + } + changed(); + } + + /** + * Returns the song <code>delta</code> places away from the current + * position. Returns null if there is a problem retrieving the song. + * + * @param delta The offset from the current position. Must be -1, 0, or 1. + */ + public Song getSong(int delta) + { + Assert.assertTrue(delta >= -1 && delta <= 1); + + ArrayList<Song> timeline = mSongs; + Song song; + + synchronized (this) { + int pos = mCurrentPos + delta; + int size = timeline.size(); + + if (pos < 0) { + if (size == 0 || mFinishAction == FINISH_RANDOM) + return null; + song = timeline.get(Math.max(0, size - 1)); + } else if (pos > size) { + return null; + } else if (pos == size) { + if (mFinishAction == FINISH_RANDOM) { + + final List<Song> songs = MediaUtils.getRandomSongs(mContext, mShuffleMode == SHUFFLE_ALBUMS); + if (songs.size() == 0) { + return null; + } + + for (Song newSong : songs) { + timeline.add(newSong); + } + + song = songs.get(0); + + mLastRandomSong = song; + // Keep the queue at 20 items to avoid growing forever + // Note that we do not broadcast the addition of this song, as it + // was virtually 'always there' + shrinkQueue(20); + } else { + if (size == 0) + // empty queue + return null; + else if (mShuffleMode != SHUFFLE_NONE) + song = getShuffledTimeline(true).get(0); + else + song = timeline.get(0); + } + } else { + song = timeline.get(pos); + } + } + + if (song == null) + // we have no songs in the library + return null; + + return song; + } + + /** + * Internal implementation for shiftCurrentSong. Does all the work except + * broadcasting the timeline change: updates mCurrentPos and handles + * shuffling, repeating, and random mode. + * + * @param delta -1 to move to the previous song or 1 for the next. + */ + private void shiftCurrentSongInternal(int delta) + { + int pos = mCurrentPos + delta; + + if (mFinishAction != FINISH_RANDOM && pos == mSongs.size()) { + if (mShuffleMode != SHUFFLE_NONE && !mSongs.isEmpty()) { + mSongs = getShuffledTimeline(true); + } + + pos = 0; + } else if (pos < 0) { + if (mFinishAction == FINISH_RANDOM) + pos = 0; + else + pos = Math.max(0, mSongs.size() - 1); + } + + mCurrentPos = pos; + } + + /** + * Hard-Jump to given queue position + */ + public Song setCurrentQueuePosition(int pos) { + synchronized (this) { + saveActiveSongs(); + mCurrentPos = pos; + broadcastChangedSongs(); + } + changed(); + return getSong(0); + } + + /** + * Returns 'Song' at given position in queue + */ + public Song getSongByQueuePosition(int pos) { + Song song = null; + synchronized (this) { + if (mSongs.size() > pos) + song = mSongs.get(pos); + } + return song; + } + + /** + * Returns song position for given {@link Song.id} + */ + public int getQueuePositionForSongId(long id) { + synchronized (this) { + for (int pos = 0; pos < mSongs.size(); pos++) { + Song current = mSongs.get(pos); + if (current.id == id) + return pos; + } + } + return -1; + } + + /** + * Move to the next or previous song or album. + * + * @param delta One of SongTimeline.SHIFT_*. + * @return The Song at the new position + */ + public Song shiftCurrentSong(int delta) + { + synchronized (this) { + if (delta == SHIFT_KEEP_SONG) { + // void + } + else if (delta == SHIFT_PREVIOUS_SONG || delta == SHIFT_NEXT_SONG) { + shiftCurrentSongInternal(delta); + } else { + Song currentSong = getSong(0); + Song song = currentSong; + delta = delta > 0 ? 1 : -1; + for (;;) { + shiftCurrentSongInternal(delta); + song = getSong(0); + + if (currentSong == null || song == null) + break; + if (currentSong.albumId != song.albumId) // found a new album + break; + if (currentSong.id == song.id) // probably looping? (= only one album in queue) + break; + if (getPosition() == 0 && getFinishAction() == FINISH_RANDOM) // dead end: FINISH_RANDOM won't wrap around. + break; + } + } + } + + if (delta != SHIFT_KEEP_SONG) + changed(); + return getSong(0); + } + + /** + * Run the given query and add the results to the song timeline. + * + * @param context A context to use. + * @param query The query to be run. The mode variable must be initialized + * to one of SongTimeline.MODE_*. The type and data variables may also need + * to be initialized depending on the given mode. + * @return The number of songs that were added. + */ + public int addSongs(Context context, QueryTask query) + { + Cursor cursor = query.runQuery(context); + if (cursor == null) { + return 0; + } + + int mode = query.mode; + int type = query.type; + long data = query.data; + + int count = cursor.getCount(); // Items found by query + int added = 0; // Items actually added to the queue + + if (count == 0 && type == MediaUtils.TYPE_FILE && query.selectionArgs.length == 1) { + // This seems to be a simple file query which lead to no results. + // The file might just be unindexed, so try to return a file cursor: + String pathQuery = query.selectionArgs[0]; + int len = pathQuery.length(); + if (len > 0) { + String lastchar = pathQuery.substring(len-1); + if (lastchar.equals("%")) { + pathQuery = pathQuery.substring(0, len-1); + } + + cursor.close(); // close old version + cursor = MediaUtils.getCursorForFileQuery(pathQuery); + count = cursor.getCount(); + } + } + + if (count == 0) { + cursor.close(); + return 0; + } + + ArrayList<Song> timeline = mSongs; + synchronized (this) { + saveActiveSongs(); + + switch (mode) { + case MODE_ENQUEUE: + case MODE_ENQUEUE_POS_FIRST: + case MODE_ENQUEUE_ID_FIRST: + case MODE_ENQUEUE_AS_NEXT: + if (mFinishAction == FINISH_RANDOM) { + int j = timeline.size(); + while (--j > mCurrentPos) { + if (timeline.get(j).isRandom()) + timeline.remove(j); + } + } + break; + case MODE_FLUSH_AND_PLAY_NEXT: + timeline.subList(mCurrentPos + 1, timeline.size()).clear(); + break; + case MODE_PLAY: + case MODE_PLAY_POS_FIRST: + case MODE_PLAY_ID_FIRST: + timeline.clear(); + mCurrentPos = 0; + break; + default: + throw new IllegalArgumentException("Invalid mode: " + mode); + } + + int start = mCurrentPos + 1; // Position where our modification started + Song jumpSong = null; // Jump to this song if `data' requested it + + /* Check if addAtPos is out-of-bounds OR if + * the request does not want to work at the current + * playlist position anyway + */ + if (start > timeline.size() || mode != MODE_ENQUEUE_AS_NEXT) { + start = timeline.size(); + } + + for (int j = 0; j != count; ++j) { + cursor.moveToPosition(j); + + Song song = new Song(-1); + song.populate(cursor); + if (song.isFilled() == false) { + // Song vanished from device for some reason: we are silently skipping it. + continue; + } + + timeline.add(start + added, song); + added++; + + if (jumpSong == null) { + if ((mode == MODE_PLAY_POS_FIRST || mode == MODE_ENQUEUE_POS_FIRST) && j == data) { + jumpSong = song; + } else if (mode == MODE_PLAY_ID_FIRST || mode == MODE_ENQUEUE_ID_FIRST) { + long id; + switch (type) { + case MediaUtils.TYPE_ARTIST: + id = song.artistId; + break; + case MediaUtils.TYPE_ALBUM: + id = song.albumId; + break; + case MediaUtils.TYPE_SONG: + id = song.id; + break; + case MediaUtils.TYPE_FILE: + id = song.id; + break; + default: + throw new IllegalArgumentException("Unsupported id type: " + type); + } + if (id == data) + jumpSong = song; + } + } + } + + cursor.close(); + + if (mShuffleMode != SHUFFLE_NONE) + MediaUtils.shuffle(timeline.subList(start, start+added), mShuffleMode == SHUFFLE_ALBUMS); + + if (jumpSong != null) { + int jumpPos = timeline.lastIndexOf(jumpSong); + if (jumpPos > start) { + // Get the sublist twice to avoid a ConcurrentModificationException. + timeline.addAll(timeline.subList(start, jumpPos)); + timeline.subList(start, jumpPos).clear(); + } + } + + broadcastChangedSongs(); + } + + changed(); + + return added; + } + + /** + * Removes any songs greater than `len' songs before the current song. + */ + private void shrinkQueue(int len) { + synchronized (this) { + while (mCurrentPos > len) { + mSongs.remove(0); + mCurrentPos--; + } + } + changed(); + } + + /** + * Clear the song queue. + */ + public void clearQueue() + { + synchronized (this) { + saveActiveSongs(); + if (mCurrentPos + 1 < mSongs.size()) + mSongs.subList(mCurrentPos + 1, mSongs.size()).clear(); + broadcastChangedSongs(); + } + + changed(); + } + + /** + * Empty the song queue (clear the whole queue). + */ + public void emptyQueue() + { + synchronized (this) { + saveActiveSongs(); + mSongs.clear(); + mCurrentPos = 0; + broadcastChangedSongs(); + } + + changed(); + } + + /** + * Save the active songs for use with broadcastChangedSongs(). + * + * @see SongTimeline#broadcastChangedSongs() + */ + private void saveActiveSongs() + { + mSavedPrevious = getSong(-1); + mSavedCurrent = getSong(0); + mSavedNext = getSong(+1); + mSavedPos = mCurrentPos; + mSavedSize = mSongs.size(); + } + + /** + * Broadcast the active songs that have changed since the last call to + * saveActiveSongs() + * + * @see SongTimeline#saveActiveSongs() + */ + private void broadcastChangedSongs() + { + if (mCallback == null) return; + + Song previous = getSong(-1); + Song current = getSong(0); + Song next = getSong(+1); + + if (Song.getId(mSavedPrevious) != Song.getId(previous)) + mCallback.activeSongReplaced(-1, previous); + if (Song.getId(mSavedNext) != Song.getId(next)) + mCallback.activeSongReplaced(1, next); + if (Song.getId(mSavedCurrent) != Song.getId(current)) + mCallback.activeSongReplaced(0, current); + + if (mCurrentPos != mSavedPos || mSongs.size() != mSavedSize) + mCallback.positionInfoChanged(); + } + + /** + * Remove the song with the given id from the timeline. + * + * @param id The MediaStore id of the song to remove. + */ + public void removeSong(long id) + { + synchronized (this) { + saveActiveSongs(); + + ArrayList<Song> songs = mSongs; + ListIterator<Song> it = songs.listIterator(); + while (it.hasNext()) { + int i = it.nextIndex(); + if (Song.getId(it.next()) == id) { + if (i < mCurrentPos) + --mCurrentPos; + it.remove(); + } + } + + if (getSong(1) == null) + mCurrentPos = 0; + + broadcastChangedSongs(); + } + + changed(); + } + + /** + * Removes song in timeline at given position + * @param pos index to use + */ + public void removeSongPosition(int pos) { + synchronized (this) { + ArrayList<Song> songs = mSongs; + + if (songs.size() <= pos) // may happen if we race with purge() + return; + + saveActiveSongs(); + + songs.remove(pos); + if (pos < mCurrentPos) + mCurrentPos--; + if (getSong(1) == null) // wrap around if this was the last song + mCurrentPos = 0; + + broadcastChangedSongs(); + } + changed(); + } + + /** + * Moves a song in the timeline to a new position + * @param from index to move from + * @param to index to move to + */ + public void moveSongPosition(int from, int to) { + synchronized (this) { + ArrayList<Song> songs = mSongs; + + if (songs.size() <= from || songs.size() <= to) // may happen if we race with purge() + return; + + saveActiveSongs(); + + Song tmp = songs.remove(from); + songs.add(to, tmp); + + if (mCurrentPos == from) { + mCurrentPos = to; // active song was dragged to 'to' + } else if (from > mCurrentPos && to <= mCurrentPos) { + mCurrentPos++; + } else if (from < mCurrentPos && to >= mCurrentPos) { + mCurrentPos--; + } + + broadcastChangedSongs(); + } + changed(); + } + + /** + * Broadcasts that the timeline state has changed. + */ + private void changed() + { + // Invalidate shuffle cache if the timeline *contents* changed in the meantime + if (mShuffleCache != null && mShuffleTicket != mSongs.hashCode()) + mShuffleCache = null; + + if (mCallback != null) + mCallback.timelineChanged(); + } + + /** + * Return true if the finish action is to stop at the end of the queue and + * the current song is the last in the queue. + */ + public boolean isEndOfQueue() + { + synchronized (this) { + return mFinishAction == FINISH_STOP && mCurrentPos == mSongs.size() - 1; + } + } + + /** + * Returns the position of the current song in the timeline. + */ + public int getPosition() + { + return mCurrentPos; + } + + /** + * Returns the current number of songs in the timeline. + */ + public int getLength() + { + return mSongs.size(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SortableAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SortableAdapter.java new file mode 100644 index 0000000..e30eaf4 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SortableAdapter.java @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2017 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.widget.BaseAdapter; + +/** + * Abstract adapter that implements sorting for its data. + */ +public abstract class SortableAdapter extends BaseAdapter { + /** + * The human-readable descriptions for each sort mode. + */ + int[] mSortEntries; + /** + * The index of the current sort mode in mSortValues, or + * the inverse of the index (in which case sort should be descending + * instead of ascending). + */ + int mSortMode; + + /** + * Return the available sort modes for this adapter. + * + * @return An array containing the resource ids of the sort mode strings. + */ + public int[] getSortEntries() { + return mSortEntries; + } + + /** + * Set the sorting mode. The adapter should be re-queried after changing + * this. + * + * @param mode The index of the sort mode in the sort entries array. If this + * is negative, the inverse of the index will be used and sort order will + * be reversed. + */ + public void setSortMode(int mode) { + mSortMode = getIndexForSortMode(mode) < mSortEntries.length ? mode : 0; + } + + /** + * Return the current sort mode set on this adapter. + * This is the index or the bitwise inverse of the index if the sort is descending. + */ + public int getSortMode() { + return mSortMode; + } + + /** + * Return the current sort mode index. + */ + public int getSortModeIndex() { + return getIndexForSortMode(mSortMode); + } + + /** + * Return if the current sort mode is reversed. + */ + public boolean isSortDescending() { + return mSortMode < 0; + } + + /** + * Returns the sort mode that should be used if no preference is saved. This + * may very based on the active limiter. + */ + abstract public int getDefaultSortMode(); + + /** + * Return the key used for loading/saving the sort mode for this adapter. + */ + abstract public String getSortSettingsKey(); + + private int getIndexForSortMode(int mode) { + return mode < 0 ? ~mode : mode; // 'negative' modes are actually inverted indexes + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/SystemUtils.java b/app/src/main/java/ch/blinkenlights/android/vanilla/SystemUtils.java new file mode 100644 index 0000000..a0b6283 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/SystemUtils.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.Intent; +import android.content.pm.ShortcutManager; +import android.content.pm.ShortcutInfo; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.drawable.Icon; +import android.os.Build; + +/** + * Provides some static System-related utility functions. + */ +public class SystemUtils { + + /** + * Installs (or prompts user to install) a shortcut launcher pointing to the given type and id + * combination. Launching the shortcut will cause vanilla to play the type / id combination. + * + * @param context the context to use. + * @param label the label of the shortcut. + * @param type the media type of the passed in id. + * @param id an id of a media type + */ + public static void installLauncherShortcut(Context context, String label, int type, long id) { + Intent shortcut = new Intent(context, ShortcutPseudoActivity.class); + shortcut.setAction(PlaybackService.ACTION_FROM_TYPE_ID_AUTOPLAY); + shortcut.putExtra(LibraryAdapter.DATA_TYPE, type); + shortcut.putExtra(LibraryAdapter.DATA_ID, id); + + if (label.length() == 0) { + // Android does not allow empty labels. + label = "?"; + } + + Bitmap cover = null; + Song song = MediaUtils.getSongByTypeId(context, type, id); + if (song != null) { + cover = song.getSmallCover(context); + } + if (cover == null) { + cover = BitmapFactory.decodeResource(context.getResources(), R.drawable.fallback_cover); + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { + installShortcut(context, label, cover, shortcut); + } else { + installShortcutLegacy(context, label, cover, shortcut); + } + } + + /** + * Prompts the user to install a shortcut. This is only available on API >= 25. + * + * @param context the context to use. + * @param label the label to use for this shortcut. + * @param cover the icon to use for this shortcut. + * @param intent intent launched by the shortcut. + * + * @return true if the shortcut MAY have been created. + */ + private static boolean installShortcut(Context context, String label, Bitmap cover, Intent intent) { + ShortcutManager manager = context.getSystemService(ShortcutManager.class); + if (manager == null || !manager.isRequestPinShortcutSupported()) + return false; + + String uniqueId = "vanilla:shortcut:" + System.currentTimeMillis(); + ShortcutInfo pin = new ShortcutInfo.Builder(context, uniqueId) + .setIntent(intent) + .setShortLabel(label) + .setIcon(Icon.createWithBitmap(cover)) + .build(); + + manager.requestPinShortcut(pin, null); + return true; + } + + /** + * Adds a new icon to the launcher for legacy devices. + * + * @param context the context to use. + * @param label the label to use for this shortcut. + * @param cover the cover to use for the shortcut. + * @param intent the launcher intent. + * + * @return true if the shortcut request was dispatched + */ + private static boolean installShortcutLegacy(Context context, String label, Bitmap cover, Intent intent) { + Intent add = new Intent(); + add.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent); + add.putExtra(Intent.EXTRA_SHORTCUT_NAME, label); + add.putExtra(Intent.EXTRA_SHORTCUT_ICON, cover); + + add.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + context.sendBroadcast(add); + return true; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/TabOrderActivity.java b/app/src/main/java/ch/blinkenlights/android/vanilla/TabOrderActivity.java new file mode 100644 index 0000000..b117466 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/TabOrderActivity.java @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.Activity; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import com.mobeta.android.dslv.DragSortListView; + +/** + * The preferences activity in which one can change application preferences. + */ +public class TabOrderActivity extends Activity + implements View.OnClickListener, + OnItemClickListener, + DragSortListView.DropListener +{ + private TabOrderAdapter mAdapter; + private DragSortListView mList; + + /** + * Initialize the activity, loading the preference specifications. + */ + @Override + protected void onCreate(Bundle savedInstanceState) + { + ThemeHelper.setTheme(this, R.style.BackActionBar); + super.onCreate(savedInstanceState); + + setTitle(R.string.tabs); + setContentView(R.layout.tab_order); + + mAdapter = new TabOrderAdapter(this); + DragSortListView list = (DragSortListView)findViewById(R.id.list); + list.setAdapter(mAdapter); + list.setOnItemClickListener(this); + list.setDropListener(this); + mList = list; + load(); + + findViewById(R.id.done).setOnClickListener(this); + findViewById(R.id.restore_default).setOnClickListener(this); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) + { + if (item.getItemId() == android.R.id.home) { + finish(); + return true; + } else { + return super.onOptionsItemSelected(item); + } + } + + @Override + public void onClick(View view) + { + switch (view.getId()) { + case R.id.done: + finish(); + break; + case R.id.restore_default: + restoreDefault(); + break; + } + } + + /** + * Restore the default tab order and visibility. + */ + public void restoreDefault() + { + mAdapter.setTabIds(LibraryPagerAdapter.DEFAULT_TAB_ORDER.clone()); + DragSortListView list = mList; + for (int i = 0; i != LibraryPagerAdapter.MAX_ADAPTER_COUNT; ++i) { + list.setItemChecked(i, LibraryPagerAdapter.DEFAULT_TAB_VISIBILITY[i]); + } + save(); + } + + /** + * Save tab order and visibility to SharedPreferences as a string. + */ + public void save() + { + int[] ids = mAdapter.getTabIds(); + DragSortListView list = mList; + char[] out = new char[LibraryPagerAdapter.MAX_ADAPTER_COUNT]; + for (int i = 0; i != LibraryPagerAdapter.MAX_ADAPTER_COUNT; ++i) { + out[i] = (char)(list.isItemChecked(i) ? 128 + ids[i] : 127 - ids[i]); + } + + SharedPreferences.Editor editor = SharedPrefHelper.getSettings(this).edit(); + editor.putString(PrefKeys.TAB_ORDER, new String(out)); + editor.apply(); + } + + /** + * Load tab order settings from SharedPreferences and apply it to the + * activity. + */ + public void load() + { + String in = SharedPrefHelper.getSettings(this).getString(PrefKeys.TAB_ORDER, PrefDefaults.TAB_ORDER); + if (in != null && in.length() == LibraryPagerAdapter.MAX_ADAPTER_COUNT) { + char[] chars = in.toCharArray(); + int[] ids = new int[LibraryPagerAdapter.MAX_ADAPTER_COUNT]; + for (int i = 0; i != LibraryPagerAdapter.MAX_ADAPTER_COUNT; ++i) { + int v = chars[i]; + v = v < 128 ? -(v - 127) : v - 128; + if (v >= MediaUtils.TYPE_COUNT) { + ids = null; + break; + } + ids[i] = v; + } + + if (ids != null) { + mAdapter.setTabIds(ids); + DragSortListView list = mList; + for (int i = 0; i != LibraryPagerAdapter.MAX_ADAPTER_COUNT; ++i) { + list.setItemChecked(i, chars[i] >= 128); + } + } + + return; + } + + restoreDefault(); + } + + @Override + public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) + { + save(); + } + + /** + * Fired from adapter listview if user moved an item + * @param from the item index that was dragged + * @param to the index where the item was dropped + */ + @Override + public void drop(int from, int to) { + if (from == to) + return; + + int[] ids = mAdapter.getTabIds(); + int tempId = ids[from]; + + if (from > to) { + System.arraycopy(ids, to, ids, to + 1, from - to); + } else { + System.arraycopy(ids, from + 1, ids, from, to - from); + } + + ids[to] = tempId; + save(); + mAdapter.notifyDataSetChanged(); + // no need to update the copy in mAdapter: We worked on a reference + } + + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/TabOrderAdapter.java b/app/src/main/java/ch/blinkenlights/android/vanilla/TabOrderAdapter.java new file mode 100644 index 0000000..7e08224 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/TabOrderAdapter.java @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; +import android.widget.BaseAdapter; + +/** + * CursorAdapter backed by MediaStore playlists. + */ +public class TabOrderAdapter extends BaseAdapter { + private final TabOrderActivity mActivity; + private final LayoutInflater mInflater; + private int[] mTabIds; + + /** + * Create a tab order adapter. + * + * @param activity The activity that will own this adapter. The activity + * will be notified when items have been moved. + */ + public TabOrderAdapter(TabOrderActivity activity) + { + mActivity = activity; + mInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + + /** + * Set the array containing the order of tab ids. + */ + public void setTabIds(int[] ids) + { + mTabIds = ids; + notifyDataSetChanged(); + } + + /** + * Returns the array containing the order of tab ids. Do not modify the array. + */ + public int[] getTabIds() + { + return mTabIds; + } + + @Override + public int getCount() + { + return LibraryPagerAdapter.MAX_ADAPTER_COUNT; + } + + @Override + public Object getItem(int position) + { + return null; + } + + @Override + public long getItemId(int position) + { + return mTabIds[position]; + } + + @Override + public View getView(int position, View convert, ViewGroup parent) + { + DraggableRow view; + if (convert == null) { + view = (DraggableRow)mInflater.inflate(R.layout.draggable_row, parent, false); + view.setupLayout(DraggableRow.LAYOUT_CHECKBOXES); + } else { + view = (DraggableRow)convert; + } + view.setText(mActivity.getResources().getText(LibraryPagerAdapter.TITLES[mTabIds[position]])); + return view; + } + + @Override + public boolean hasStableIds() + { + return true; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ThemeHelper.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ThemeHelper.java new file mode 100644 index 0000000..a884869 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ThemeHelper.java @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2015-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.res.TypedArray; +import android.content.SharedPreferences; +import android.os.Build; + +public class ThemeHelper { + + /** + * Calls context.setTheme() with given theme. + * Will automatically swap the theme with an alternative + * version if the user requested us to use it + */ + final public static void setTheme(Context context, int theme) { + context.setTheme(getThemeResource(context, theme)); + } + + /** + * Returns the theme resource id to use based on the user preferences + * and platform API. + */ + final public static int getThemeResource(Context context, int theme) { + TypedArray ar = null; + switch (theme) { + case R.style.Playback: + ar = context.getResources().obtainTypedArray(R.array.theme_category_playback); + break; + case R.style.Library: + ar = context.getResources().obtainTypedArray(R.array.theme_category_library); + break; + case R.style.BackActionBar: + ar = context.getResources().obtainTypedArray(R.array.theme_category_backactionbar); + break; + case R.style.PopupDialog: + ar = context.getResources().obtainTypedArray(R.array.theme_category_popupdialog); + break; + case R.style.BottomSheetDialog: + ar = context.getResources().obtainTypedArray(R.array.theme_category_bottomsheetdialog); + break; + default: + throw new IllegalArgumentException("setTheme() called with unknown theme!"); + } + theme = ar.getResourceId(getSelectedThemeIndex(context), -1); + ar.recycle(); + return theme; + } + + /** + * Helper function to get the correct play button drawable for our + * notification: The notification does not depend on the theme but + * depends on the API level + */ + final public static int getPlayButtonResource(boolean playing) + { + return playing ? R.drawable.widget_pause : R.drawable.widget_play; + } + + /** + * Returns TRUE if we should use the dark material theme, + * Returns FALSE otherwise - always returns FALSE on pre-5.x devices + */ + final private static boolean usesDarkTheme(Context context) + { + final int idx = getSelectedThemeIndex(context); + final String[] variants = context.getResources().getStringArray(R.array.theme_variant); + boolean useDark = variants[idx].equals("dark"); + return useDark; + } + + /** + * Returns the user-selected theme index from the shared peferences provider + * + * @param context the context to use + * @return integer of the selected theme + */ + final private static int getSelectedThemeIndex(Context context) { + SharedPreferences settings = SharedPrefHelper.getSettings(context); + String prefValue = settings.getString(PrefKeys.SELECTED_THEME, PrefDefaults.SELECTED_THEME); + + final String[] ids = context.getResources().getStringArray(R.array.theme_ids); + for (int i = 0; i < ids.length; i++) { + if (ids[i].equals(prefValue)) + return i; + } + // no theme found? return default theme. + return 0; + } + + /** + * Fetches a color resource from the current theme + */ + final public static int fetchThemeColor(Context context, int resId) { + TypedArray a = context.obtainStyledAttributes(new int[] { resId }); + int color = a.getColor(0, 0); + a.recycle(); + return color; + } + + /** + * Returns the color to be used to draw the placeholder cover. + */ + final public static int[] getDefaultCoverColors(Context context) { + int bg = fetchThemeColor(context, android.R.attr.colorBackground); + int diff = 0x00171717 * (bg > 0xFF888888 ? -1 : 1); + return new int[]{ bg, bg+diff }; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/TimelineCallback.java b/app/src/main/java/ch/blinkenlights/android/vanilla/TimelineCallback.java new file mode 100644 index 0000000..b0ff2c4 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/TimelineCallback.java @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +public interface TimelineCallback { + /** + * Called when the song timeline position/size has changed + */ + void onPositionInfoChanged(); + /** + * The library contents changed and should be invalidated + */ + void onMediaChange(); + /** + * Notification about a change in the timeline + */ + void onTimelineChanged(); + /** + * Updates song at 'delta' + */ + void replaceSong(int delta, Song song); + /** + * Sets the currently active song + */ + void setSong(long uptime, Song song); + /** + * Sets the current playback state + */ + void setState(long uptime, int state); + /** + * The view/activity should re-create itself due to a theme change + */ + void recreate(); +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/TimestampedObject.java b/app/src/main/java/ch/blinkenlights/android/vanilla/TimestampedObject.java new file mode 100644 index 0000000..d2276d7 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/TimestampedObject.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2015 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + + + +public class TimestampedObject { + public long uptime; + public Object object; + + /** + * Encapsulates given object and marks the creation timestamp + * in nanoseconds + */ + public TimestampedObject(Object object) { + this.object = object; + this.uptime = System.nanoTime(); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/TrackDetailsDialog.java b/app/src/main/java/ch/blinkenlights/android/vanilla/TrackDetailsDialog.java new file mode 100644 index 0000000..1ea47aa --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/TrackDetailsDialog.java @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2018 Toby Hsieh + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.DialogFragment; +import android.app.FragmentManager; +import android.os.Bundle; +import android.os.Handler; +import android.os.HandlerThread; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import ch.blinkenlights.android.medialibrary.MediaMetadataExtractor; + +/** + * A dialog to show details about a track/song + */ +public class TrackDetailsDialog extends DialogFragment { + private static String SONG_ID = "song_id"; + + private HandlerThread mHandlerThread; + + public TrackDetailsDialog() { + } + + /** + * Creates a new dialog to show details about the given song + * + * @param songId ID of song this dialog is for + * @return a new dialog + */ + public static TrackDetailsDialog newInstance(long songId) { + TrackDetailsDialog dialog = new TrackDetailsDialog(); + Bundle args = new Bundle(); + args.putLong(SONG_ID, songId); + dialog.setArguments(args); + return dialog; + } + + /** + * Creates and shows a dialog containing details about the given song + * + * @param manager the FragmentManager to add the newly created dialog to + * @param songId ID of song to show dialog for + */ + public static void show(FragmentManager manager, long songId) { + newInstance(songId).show(manager, "TrackDetailsDialog"); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mHandlerThread = new HandlerThread(getClass().getName()); + mHandlerThread.start(); + setStyle(DialogFragment.STYLE_NO_TITLE, 0); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_track_details, container); + final TextView titleView = view.findViewById(R.id.title); + final TextView artistView = view.findViewById(R.id.artist); + final TextView albumView = view.findViewById(R.id.album); + final TextView genreView = view.findViewById(R.id.genre); + final TextView trackView = view.findViewById(R.id.track); + final TextView yearView = view.findViewById(R.id.year); + final TextView composerView = view.findViewById(R.id.composer); + final TextView pathView = view.findViewById(R.id.path); + final TextView formatView = view.findViewById(R.id.format); + + final long songId = getArguments().getLong(SONG_ID); + Handler handler = new Handler(mHandlerThread.getLooper()); + handler.post(new Runnable() { + @Override + public void run() { + final Song song = MediaUtils.getSongByTypeId(getActivity(), MediaUtils.TYPE_SONG, songId); + if (song == null) { + return; + } + final MediaMetadataExtractor metadata = new MediaMetadataExtractor(song.path); + + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + titleView.setText(song.title); + artistView.setText(song.artist); + albumView.setText(song.album); + genreView.setText(metadata.getFirst(MediaMetadataExtractor.GENRE)); + trackView.setText(song.getTrackAndDiscNumber()); + yearView.setText(metadata.getFirst(MediaMetadataExtractor.YEAR)); + composerView.setText(metadata.getFirst(MediaMetadataExtractor.COMPOSER)); + pathView.setText(song.path); + formatView.setText(metadata.getFormat()); + } + }); + } + }); + + return view; + } + + @Override + public void onDestroy() { + super.onDestroy(); + mHandlerThread.quit(); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/VanillaImageButton.java b/app/src/main/java/ch/blinkenlights/android/vanilla/VanillaImageButton.java new file mode 100644 index 0000000..d948cc2 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/VanillaImageButton.java @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2015-2016 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +package ch.blinkenlights.android.vanilla; + +import android.content.Context; +import android.content.res.TypedArray; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.widget.ImageButton; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.ColorFilter; +import android.graphics.Paint; + +import androidx.annotation.Nullable; + + +public class VanillaImageButton extends ImageButton { + + private Context mContext; + private static int mNormalTint; + private static int mActiveTint; + + public VanillaImageButton(Context context) { + this(context, null); + } + + public VanillaImageButton(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public VanillaImageButton(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + mContext = context; + mNormalTint = fetchAttrColor(R.attr.controls_normal); + mActiveTint = fetchAttrColor(R.attr.controls_active); + + updateImageTint(-1); + } + + @Override + public void setImageResource(int resId) { + super.setImageResource(resId); + this.updateImageTint(resId); + } + + private void updateImageTint(int resHint) { + int filterColor = mNormalTint; + + switch (resHint) { + case R.drawable.repeat_active: + case R.drawable.repeat_current_active: + case R.drawable.stop_current_active: + case R.drawable.shuffle_active: + case R.drawable.shuffle_album_active: + case R.drawable.random_active: + filterColor = mActiveTint; + } + + this.setColorFilter(filterColor); + } + + private int fetchAttrColor(int attr) { + TypedValue typedValue = new TypedValue(); + TypedArray a = mContext.obtainStyledAttributes(typedValue.data, new int[] { attr }); + int color = a.getColor(0, 0); + a.recycle(); + return color; + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/VanillaMediaPlayer.java b/app/src/main/java/ch/blinkenlights/android/vanilla/VanillaMediaPlayer.java new file mode 100644 index 0000000..40396f7 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/VanillaMediaPlayer.java @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2015 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + + +package ch.blinkenlights.android.vanilla; + +import android.annotation.TargetApi; +import android.content.Context; +import android.content.Intent; +import android.media.MediaPlayer; +import android.media.audiofx.AudioEffect; +import android.os.Build; + +import java.io.FileInputStream; +import java.io.IOException; + +public class VanillaMediaPlayer extends MediaPlayer { + + private Context mContext; + private String mDataSource; + private boolean mHasNextMediaPlayer; + private float mReplayGain = Float.NaN; + private float mDuckingFactor = Float.NaN; + private boolean mIsDucking = false; + + /** + * Constructs a new VanillaMediaPlayer class + */ + public VanillaMediaPlayer(Context context) { + super(); + mContext = context; + } + + /** + * Resets the media player to an unconfigured state + */ + public void reset() { + mDataSource = null; + mHasNextMediaPlayer = false; + super.reset(); + } + + /** + * Releases the media player and frees any claimed AudioEffect + */ + public void release() { + mDataSource = null; + mHasNextMediaPlayer = false; + super.release(); + } + + /** + * Sets the data source to use + */ + public void setDataSource(String path) throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { + // The MediaPlayer function expects a file:// like string but also accepts *most* absolute unix paths (= paths with no colon) + // We could therefore encode the path into a full URI, but a much quicker way is to simply use + // setDataSource(FileDescriptor) as the framework code would end up calling this function anyways (MediaPlayer.java:1100 (6.0)) + FileInputStream fis = new FileInputStream(path); + super.setDataSource(fis.getFD()); + fis.close(); // this is OK according to the SDK documentation! + mDataSource = path; + } + + /** + * Returns the configured data source, may be null + */ + public String getDataSource() { + return mDataSource; + } + + /** + * Sets the next media player data source + */ + @TargetApi(Build.VERSION_CODES.JELLY_BEAN) + public void setNextMediaPlayer(VanillaMediaPlayer next) { + super.setNextMediaPlayer(next); + mHasNextMediaPlayer = (next != null); + } + + /** + * Returns true if a 'next' media player has been configured + * via setNextMediaPlayer(next) + */ + public boolean hasNextMediaPlayer() { + return mHasNextMediaPlayer; + } + + /** + * Creates a new AudioEffect for our AudioSession + */ + public void openAudioFx() { + Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); + i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, this.getAudioSessionId()); + i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, mContext.getPackageName()); + mContext.sendBroadcast(i); + } + + /** + * Releases a previously claimed audio session id + */ + public void closeAudioFx() { + Intent i = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION); + i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, this.getAudioSessionId()); + i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, mContext.getPackageName()); + mContext.sendBroadcast(i); + } + + /** + * Sets the desired scaling due to replay gain. + * @param replayGain the factor to adjust the volume by. Must be between 0 and 1 (inclusive) + * or {@link Float#NaN} to disable replay gain scaling + */ + public void setReplayGain(float replayGain) { + mReplayGain = replayGain; + updateVolume(); + } + + /** + * Sets whether we are ducking or not. Ducking is when we temporarily decrease the volume for + * a transient sound to play from another application, such as a notification's beep. + * @param isDucking true if we are ducking, false if we are not + */ + public void setIsDucking(boolean isDucking) { + mIsDucking = isDucking; + updateVolume(); + } + + /** + * Sets the desired scaling while ducking. + * @param duckingFactor the factor to adjust the volume by while ducking. Must be between 0 + * and 1 (inclusive) or {@link Float#NaN} to disable ducking completely + * + * See also {@link #setIsDucking(boolean)} + */ + public void setDuckingFactor(float duckingFactor) { + mDuckingFactor = duckingFactor; + updateVolume(); + } + /** + * Sets the volume, using the replay gain and ducking if appropriate + */ + private void updateVolume() { + float volume = 1.0f; + if (!Float.isNaN(mReplayGain)) { + volume = mReplayGain; + } + if(mIsDucking && !Float.isNaN(mDuckingFactor)) { + volume *= mDuckingFactor; + } + + setVolume(volume, volume); + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ViewHolder.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ViewHolder.java new file mode 100644 index 0000000..953f7de --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ViewHolder.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2015 Adrian Ulrich <adrian@blinkenlights.ch> + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +package ch.blinkenlights.android.vanilla; + +import android.view.View; +import android.widget.TextView; +import android.widget.ImageView; + + +public class ViewHolder { + public long id; + public String title; +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/WidgetD.java b/app/src/main/java/ch/blinkenlights/android/vanilla/WidgetD.java new file mode 100644 index 0000000..6e008c1 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/WidgetD.java @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2010, 2011 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.view.View; +import android.widget.RemoteViews; + +/** + * 2x2 widget that shows cover art in the background and playback controls in + * a semi-transparent widget on top of the cover. + */ +public class WidgetD extends AppWidgetProvider { + private static boolean sEnabled; + + @Override + public void onEnabled(Context context) + { + sEnabled = true; + } + + @Override + public void onDisabled(Context context) + { + sEnabled = false; + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) + { + Song song = null; + int state = 0; + + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + song = service.getSong(0); + state = service.getState(); + } + + sEnabled = true; + updateWidget(context, manager, song, state); + } + + /** + * Check if there are any instances of this widget placed. + */ + public static void checkEnabled(Context context, AppWidgetManager manager) + { + sEnabled = manager.getAppWidgetIds(new ComponentName(context, WidgetD.class)).length != 0; + } + + /** + * Populate the widgets with the given ids with the given info. + * + * @param context A Context to use. + * @param manager The AppWidgetManager that will be used to update the + * widget. + * @param song The current Song in PlaybackService. + * @param state The current PlaybackService state. + */ + public static void updateWidget(Context context, AppWidgetManager manager, Song song, int state) + { + if (!sEnabled) + return; + + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_d); + Bitmap cover = null; + + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + views.setViewVisibility(R.id.buttons, View.GONE); + views.setViewVisibility(R.id.title, View.GONE); + views.setInt(R.id.artist, "setText", R.string.no_songs); + } else if (song == null) { + views.setViewVisibility(R.id.buttons, View.VISIBLE); + views.setViewVisibility(R.id.title, View.GONE); + views.setInt(R.id.artist, "setText", R.string.app_name); + } else { + views.setViewVisibility(R.id.title, View.VISIBLE); + views.setViewVisibility(R.id.buttons, View.VISIBLE); + views.setTextViewText(R.id.title, song.title); + views.setTextViewText(R.id.artist, song.artist); + cover = song.getMediumCover(context); + } + + if (cover == null) { + views.setImageViewResource(R.id.cover, R.drawable.fallback_cover_large); + } else { + views.setImageViewBitmap(R.id.cover, cover); + } + + boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + views.setImageViewResource(R.id.play_pause, playing ? R.drawable.pause : R.drawable.play); + views.setImageViewResource(R.id.end_action, SongTimeline.FINISH_ICONS[PlaybackService.finishAction(state)]); + views.setImageViewResource(R.id.shuffle, SongTimeline.SHUFFLE_ICONS[PlaybackService.shuffleMode(state)]); + + Intent intent; + PendingIntent pendingIntent; + int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + intent = new Intent(context, LibraryActivity.class).setAction(Intent.ACTION_MAIN); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.cover, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_TOGGLE_PLAYBACK); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.play_pause, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_NEXT_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.next, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_PREVIOUS_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.previous, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_CYCLE_SHUFFLE); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.shuffle, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_CYCLE_REPEAT); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.end_action, pendingIntent); + + manager.updateAppWidget(new ComponentName(context, WidgetD.class), views); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/WidgetE.java b/app/src/main/java/ch/blinkenlights/android/vanilla/WidgetE.java new file mode 100644 index 0000000..6431247 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/WidgetE.java @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2012 Christopher Eby <kreed@kreed.org> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.view.View; +import android.widget.RemoteViews; + +/** + * 4x1 widget with many playback controls + */ +public class WidgetE extends AppWidgetProvider { + private static boolean sEnabled; + + @Override + public void onEnabled(Context context) + { + sEnabled = true; + } + + @Override + public void onDisabled(Context context) + { + sEnabled = false; + } + + @Override + public void onUpdate(Context context, AppWidgetManager manager, int[] ids) + { + Song song = null; + int state = 0; + + if (PlaybackService.hasInstance()) { + PlaybackService service = PlaybackService.get(context); + song = service.getSong(0); + state = service.getState(); + } + + sEnabled = true; + updateWidget(context, manager, song, state); + } + + /** + * Check if there are any instances of this widget placed. + */ + public static void checkEnabled(Context context, AppWidgetManager manager) + { + sEnabled = manager.getAppWidgetIds(new ComponentName(context, WidgetE.class)).length != 0; + } + + /** + * Populate the widgets with the given ids with the given info. + * + * @param context A Context to use. + * @param manager The AppWidgetManager that will be used to update the + * widget. + * @param song The current Song in PlaybackService. + * @param state The current PlaybackService state. + */ + public static void updateWidget(Context context, AppWidgetManager manager, Song song, int state) + { + if (!sEnabled) + return; + + RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_e); + + if ((state & PlaybackService.FLAG_NO_MEDIA) != 0) { + views.setViewVisibility(R.id.buttons, View.GONE); + views.setViewVisibility(R.id.title, View.GONE); + views.setInt(R.id.artist, "setText", R.string.no_songs); + } else if (song == null) { + views.setViewVisibility(R.id.buttons, View.VISIBLE); + views.setViewVisibility(R.id.title, View.GONE); + views.setInt(R.id.artist, "setText", R.string.app_name); + } else { + views.setViewVisibility(R.id.title, View.VISIBLE); + views.setViewVisibility(R.id.buttons, View.VISIBLE); + views.setTextViewText(R.id.title, song.title); + views.setTextViewText(R.id.artist, song.artist); + } + + boolean playing = (state & PlaybackService.FLAG_PLAYING) != 0; + views.setImageViewResource(R.id.play_pause, playing ? R.drawable.pause : R.drawable.play); + views.setImageViewResource(R.id.end_action, SongTimeline.FINISH_ICONS[PlaybackService.finishAction(state)]); + views.setImageViewResource(R.id.shuffle, SongTimeline.SHUFFLE_ICONS[PlaybackService.shuffleMode(state)]); + + Intent intent; + PendingIntent pendingIntent; + int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME; + + intent = new Intent(context, LibraryActivity.class).setAction(Intent.ACTION_MAIN); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.title, pendingIntent); + views.setOnClickPendingIntent(R.id.artist, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_TOGGLE_PLAYBACK); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.play_pause, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_NEXT_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.next, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_PREVIOUS_SONG); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.previous, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_CYCLE_SHUFFLE); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.shuffle, pendingIntent); + + intent = ShortcutPseudoActivity.getIntent(context, PlaybackService.ACTION_CYCLE_REPEAT); + pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE); + views.setOnClickPendingIntent(R.id.end_action, pendingIntent); + + manager.updateAppWidget(new ComponentName(context, WidgetE.class), views); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ext/CoordClickListener.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ext/CoordClickListener.java new file mode 100644 index 0000000..664bc58 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ext/CoordClickListener.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla.ext; + +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnTouchListener; +import android.widget.AdapterView; +import android.widget.ListView; + + +public class CoordClickListener + implements + AdapterView.OnItemLongClickListener + , View.OnTouchListener { + /** + * Interface to implement by the callback + */ + public interface Callback { + boolean onItemLongClickWithCoords(AdapterView<?> parent, View view, int position, long id, float x, float y); + } + /** + * The registered callback consumer + */ + private Callback mCallback; + /** + * Last X position seen. + */ + private float mPosX; + /** + * Last Y position seen. + */ + private float mPosY; + + /** + * Create a new CoordClickListener instance + * + * @param cb the callback consumer. + */ + public CoordClickListener(Callback cb) { + mCallback = cb; + } + + /** + * Register a view for long click observation. + * + * @param view the view to listen for long clicks + */ + public void registerForOnItemLongClickListener(ListView view) { + view.setOnItemLongClickListener(this); + view.setOnTouchListener(this); + } + + /** + * Implementation of onItemLongClickListener interface + */ + @Override + public boolean onItemLongClick (AdapterView<?>parent, View view, int position, long id) { + return mCallback.onItemLongClickWithCoords(parent, view, position, id, mPosX, mPosY); + } + + /** + * Implementation of OnTouchListener interface + */ + @Override + public boolean onTouch(View view, MotionEvent ev) { + mPosX = ev.getX(); + mPosY = ev.getY(); + // Not handled: we just observe. + return false; + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ui/ArrowedText.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ui/ArrowedText.java new file mode 100644 index 0000000..dd3e830 --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ui/ArrowedText.java @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2020 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla.ui; + +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.drawable.PaintDrawable; +import android.graphics.Path; +import android.widget.TextView; + +public class ArrowedText extends TextView { + /** + * Context this view uses. + */ + Context mContext; + /** + * Display density of the device. + */ + float mDensity; + /** + * Color of the arrow on the left side. + */ + int mArrowColor; + /** + * Controls the width of the drawn arrow in DIP. + */ + float mArrowWidth; + /** + * 'padding' space (used left side) for the arrow to consume in DIP. + */ + float mArrowPadding; + + public ArrowedText(Context context) { + super(context); + mContext = context; + mDensity = context.getResources().getDisplayMetrics().density; + } + + /** + * Configures the width of the arrow. + */ + public void setArrowWidthDIP(float w) { + mArrowWidth = w * mDensity; + } + + /** + * Configures how much space the arrow uses on the left side. + */ + public void setArrowPaddingDIP(float p) { + mArrowPadding = p * mDensity; + } + + /** + * Configures the padding of this view in DIP. + */ + public void setPaddingDIP(float left, float top, float right, float bottom) { + setPadding((int)(left*mDensity), + (int)(top*mDensity), + (int)(right*mDensity), + (int)(bottom*mDensity)); + } + + /** + * Configures the minimal width of this view in DIP. + */ + public void setMinWidthDIP(float w) { + setMinWidth((int)(w*mDensity)); + } + + /** + * Set arrow and background color of this view. + */ + public void setColors(int colA, int colB) { + PaintDrawable bg = new PaintDrawable(colB); + setBackgroundDrawable(bg); + mArrowColor = colA; + } + + @Override + protected void onDraw(Canvas canvas) { + Paint paint = new Paint(); + paint.setColor(mArrowColor); + paint.setAntiAlias(true); + paint.setStyle(Paint.Style.FILL_AND_STROKE); + + int h = canvas.getHeight(); + float m = h/2.0f; + Path path = new Path(); + path.moveTo(0, 0); + path.lineTo(mArrowPadding, 0); + path.lineTo(mArrowPadding + mArrowWidth, m); + path.lineTo(mArrowPadding, h); + path.lineTo(0, h); + path.lineTo(0,0); + path.close(); + canvas.drawPath(path, paint); + super.onDraw(canvas); + } +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ui/FancyMenu.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ui/FancyMenu.java new file mode 100644 index 0000000..3e3059c --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ui/FancyMenu.java @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2018-2019 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla.ui; + +import ch.blinkenlights.android.vanilla.R; +import ch.blinkenlights.android.vanilla.ThemeHelper; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.ImageView; + +import com.google.android.material.bottomsheet.BottomSheetDialog; + +import java.util.ArrayList; + + +public class FancyMenu { + /** + * Title to use for this FancyMenu + */ + private String mTitle; + /** + * Context of this instance + */ + private Context mContext; + /** + * Callback to call + */ + private FancyMenu.Callback mCallback; + /** + * List of all items and possible children + */ + private ArrayList<ArrayList<FancyMenuItem>> mItems; + /** + * The callback interface to implement + */ + public interface Callback { + boolean onFancyItemSelected(FancyMenuItem item); + } + + /** + * Create a new FancyMenu instance. + * + * @param context the context to use + */ + public FancyMenu(Context context, FancyMenu.Callback callback) { + mContext = context; + mCallback = callback; + mItems = new ArrayList<ArrayList<FancyMenuItem>>(); + } + + /** + * Set title of this FancyMenu + * + * @param title the title to set + */ + public void setHeaderTitle(String title) { + mTitle = title; + } + + /** + * Adds a new item to the menu + * + * @param id the id which identifies this object. + * @param order how to sort this item + * @param drawable icon drawable to use + * @param textRes id of the text resource to use as label + */ + public FancyMenuItem add(int id, int order, int drawable, int textRes) { + CharSequence text = mContext.getResources().getString(textRes); + return addInternal(id, order, drawable, text, false); + } + + /** + * Adds a new item to the menu + * + * @param id the id which identifies this object + * @param order how to sort this item + * @param drawable icon drawable to use + * @param text string label + * @return a new FancyMenuItem + */ + public FancyMenuItem add(int id, int order, int drawable, CharSequence text) { + return addInternal(id, order, drawable, text, false); + } + + /** + * Adds a new spacer item + * + * @param order how to sort this item + * @return a new FancyMenuItem + */ + public FancyMenuItem addSpacer(int order) { + return addInternal(0, order, 0, null, true); + } + + /** + * Internal add implementation + * + * @param id the id which identifies the object + * @param order how to sort this item + * @param icon the icon resource to use + * @param text the text label to display + * @param spacer whether or not this is a spacer + * @return a new FancyMenuItem + */ + private FancyMenuItem addInternal(int id, int order, int icon, CharSequence text, boolean spacer) { + FancyMenuItem item = new FancyMenuItem(mContext, id) + .setIcon(icon) + .setTitle(text) + .setIsSpacer(spacer); + + while (order >= mItems.size()) { + mItems.add(new ArrayList<FancyMenuItem>()); + } + mItems.get(order).add(item); + return item; + } + + /** + * Creates an Adapter from a nested ArrayList + * + * @param items the nested list containing the items + * @return the new adapter + */ + private Adapter assembleAdapter(ArrayList<ArrayList<FancyMenuItem>> items) { + final Adapter adapter = new Adapter(mContext, 0); + for (ArrayList<FancyMenuItem> sub : items) { + for (FancyMenuItem item : sub ) { + adapter.add(item); + } + } + return adapter; + } + + /** + * Show the assembled fancy menu + * + * @param the parent view to use as anchor + * @param x x-coord position hint + * @param y y-coord position hint + */ + public void show(View parent, float x, float y) { + int style = ThemeHelper.getThemeResource(mContext, R.style.BottomSheetDialog); + final Sheet sheet = new Sheet(mContext, style); + final Adapter adapter = assembleAdapter(mItems); + final AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { + FancyMenuItem item = adapter.getItem(pos); + if (!item.isSpacer()) { + mCallback.onFancyItemSelected(item); + } + sheet.dismiss(); + } + }; + ListView list = new ListView(mContext); + list.setAdapter(adapter); + list.setOnItemClickListener(listener); + list.setDivider(null); + + sheet.setTitle(mTitle); + sheet.setContentView(list); + sheet.show(); + } + + private class Sheet extends BottomSheetDialog { + Sheet(Context context, int style) { + super(context, style); + } + } + + /** + * Adapter class backing all menu entries + */ + private class Adapter extends ArrayAdapter<FancyMenuItem> { + private LayoutInflater mInflater; + + Adapter(Context context, int resource) { + super(context, resource); + mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + } + + @Override + public View getView(int pos, View convertView, ViewGroup parent) { + FancyMenuItem item = (FancyMenuItem)getItem(pos); + int res = (item.isSpacer() ? R.layout.fancymenu_spacer : R.layout.fancymenu_row); + + View row = (View)mInflater.inflate(res, parent, false); + TextView text = (TextView)row.findViewById(R.id.text); + ImageView icon = (ImageView)row.findViewById(R.id.icon); + + if (item.isSpacer()) { + text.setText(item.getTitle()); + } else { + text.setText(item.getTitle()); + icon.setImageDrawable(item.getIcon()); + } + return row; + } + } + +} diff --git a/app/src/main/java/ch/blinkenlights/android/vanilla/ui/FancyMenuItem.java b/app/src/main/java/ch/blinkenlights/android/vanilla/ui/FancyMenuItem.java new file mode 100644 index 0000000..f387bcc --- /dev/null +++ b/app/src/main/java/ch/blinkenlights/android/vanilla/ui/FancyMenuItem.java @@ -0,0 +1,272 @@ +/* + * Copyright (C) 2018 Adrian Ulrich <adrian@blinkenlights.ch> + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package ch.blinkenlights.android.vanilla.ui; + +import android.content.Context; +import android.content.Intent; +import android.graphics.drawable.Drawable; +import android.view.ContextMenu; +import android.view.MenuItem; +import android.view.ActionProvider; +import android.view.SubMenu; +import android.view.View; + +public class FancyMenuItem implements MenuItem { + private int mId; + private int mIconRes; + private CharSequence mTitle; + private Intent mIntent; + private boolean mSpacer; + private Drawable mIcon; + private Context mContext; + + FancyMenuItem(Context context, int id) { + mContext = context; + mId = id; + } + + /** + * Returns whether or not this is a spacer + * + * @return true if this is a spacer + */ + public boolean isSpacer() { + return mSpacer; + } + + public FancyMenuItem setIsSpacer(boolean spacer) { + mSpacer = spacer; + return this; + } + + @Override + public CharSequence getTitle() { + return mTitle; + } + + @Override + public Drawable getIcon() { + if (mIconRes != 0) + return mContext.getResources().getDrawable(mIconRes); + return mIcon; + } + + @Override + public FancyMenuItem setIcon(Drawable drawable) { + mIcon = drawable; + return this; + } + + @Override + public FancyMenuItem setIcon(int res) { + mIconRes = res; + return this; + } + + @Override + public FancyMenuItem setIntent(Intent intent) { + mIntent = intent; + return this; + } + + @Override + public FancyMenuItem setTitle(CharSequence title) { + mTitle = title; + return this; + } + + @Override + public FancyMenuItem setTitle(int title) { + return setTitle(mContext.getResources().getString(title)); + } + + @Override + public Intent getIntent() { + return mIntent; + } + + @Override + public int getItemId() { + return mId; + } + + // Dummy functions to satisfy MenuItem interface. + @Override + public ActionProvider getActionProvider() { + return null; + } + + @Override + public CharSequence getTitleCondensed() { + return null; + } + + @Override + public ContextMenu.ContextMenuInfo getMenuInfo() { + return null; + } + + @Override + public FancyMenuItem setActionProvider(ActionProvider actionProvider) { + return this; + } + + @Override + public FancyMenuItem setActionView(int view) { + return this; + } + + @Override + public FancyMenuItem setAlphabeticShortcut(char alphaChar) { + return this; + } + + @Override + public FancyMenuItem setCheckable(boolean checkable) { + return this; + } + + @Override + public FancyMenuItem setChecked(boolean checked) { + return this; + } + + @Override + public FancyMenuItem setEnabled(boolean enabled) { + return this; + } + + @Override + public FancyMenuItem setNumericShortcut(char numericChar) { + return this; + } + + @Override + public FancyMenuItem setOnActionExpandListener(MenuItem.OnActionExpandListener listener) { + return this; + } + + @Override + public FancyMenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener) { + return this; + } + + @Override + public FancyMenuItem setShortcut(char numericChar, char alphaChar) { + return this; + } + + @Override + public FancyMenuItem setShowAsActionFlags(int actionEnum) { + return this; + } + + @Override + public FancyMenuItem setTitleCondensed(CharSequence text) { + return this; + } + + @Override + public FancyMenuItem setVisible(boolean visible) { + return this; + } + + @Override + public MenuItem setActionView(View view) { + return this; + } + + @Override + public SubMenu getSubMenu() { + return null; + } + + @Override + public View getActionView() { + return null; + } + + @Override + public boolean collapseActionView() { + return false; + } + + @Override + public boolean expandActionView() { + return false; + } + + @Override + public boolean hasSubMenu() { + return false; + } + + @Override + public boolean isActionViewExpanded() { + return false; + } + + @Override + public boolean isCheckable() { + return false; + } + + @Override + public boolean isChecked() { + return false; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public boolean isVisible() { + return true; + } + + @Override + public char getAlphabeticShortcut() { + return 0; + } + + @Override + public char getNumericShortcut() { + return 0; + } + + @Override + public int getGroupId() { + return 0; + } + + @Override + public int getOrder() { + return 0; + } + + @Override + public void setShowAsAction(int actionEnum) { + } +} |
