code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.text.TextUtils;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* Utility methods to deal with editing text through an InputConnection.
*/
public class EditingUtil {
/**
* Number of characters we want to look back in order to identify the previous word
*/
private static final int LOOKBACK_CHARACTER_NUM = 15;
// Cache Method pointers
private static boolean sMethodsInitialized;
private static Method sMethodGetSelectedText;
private static Method sMethodSetComposingRegion;
private EditingUtil() {};
/**
* Append newText to the text field represented by connection.
* The new text becomes selected.
*/
public static void appendText(InputConnection connection, String newText) {
if (connection == null) {
return;
}
// Commit the composing text
connection.finishComposingText();
// Add a space if the field already has text.
CharSequence charBeforeCursor = connection.getTextBeforeCursor(1, 0);
if (charBeforeCursor != null
&& !charBeforeCursor.equals(" ")
&& (charBeforeCursor.length() > 0)) {
newText = " " + newText;
}
connection.setComposingText(newText, 1);
}
private static int getCursorPosition(InputConnection connection) {
ExtractedText extracted = connection.getExtractedText(
new ExtractedTextRequest(), 0);
if (extracted == null) {
return -1;
}
return extracted.startOffset + extracted.selectionStart;
}
/**
* @param connection connection to the current text field.
* @param sep characters which may separate words
* @param range the range object to store the result into
* @return the word that surrounds the cursor, including up to one trailing
* separator. For example, if the field contains "he|llo world", where |
* represents the cursor, then "hello " will be returned.
*/
public static String getWordAtCursor(
InputConnection connection, String separators, Range range) {
Range r = getWordRangeAtCursor(connection, separators, range);
return (r == null) ? null : r.word;
}
/**
* Removes the word surrounding the cursor. Parameters are identical to
* getWordAtCursor.
*/
public static void deleteWordAtCursor(
InputConnection connection, String separators) {
Range range = getWordRangeAtCursor(connection, separators, null);
if (range == null) return;
connection.finishComposingText();
// Move cursor to beginning of word, to avoid crash when cursor is outside
// of valid range after deleting text.
int newCursor = getCursorPosition(connection) - range.charsBefore;
connection.setSelection(newCursor, newCursor);
connection.deleteSurroundingText(0, range.charsBefore + range.charsAfter);
}
/**
* Represents a range of text, relative to the current cursor position.
*/
public static class Range {
/** Characters before selection start */
public int charsBefore;
/**
* Characters after selection start, including one trailing word
* separator.
*/
public int charsAfter;
/** The actual characters that make up a word */
public String word;
public Range() {}
public Range(int charsBefore, int charsAfter, String word) {
if (charsBefore < 0 || charsAfter < 0) {
throw new IndexOutOfBoundsException();
}
this.charsBefore = charsBefore;
this.charsAfter = charsAfter;
this.word = word;
}
}
private static Range getWordRangeAtCursor(
InputConnection connection, String sep, Range range) {
if (connection == null || sep == null) {
return null;
}
CharSequence before = connection.getTextBeforeCursor(1000, 0);
CharSequence after = connection.getTextAfterCursor(1000, 0);
if (before == null || after == null) {
return null;
}
// Find first word separator before the cursor
int start = before.length();
while (start > 0 && !isWhitespace(before.charAt(start - 1), sep)) start--;
// Find last word separator after the cursor
int end = -1;
while (++end < after.length() && !isWhitespace(after.charAt(end), sep));
int cursor = getCursorPosition(connection);
if (start >= 0 && cursor + end <= after.length() + before.length()) {
String word = before.toString().substring(start, before.length())
+ after.toString().substring(0, end);
Range returnRange = range != null? range : new Range();
returnRange.charsBefore = before.length() - start;
returnRange.charsAfter = end;
returnRange.word = word;
return returnRange;
}
return null;
}
private static boolean isWhitespace(int code, String whitespace) {
return whitespace.contains(String.valueOf((char) code));
}
private static final Pattern spaceRegex = Pattern.compile("\\s+");
public static CharSequence getPreviousWord(InputConnection connection,
String sentenceSeperators) {
//TODO: Should fix this. This could be slow!
CharSequence prev = connection.getTextBeforeCursor(LOOKBACK_CHARACTER_NUM, 0);
if (prev == null) {
return null;
}
String[] w = spaceRegex.split(prev);
if (w.length >= 2 && w[w.length-2].length() > 0) {
char lastChar = w[w.length-2].charAt(w[w.length-2].length() -1);
if (sentenceSeperators.contains(String.valueOf(lastChar))) {
return null;
}
return w[w.length-2];
} else {
return null;
}
}
public static class SelectedWord {
public int start;
public int end;
public CharSequence word;
}
/**
* Takes a character sequence with a single character and checks if the character occurs
* in a list of word separators or is empty.
* @param singleChar A CharSequence with null, zero or one character
* @param wordSeparators A String containing the word separators
* @return true if the character is at a word boundary, false otherwise
*/
private static boolean isWordBoundary(CharSequence singleChar, String wordSeparators) {
return TextUtils.isEmpty(singleChar) || wordSeparators.contains(singleChar);
}
/**
* Checks if the cursor is inside a word or the current selection is a whole word.
* @param ic the InputConnection for accessing the text field
* @param selStart the start position of the selection within the text field
* @param selEnd the end position of the selection within the text field. This could be
* the same as selStart, if there's no selection.
* @param wordSeparators the word separator characters for the current language
* @return an object containing the text and coordinates of the selected/touching word,
* null if the selection/cursor is not marking a whole word.
*/
public static SelectedWord getWordAtCursorOrSelection(final InputConnection ic,
int selStart, int selEnd, String wordSeparators) {
if (selStart == selEnd) {
// There is just a cursor, so get the word at the cursor
EditingUtil.Range range = new EditingUtil.Range();
CharSequence touching = getWordAtCursor(ic, wordSeparators, range);
if (!TextUtils.isEmpty(touching)) {
SelectedWord selWord = new SelectedWord();
selWord.word = touching;
selWord.start = selStart - range.charsBefore;
selWord.end = selEnd + range.charsAfter;
return selWord;
}
} else {
// Is the previous character empty or a word separator? If not, return null.
CharSequence charsBefore = ic.getTextBeforeCursor(1, 0);
if (!isWordBoundary(charsBefore, wordSeparators)) {
return null;
}
// Is the next character empty or a word separator? If not, return null.
CharSequence charsAfter = ic.getTextAfterCursor(1, 0);
if (!isWordBoundary(charsAfter, wordSeparators)) {
return null;
}
// Extract the selection alone
CharSequence touching = getSelectedText(ic, selStart, selEnd);
if (TextUtils.isEmpty(touching)) return null;
// Is any part of the selection a separator? If so, return null.
final int length = touching.length();
for (int i = 0; i < length; i++) {
if (wordSeparators.contains(touching.subSequence(i, i + 1))) {
return null;
}
}
// Prepare the selected word
SelectedWord selWord = new SelectedWord();
selWord.start = selStart;
selWord.end = selEnd;
selWord.word = touching;
return selWord;
}
return null;
}
/**
* Cache method pointers for performance
*/
private static void initializeMethodsForReflection() {
try {
// These will either both exist or not, so no need for separate try/catch blocks.
// If other methods are added later, use separate try/catch blocks.
sMethodGetSelectedText = InputConnection.class.getMethod("getSelectedText", int.class);
sMethodSetComposingRegion = InputConnection.class.getMethod("setComposingRegion",
int.class, int.class);
} catch (NoSuchMethodException exc) {
// Ignore
}
sMethodsInitialized = true;
}
/**
* Returns the selected text between the selStart and selEnd positions.
*/
private static CharSequence getSelectedText(InputConnection ic, int selStart, int selEnd) {
// Use reflection, for backward compatibility
CharSequence result = null;
if (!sMethodsInitialized) {
initializeMethodsForReflection();
}
if (sMethodGetSelectedText != null) {
try {
result = (CharSequence) sMethodGetSelectedText.invoke(ic, 0);
return result;
} catch (InvocationTargetException exc) {
// Ignore
} catch (IllegalArgumentException e) {
// Ignore
} catch (IllegalAccessException e) {
// Ignore
}
}
// Reflection didn't work, try it the poor way, by moving the cursor to the start,
// getting the text after the cursor and moving the text back to selected mode.
// TODO: Verify that this works properly in conjunction with
// LatinIME#onUpdateSelection
ic.setSelection(selStart, selEnd);
result = ic.getTextAfterCursor(selEnd - selStart, 0);
ic.setSelection(selStart, selEnd);
return result;
}
/**
* Tries to set the text into composition mode if there is support for it in the framework.
*/
public static void underlineWord(InputConnection ic, SelectedWord word) {
// Use reflection, for backward compatibility
// If method not found, there's nothing we can do. It still works but just wont underline
// the word.
if (!sMethodsInitialized) {
initializeMethodsForReflection();
}
if (sMethodSetComposingRegion != null) {
try {
sMethodSetComposingRegion.invoke(ic, word.start, word.end);
} catch (InvocationTargetException exc) {
// Ignore
} catch (IllegalArgumentException e) {
// Ignore
} catch (IllegalAccessException e) {
// Ignore
}
}
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/EditingUtil.java
|
Java
|
asf20
| 13,010
|
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.AsyncTask;
import android.provider.BaseColumns;
import android.util.Log;
/**
* Stores all the pairs user types in databases. Prune the database if the size
* gets too big. Unlike AutoDictionary, it even stores the pairs that are already
* in the dictionary.
*/
public class UserBigramDictionary extends ExpandableDictionary {
private static final String TAG = "UserBigramDictionary";
/** Any pair being typed or picked */
private static final int FREQUENCY_FOR_TYPED = 2;
/** Maximum frequency for all pairs */
private static final int FREQUENCY_MAX = 127;
/**
* If this pair is typed 6 times, it would be suggested.
* Should be smaller than ContactsDictionary.FREQUENCY_FOR_CONTACTS_BIGRAM
*/
protected static final int SUGGEST_THRESHOLD = 6 * FREQUENCY_FOR_TYPED;
/** Maximum number of pairs. Pruning will start when databases goes above this number. */
private static int sMaxUserBigrams = 10000;
/**
* When it hits maximum bigram pair, it will delete until you are left with
* only (sMaxUserBigrams - sDeleteUserBigrams) pairs.
* Do not keep this number small to avoid deleting too often.
*/
private static int sDeleteUserBigrams = 1000;
/**
* Database version should increase if the database structure changes
*/
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "userbigram_dict.db";
/** Name of the words table in the database */
private static final String MAIN_TABLE_NAME = "main";
// TODO: Consume less space by using a unique id for locale instead of the whole
// 2-5 character string. (Same TODO from AutoDictionary)
private static final String MAIN_COLUMN_ID = BaseColumns._ID;
private static final String MAIN_COLUMN_WORD1 = "word1";
private static final String MAIN_COLUMN_WORD2 = "word2";
private static final String MAIN_COLUMN_LOCALE = "locale";
/** Name of the frequency table in the database */
private static final String FREQ_TABLE_NAME = "frequency";
private static final String FREQ_COLUMN_ID = BaseColumns._ID;
private static final String FREQ_COLUMN_PAIR_ID = "pair_id";
private static final String FREQ_COLUMN_FREQUENCY = "freq";
private final LatinIME mIme;
/** Locale for which this auto dictionary is storing words */
private String mLocale;
private HashSet<Bigram> mPendingWrites = new HashSet<Bigram>();
private final Object mPendingWritesLock = new Object();
private static volatile boolean sUpdatingDB = false;
private final static HashMap<String, String> sDictProjectionMap;
static {
sDictProjectionMap = new HashMap<String, String>();
sDictProjectionMap.put(MAIN_COLUMN_ID, MAIN_COLUMN_ID);
sDictProjectionMap.put(MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD1);
sDictProjectionMap.put(MAIN_COLUMN_WORD2, MAIN_COLUMN_WORD2);
sDictProjectionMap.put(MAIN_COLUMN_LOCALE, MAIN_COLUMN_LOCALE);
sDictProjectionMap.put(FREQ_COLUMN_ID, FREQ_COLUMN_ID);
sDictProjectionMap.put(FREQ_COLUMN_PAIR_ID, FREQ_COLUMN_PAIR_ID);
sDictProjectionMap.put(FREQ_COLUMN_FREQUENCY, FREQ_COLUMN_FREQUENCY);
}
private static DatabaseHelper sOpenHelper = null;
private static class Bigram {
String word1;
String word2;
int frequency;
Bigram(String word1, String word2, int frequency) {
this.word1 = word1;
this.word2 = word2;
this.frequency = frequency;
}
@Override
public boolean equals(Object bigram) {
Bigram bigram2 = (Bigram) bigram;
return (word1.equals(bigram2.word1) && word2.equals(bigram2.word2));
}
@Override
public int hashCode() {
return (word1 + " " + word2).hashCode();
}
}
public void setDatabaseMax(int maxUserBigram) {
sMaxUserBigrams = maxUserBigram;
}
public void setDatabaseDelete(int deleteUserBigram) {
sDeleteUserBigrams = deleteUserBigram;
}
public UserBigramDictionary(Context context, LatinIME ime, String locale, int dicTypeId) {
super(context, dicTypeId);
mIme = ime;
mLocale = locale;
if (sOpenHelper == null) {
sOpenHelper = new DatabaseHelper(getContext());
}
if (mLocale != null && mLocale.length() > 1) {
loadDictionary();
}
}
@Override
public void close() {
flushPendingWrites();
// Don't close the database as locale changes will require it to be reopened anyway
// Also, the database is written to somewhat frequently, so it needs to be kept alive
// throughout the life of the process.
// mOpenHelper.close();
super.close();
}
/**
* Pair will be added to the userbigram database.
*/
public int addBigrams(String word1, String word2) {
// remove caps
if (mIme != null && mIme.getCurrentWord().isAutoCapitalized()) {
word2 = Character.toLowerCase(word2.charAt(0)) + word2.substring(1);
}
int freq = super.addBigram(word1, word2, FREQUENCY_FOR_TYPED);
if (freq > FREQUENCY_MAX) freq = FREQUENCY_MAX;
synchronized (mPendingWritesLock) {
if (freq == FREQUENCY_FOR_TYPED || mPendingWrites.isEmpty()) {
mPendingWrites.add(new Bigram(word1, word2, freq));
} else {
Bigram bi = new Bigram(word1, word2, freq);
mPendingWrites.remove(bi);
mPendingWrites.add(bi);
}
}
return freq;
}
/**
* Schedules a background thread to write any pending words to the database.
*/
public void flushPendingWrites() {
synchronized (mPendingWritesLock) {
// Nothing pending? Return
if (mPendingWrites.isEmpty()) return;
// Create a background thread to write the pending entries
new UpdateDbTask(getContext(), sOpenHelper, mPendingWrites, mLocale).execute();
// Create a new map for writing new entries into while the old one is written to db
mPendingWrites = new HashSet<Bigram>();
}
}
/** Used for testing purpose **/
void waitUntilUpdateDBDone() {
synchronized (mPendingWritesLock) {
while (sUpdatingDB) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
return;
}
}
@Override
public void loadDictionaryAsync() {
// Load the words that correspond to the current input locale
Cursor cursor = query(MAIN_COLUMN_LOCALE + "=?", new String[] { mLocale });
try {
if (cursor.moveToFirst()) {
int word1Index = cursor.getColumnIndex(MAIN_COLUMN_WORD1);
int word2Index = cursor.getColumnIndex(MAIN_COLUMN_WORD2);
int frequencyIndex = cursor.getColumnIndex(FREQ_COLUMN_FREQUENCY);
while (!cursor.isAfterLast()) {
String word1 = cursor.getString(word1Index);
String word2 = cursor.getString(word2Index);
int frequency = cursor.getInt(frequencyIndex);
// Safeguard against adding really long words. Stack may overflow due
// to recursive lookup
if (word1.length() < MAX_WORD_LENGTH && word2.length() < MAX_WORD_LENGTH) {
super.setBigram(word1, word2, frequency);
}
cursor.moveToNext();
}
}
} finally {
cursor.close();
}
}
/**
* Query the database
*/
private Cursor query(String selection, String[] selectionArgs) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
// main INNER JOIN frequency ON (main._id=freq.pair_id)
qb.setTables(MAIN_TABLE_NAME + " INNER JOIN " + FREQ_TABLE_NAME + " ON ("
+ MAIN_TABLE_NAME + "." + MAIN_COLUMN_ID + "=" + FREQ_TABLE_NAME + "."
+ FREQ_COLUMN_PAIR_ID +")");
qb.setProjectionMap(sDictProjectionMap);
// Get the database and run the query
SQLiteDatabase db = sOpenHelper.getReadableDatabase();
Cursor c = qb.query(db,
new String[] { MAIN_COLUMN_WORD1, MAIN_COLUMN_WORD2, FREQ_COLUMN_FREQUENCY },
selection, selectionArgs, null, null, null);
return c;
}
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys = ON;");
db.execSQL("CREATE TABLE " + MAIN_TABLE_NAME + " ("
+ MAIN_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ MAIN_COLUMN_WORD1 + " TEXT,"
+ MAIN_COLUMN_WORD2 + " TEXT,"
+ MAIN_COLUMN_LOCALE + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + FREQ_TABLE_NAME + " ("
+ FREQ_COLUMN_ID + " INTEGER PRIMARY KEY,"
+ FREQ_COLUMN_PAIR_ID + " INTEGER,"
+ FREQ_COLUMN_FREQUENCY + " INTEGER,"
+ "FOREIGN KEY(" + FREQ_COLUMN_PAIR_ID + ") REFERENCES " + MAIN_TABLE_NAME
+ "(" + MAIN_COLUMN_ID + ")" + " ON DELETE CASCADE"
+ ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + MAIN_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FREQ_TABLE_NAME);
onCreate(db);
}
}
/**
* Async task to write pending words to the database so that it stays in sync with
* the in-memory trie.
*/
private static class UpdateDbTask extends AsyncTask<Void, Void, Void> {
private final HashSet<Bigram> mMap;
private final DatabaseHelper mDbHelper;
private final String mLocale;
public UpdateDbTask(Context context, DatabaseHelper openHelper,
HashSet<Bigram> pendingWrites, String locale) {
mMap = pendingWrites;
mLocale = locale;
mDbHelper = openHelper;
}
/** Prune any old data if the database is getting too big. */
private void checkPruneData(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys = ON;");
Cursor c = db.query(FREQ_TABLE_NAME, new String[] { FREQ_COLUMN_PAIR_ID },
null, null, null, null, null);
try {
int totalRowCount = c.getCount();
// prune out old data if we have too much data
if (totalRowCount > sMaxUserBigrams) {
int numDeleteRows = (totalRowCount - sMaxUserBigrams) + sDeleteUserBigrams;
int pairIdColumnId = c.getColumnIndex(FREQ_COLUMN_PAIR_ID);
c.moveToFirst();
int count = 0;
while (count < numDeleteRows && !c.isAfterLast()) {
String pairId = c.getString(pairIdColumnId);
// Deleting from MAIN table will delete the frequencies
// due to FOREIGN KEY .. ON DELETE CASCADE
db.delete(MAIN_TABLE_NAME, MAIN_COLUMN_ID + "=?",
new String[] { pairId });
c.moveToNext();
count++;
}
}
} finally {
c.close();
}
}
@Override
protected void onPreExecute() {
sUpdatingDB = true;
}
@Override
protected Void doInBackground(Void... v) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.execSQL("PRAGMA foreign_keys = ON;");
// Write all the entries to the db
Iterator<Bigram> iterator = mMap.iterator();
while (iterator.hasNext()) {
Bigram bi = iterator.next();
// find pair id
Cursor c = db.query(MAIN_TABLE_NAME, new String[] { MAIN_COLUMN_ID },
MAIN_COLUMN_WORD1 + "=? AND " + MAIN_COLUMN_WORD2 + "=? AND "
+ MAIN_COLUMN_LOCALE + "=?",
new String[] { bi.word1, bi.word2, mLocale }, null, null, null);
int pairId;
if (c.moveToFirst()) {
// existing pair
pairId = c.getInt(c.getColumnIndex(MAIN_COLUMN_ID));
db.delete(FREQ_TABLE_NAME, FREQ_COLUMN_PAIR_ID + "=?",
new String[] { Integer.toString(pairId) });
} else {
// new pair
Long pairIdLong = db.insert(MAIN_TABLE_NAME, null,
getContentValues(bi.word1, bi.word2, mLocale));
pairId = pairIdLong.intValue();
}
c.close();
// insert new frequency
db.insert(FREQ_TABLE_NAME, null, getFrequencyContentValues(pairId, bi.frequency));
}
checkPruneData(db);
sUpdatingDB = false;
return null;
}
private ContentValues getContentValues(String word1, String word2, String locale) {
ContentValues values = new ContentValues(3);
values.put(MAIN_COLUMN_WORD1, word1);
values.put(MAIN_COLUMN_WORD2, word2);
values.put(MAIN_COLUMN_LOCALE, locale);
return values;
}
private ContentValues getFrequencyContentValues(int pairId, int frequency) {
ContentValues values = new ContentValues(2);
values.put(FREQ_COLUMN_PAIR_ID, pairId);
values.put(FREQ_COLUMN_FREQUENCY, frequency);
return values;
}
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/UserBigramDictionary.java
|
Java
|
asf20
| 15,477
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.text.AutoText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
/**
* This class loads a dictionary and provides a list of suggestions for a given sequence of
* characters. This includes corrections and completions.
* @hide pending API Council Approval
*/
public class Suggest implements Dictionary.WordCallback {
private static String TAG = "PCKeyboard";
public static final int APPROX_MAX_WORD_LENGTH = 32;
public static final int CORRECTION_NONE = 0;
public static final int CORRECTION_BASIC = 1;
public static final int CORRECTION_FULL = 2;
public static final int CORRECTION_FULL_BIGRAM = 3;
/**
* Words that appear in both bigram and unigram data gets multiplier ranging from
* BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the frequency score from
* bigram data.
*/
public static final double BIGRAM_MULTIPLIER_MIN = 1.2;
public static final double BIGRAM_MULTIPLIER_MAX = 1.5;
/**
* Maximum possible bigram frequency. Will depend on how many bits are being used in data
* structure. Maximum bigram freqeuncy will get the BIGRAM_MULTIPLIER_MAX as the multiplier.
*/
public static final int MAXIMUM_BIGRAM_FREQUENCY = 127;
public static final int DIC_USER_TYPED = 0;
public static final int DIC_MAIN = 1;
public static final int DIC_USER = 2;
public static final int DIC_AUTO = 3;
public static final int DIC_CONTACTS = 4;
// If you add a type of dictionary, increment DIC_TYPE_LAST_ID
public static final int DIC_TYPE_LAST_ID = 4;
static final int LARGE_DICTIONARY_THRESHOLD = 200 * 1000;
private BinaryDictionary mMainDict;
private Dictionary mUserDictionary;
private Dictionary mAutoDictionary;
private Dictionary mContactsDictionary;
private Dictionary mUserBigramDictionary;
private int mPrefMaxSuggestions = 12;
private static final int PREF_MAX_BIGRAMS = 60;
private boolean mAutoTextEnabled;
private int[] mPriorities = new int[mPrefMaxSuggestions];
private int[] mBigramPriorities = new int[PREF_MAX_BIGRAMS];
// Handle predictive correction for only the first 1280 characters for performance reasons
// If we support scripts that need latin characters beyond that, we should probably use some
// kind of a sparse array or language specific list with a mapping lookup table.
// 1280 is the size of the BASE_CHARS array in ExpandableDictionary, which is a basic set of
// latin characters.
private int[] mNextLettersFrequencies = new int[1280];
private ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>();
private ArrayList<CharSequence> mStringPool = new ArrayList<CharSequence>();
private boolean mHaveCorrection;
private CharSequence mOriginalWord;
private String mLowerOriginalWord;
// TODO: Remove these member variables by passing more context to addWord() callback method
private boolean mIsFirstCharCapitalized;
private boolean mIsAllUpperCase;
private int mCorrectionMode = CORRECTION_BASIC;
public Suggest(Context context, int[] dictionaryResId) {
mMainDict = new BinaryDictionary(context, dictionaryResId, DIC_MAIN);
if (!hasMainDictionary()) {
Locale locale = context.getResources().getConfiguration().locale;
BinaryDictionary plug = PluginManager.getDictionary(context, locale.getLanguage());
if (plug != null) {
mMainDict.close();
mMainDict = plug;
}
}
initPool();
}
public Suggest(Context context, ByteBuffer byteBuffer) {
mMainDict = new BinaryDictionary(context, byteBuffer, DIC_MAIN);
initPool();
}
private void initPool() {
for (int i = 0; i < mPrefMaxSuggestions; i++) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
mStringPool.add(sb);
}
}
public void setAutoTextEnabled(boolean enabled) {
mAutoTextEnabled = enabled;
}
public int getCorrectionMode() {
return mCorrectionMode;
}
public void setCorrectionMode(int mode) {
mCorrectionMode = mode;
}
public boolean hasMainDictionary() {
return mMainDict.getSize() > LARGE_DICTIONARY_THRESHOLD;
}
public int getApproxMaxWordLength() {
return APPROX_MAX_WORD_LENGTH;
}
/**
* Sets an optional user dictionary resource to be loaded. The user dictionary is consulted
* before the main dictionary, if set.
*/
public void setUserDictionary(Dictionary userDictionary) {
mUserDictionary = userDictionary;
}
/**
* Sets an optional contacts dictionary resource to be loaded.
*/
public void setContactsDictionary(Dictionary userDictionary) {
mContactsDictionary = userDictionary;
}
public void setAutoDictionary(Dictionary autoDictionary) {
mAutoDictionary = autoDictionary;
}
public void setUserBigramDictionary(Dictionary userBigramDictionary) {
mUserBigramDictionary = userBigramDictionary;
}
/**
* Number of suggestions to generate from the input key sequence. This has
* to be a number between 1 and 100 (inclusive).
* @param maxSuggestions
* @throws IllegalArgumentException if the number is out of range
*/
public void setMaxSuggestions(int maxSuggestions) {
if (maxSuggestions < 1 || maxSuggestions > 100) {
throw new IllegalArgumentException("maxSuggestions must be between 1 and 100");
}
mPrefMaxSuggestions = maxSuggestions;
mPriorities = new int[mPrefMaxSuggestions];
mBigramPriorities = new int[PREF_MAX_BIGRAMS];
collectGarbage(mSuggestions, mPrefMaxSuggestions);
while (mStringPool.size() < mPrefMaxSuggestions) {
StringBuilder sb = new StringBuilder(getApproxMaxWordLength());
mStringPool.add(sb);
}
}
private boolean haveSufficientCommonality(String original, CharSequence suggestion) {
final int originalLength = original.length();
final int suggestionLength = suggestion.length();
final int minLength = Math.min(originalLength, suggestionLength);
if (minLength <= 2) return true;
int matching = 0;
int lessMatching = 0; // Count matches if we skip one character
int i;
for (i = 0; i < minLength; i++) {
final char origChar = ExpandableDictionary.toLowerCase(original.charAt(i));
if (origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i))) {
matching++;
lessMatching++;
} else if (i + 1 < suggestionLength
&& origChar == ExpandableDictionary.toLowerCase(suggestion.charAt(i + 1))) {
lessMatching++;
}
}
matching = Math.max(matching, lessMatching);
if (minLength <= 4) {
return matching >= 2;
} else {
return matching > minLength / 2;
}
}
/**
* Returns a list of words that match the list of character codes passed in.
* This list will be overwritten the next time this function is called.
* @param view a view for retrieving the context for AutoText
* @param wordComposer contains what is currently being typed
* @param prevWordForBigram previous word (used only for bigram)
* @return list of suggestions.
*/
public List<CharSequence> getSuggestions(View view, WordComposer wordComposer,
boolean includeTypedWordIfValid, CharSequence prevWordForBigram) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
mHaveCorrection = false;
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
Arrays.fill(mPriorities, 0);
Arrays.fill(mNextLettersFrequencies, 0);
// Save a lowercase version of the original word
mOriginalWord = wordComposer.getTypedWord();
if (mOriginalWord != null) {
final String mOriginalWordString = mOriginalWord.toString();
mOriginalWord = mOriginalWordString;
mLowerOriginalWord = mOriginalWordString.toLowerCase();
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(mOriginalWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
} else {
mLowerOriginalWord = "";
}
if (wordComposer.size() == 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
Arrays.fill(mBigramPriorities, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase();
if (mMainDict.isValidWord(lowerPrevWord)) {
prevWordForBigram = lowerPrevWord;
}
if (mUserBigramDictionary != null) {
mUserBigramDictionary.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
if (mContactsDictionary != null) {
mContactsDictionary.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
if (mMainDict != null) {
mMainDict.getBigrams(wordComposer, prevWordForBigram, this,
mNextLettersFrequencies);
}
char currentChar = wordComposer.getTypedWord().charAt(0);
char currentCharUpper = Character.toUpperCase(currentChar);
int count = 0;
int bigramSuggestionSize = mBigramSuggestions.size();
for (int i = 0; i < bigramSuggestionSize; i++) {
if (mBigramSuggestions.get(i).charAt(0) == currentChar
|| mBigramSuggestions.get(i).charAt(0) == currentCharUpper) {
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ?
(StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
sb.setLength(0);
sb.append(mBigramSuggestions.get(i));
mSuggestions.add(count++, sb);
if (count > mPrefMaxSuggestions) break;
}
}
}
} else if (wordComposer.size() > 1) {
// At second character typed, search the unigrams (scores being affected by bigrams)
if (mUserDictionary != null || mContactsDictionary != null) {
if (mUserDictionary != null) {
mUserDictionary.getWords(wordComposer, this, mNextLettersFrequencies);
}
if (mContactsDictionary != null) {
mContactsDictionary.getWords(wordComposer, this, mNextLettersFrequencies);
}
if (mSuggestions.size() > 0 && isValidWord(mOriginalWord)
&& (mCorrectionMode == CORRECTION_FULL
|| mCorrectionMode == CORRECTION_FULL_BIGRAM)) {
mHaveCorrection = true;
}
}
mMainDict.getWords(wordComposer, this, mNextLettersFrequencies);
if ((mCorrectionMode == CORRECTION_FULL || mCorrectionMode == CORRECTION_FULL_BIGRAM)
&& mSuggestions.size() > 0) {
mHaveCorrection = true;
}
}
if (mOriginalWord != null) {
mSuggestions.add(0, mOriginalWord.toString());
}
// Check if the first suggestion has a minimum number of characters in common
if (wordComposer.size() > 1 && mSuggestions.size() > 1
&& (mCorrectionMode == CORRECTION_FULL
|| mCorrectionMode == CORRECTION_FULL_BIGRAM)) {
if (!haveSufficientCommonality(mLowerOriginalWord, mSuggestions.get(1))) {
mHaveCorrection = false;
}
}
if (mAutoTextEnabled) {
int i = 0;
int max = 6;
// Don't autotext the suggestions from the dictionaries
if (mCorrectionMode == CORRECTION_BASIC) max = 1;
while (i < mSuggestions.size() && i < max) {
String suggestedWord = mSuggestions.get(i).toString().toLowerCase();
CharSequence autoText =
AutoText.get(suggestedWord, 0, suggestedWord.length(), view);
// Is there an AutoText correction?
boolean canAdd = autoText != null;
// Is that correction already the current prediction (or original word)?
canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i));
// Is that correction already the next predicted word?
if (canAdd && i + 1 < mSuggestions.size() && mCorrectionMode != CORRECTION_BASIC) {
canAdd &= !TextUtils.equals(autoText, mSuggestions.get(i + 1));
}
if (canAdd) {
mHaveCorrection = true;
mSuggestions.add(i + 1, autoText);
i++;
}
i++;
}
}
removeDupes();
return mSuggestions;
}
public int[] getNextLettersFrequencies() {
return mNextLettersFrequencies;
}
private void removeDupes() {
final ArrayList<CharSequence> suggestions = mSuggestions;
if (suggestions.size() < 2) return;
int i = 1;
// Don't cache suggestions.size(), since we may be removing items
while (i < suggestions.size()) {
final CharSequence cur = suggestions.get(i);
// Compare each candidate with each previous candidate
for (int j = 0; j < i; j++) {
CharSequence previous = suggestions.get(j);
if (TextUtils.equals(cur, previous)) {
removeFromSuggestions(i);
i--;
break;
}
}
i++;
}
}
private void removeFromSuggestions(int index) {
CharSequence garbage = mSuggestions.remove(index);
if (garbage != null && garbage instanceof StringBuilder) {
mStringPool.add(garbage);
}
}
public boolean hasMinimalCorrection() {
return mHaveCorrection;
}
private boolean compareCaseInsensitive(final String mLowerOriginalWord,
final char[] word, final int offset, final int length) {
final int originalLength = mLowerOriginalWord.length();
if (originalLength == length && Character.isUpperCase(word[offset])) {
for (int i = 0; i < originalLength; i++) {
if (mLowerOriginalWord.charAt(i) != Character.toLowerCase(word[offset+i])) {
return false;
}
}
return true;
}
return false;
}
public boolean addWord(final char[] word, final int offset, final int length, int freq,
final int dicTypeId, final Dictionary.DataType dataType) {
Dictionary.DataType dataTypeForLog = dataType;
ArrayList<CharSequence> suggestions;
int[] priorities;
int prefMaxSuggestions;
if(dataType == Dictionary.DataType.BIGRAM) {
suggestions = mBigramSuggestions;
priorities = mBigramPriorities;
prefMaxSuggestions = PREF_MAX_BIGRAMS;
} else {
suggestions = mSuggestions;
priorities = mPriorities;
prefMaxSuggestions = mPrefMaxSuggestions;
}
int pos = 0;
// Check if it's the same word, only caps are different
if (compareCaseInsensitive(mLowerOriginalWord, word, offset, length)) {
pos = 0;
} else {
if (dataType == Dictionary.DataType.UNIGRAM) {
// Check if the word was already added before (by bigram data)
int bigramSuggestion = searchBigramSuggestion(word,offset,length);
if(bigramSuggestion >= 0) {
dataTypeForLog = Dictionary.DataType.BIGRAM;
// turn freq from bigram into multiplier specified above
double multiplier = (((double) mBigramPriorities[bigramSuggestion])
/ MAXIMUM_BIGRAM_FREQUENCY)
* (BIGRAM_MULTIPLIER_MAX - BIGRAM_MULTIPLIER_MIN)
+ BIGRAM_MULTIPLIER_MIN;
/* Log.d(TAG,"bigram num: " + bigramSuggestion
+ " wordB: " + mBigramSuggestions.get(bigramSuggestion).toString()
+ " currentPriority: " + freq + " bigramPriority: "
+ mBigramPriorities[bigramSuggestion]
+ " multiplier: " + multiplier); */
freq = (int)Math.round((freq * multiplier));
}
}
// Check the last one's priority and bail
if (priorities[prefMaxSuggestions - 1] >= freq) return true;
while (pos < prefMaxSuggestions) {
if (priorities[pos] < freq
|| (priorities[pos] == freq && length < suggestions.get(pos).length())) {
break;
}
pos++;
}
}
if (pos >= prefMaxSuggestions) {
return true;
}
System.arraycopy(priorities, pos, priorities, pos + 1,
prefMaxSuggestions - pos - 1);
priorities[pos] = freq;
int poolSize = mStringPool.size();
StringBuilder sb = poolSize > 0 ? (StringBuilder) mStringPool.remove(poolSize - 1)
: new StringBuilder(getApproxMaxWordLength());
sb.setLength(0);
if (mIsAllUpperCase) {
sb.append(new String(word, offset, length).toUpperCase());
} else if (mIsFirstCharCapitalized) {
sb.append(Character.toUpperCase(word[offset]));
if (length > 1) {
sb.append(word, offset + 1, length - 1);
}
} else {
sb.append(word, offset, length);
}
suggestions.add(pos, sb);
if (suggestions.size() > prefMaxSuggestions) {
CharSequence garbage = suggestions.remove(prefMaxSuggestions);
if (garbage instanceof StringBuilder) {
mStringPool.add(garbage);
}
} else {
LatinImeLogger.onAddSuggestedWord(sb.toString(), dicTypeId, dataTypeForLog);
}
return true;
}
private int searchBigramSuggestion(final char[] word, final int offset, final int length) {
// TODO This is almost O(n^2). Might need fix.
// search whether the word appeared in bigram data
int bigramSuggestSize = mBigramSuggestions.size();
for(int i = 0; i < bigramSuggestSize; i++) {
if(mBigramSuggestions.get(i).length() == length) {
boolean chk = true;
for(int j = 0; j < length; j++) {
if(mBigramSuggestions.get(i).charAt(j) != word[offset+j]) {
chk = false;
break;
}
}
if(chk) return i;
}
}
return -1;
}
public boolean isValidWord(final CharSequence word) {
if (word == null || word.length() == 0) {
return false;
}
return mMainDict.isValidWord(word)
|| (mUserDictionary != null && mUserDictionary.isValidWord(word))
|| (mAutoDictionary != null && mAutoDictionary.isValidWord(word))
|| (mContactsDictionary != null && mContactsDictionary.isValidWord(word));
}
private void collectGarbage(ArrayList<CharSequence> suggestions, int prefMaxSuggestions) {
int poolSize = mStringPool.size();
int garbageSize = suggestions.size();
while (poolSize < prefMaxSuggestions && garbageSize > 0) {
CharSequence garbage = suggestions.get(garbageSize - 1);
if (garbage != null && garbage instanceof StringBuilder) {
mStringPool.add(garbage);
poolSize++;
}
garbageSize--;
}
if (poolSize == prefMaxSuggestions + 1) {
Log.w("Suggest", "String pool got too big: " + poolSize);
}
suggestions.clear();
}
public void close() {
if (mMainDict != null) {
mMainDict.close();
}
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/Suggest.java
|
Java
|
asf20
| 22,169
|
package org.pocketworkstation.pckeyboard;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParserException;
import android.content.BroadcastReceiver;
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.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.util.Log;
public class PluginManager extends BroadcastReceiver {
private static String TAG = "PCKeyboard";
private static String HK_INTENT_DICT = "org.pocketworkstation.DICT";
private static String SOFTKEYBOARD_INTENT_DICT = "com.menny.android.anysoftkeyboard.DICTIONARY";
private LatinIME mIME;
// Apparently anysoftkeyboard doesn't use ISO 639-1 language codes for its locales?
// Add exceptions as needed.
private static Map<String, String> SOFTKEYBOARD_LANG_MAP = new HashMap<String, String>();
static {
SOFTKEYBOARD_LANG_MAP.put("dk", "da");
}
PluginManager(LatinIME ime) {
super();
mIME = ime;
}
private static Map<String, DictPluginSpec> mPluginDicts =
new HashMap<String, DictPluginSpec>();
static interface DictPluginSpec {
BinaryDictionary getDict(Context context);
}
static private abstract class DictPluginSpecBase
implements DictPluginSpec {
String mPackageName;
Resources getResources(Context context) {
PackageManager packageManager = context.getPackageManager();
Resources res = null;
try {
ApplicationInfo appInfo = packageManager.getApplicationInfo(mPackageName, 0);
res = packageManager.getResourcesForApplication(appInfo);
} catch (NameNotFoundException e) {
Log.i(TAG, "couldn't get resources");
}
return res;
}
abstract InputStream[] getStreams(Resources res);
public BinaryDictionary getDict(Context context) {
Resources res = getResources(context);
if (res == null) return null;
InputStream[] dicts = getStreams(res);
if (dicts == null) return null;
BinaryDictionary dict = new BinaryDictionary(
context, dicts, Suggest.DIC_MAIN);
if (dict.getSize() == 0) return null;
//Log.i(TAG, "dict size=" + dict.getSize());
return dict;
}
}
static private class DictPluginSpecHK
extends DictPluginSpecBase {
int[] mRawIds;
public DictPluginSpecHK(String pkg, int[] ids) {
mPackageName = pkg;
mRawIds = ids;
}
@Override
InputStream[] getStreams(Resources res) {
if (mRawIds == null || mRawIds.length == 0) return null;
InputStream[] streams = new InputStream[mRawIds.length];
for (int i = 0; i < mRawIds.length; ++i) {
streams[i] = res.openRawResource(mRawIds[i]);
}
return streams;
}
}
static private class DictPluginSpecSoftKeyboard
extends DictPluginSpecBase {
String mAssetName;
public DictPluginSpecSoftKeyboard(String pkg, String asset) {
mPackageName = pkg;
mAssetName = asset;
}
@Override
InputStream[] getStreams(Resources res) {
if (mAssetName == null) return null;
try {
InputStream in = res.getAssets().open(mAssetName);
return new InputStream[] {in};
} catch (IOException e) {
Log.e(TAG, "Dictionary asset loading failure");
return null;
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Package information changed, updating dictionaries.");
getPluginDictionaries(context);
Log.i(TAG, "Finished updating dictionaries.");
mIME.toggleLanguage(true, true);
}
static void getSoftKeyboardDictionaries(PackageManager packageManager) {
Intent dictIntent = new Intent(SOFTKEYBOARD_INTENT_DICT);
List<ResolveInfo> dictPacks = packageManager.queryBroadcastReceivers(
dictIntent, PackageManager.GET_RECEIVERS);
for (ResolveInfo ri : dictPacks) {
ApplicationInfo appInfo = ri.activityInfo.applicationInfo;
String pkgName = appInfo.packageName;
boolean success = false;
try {
Resources res = packageManager.getResourcesForApplication(appInfo);
//Log.i(TAG, "Found dictionary plugin package: " + pkgName);
int dictId = res.getIdentifier("dictionaries", "xml", pkgName);
if (dictId == 0) continue;
XmlResourceParser xrp = res.getXml(dictId);
String assetName = null;
String lang = null;
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("Dictionary")) {
lang = xrp.getAttributeValue(null, "locale");
String convLang = SOFTKEYBOARD_LANG_MAP.get(lang);
if (convLang != null) lang = convLang;
String type = xrp.getAttributeValue(null, "type");
if (type == null || type.equals("raw") || type.equals("binary")) {
assetName = xrp.getAttributeValue(null, "dictionaryAssertName"); // sic
} else {
Log.w(TAG, "Unsupported AnySoftKeyboard dict type " + type);
}
//Log.i(TAG, "asset=" + assetName + " lang=" + lang);
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
if (assetName == null || lang == null) continue;
DictPluginSpec spec = new DictPluginSpecSoftKeyboard(pkgName, assetName);
mPluginDicts.put(lang, spec);
Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName);
success = true;
} catch (NameNotFoundException e) {
Log.i(TAG, "bad");
} finally {
if (!success) {
Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName);
}
}
}
}
static void getHKDictionaries(PackageManager packageManager) {
Intent dictIntent = new Intent(HK_INTENT_DICT);
List<ResolveInfo> dictPacks = packageManager.queryIntentActivities(dictIntent, 0);
for (ResolveInfo ri : dictPacks) {
ApplicationInfo appInfo = ri.activityInfo.applicationInfo;
String pkgName = appInfo.packageName;
boolean success = false;
try {
Resources res = packageManager.getResourcesForApplication(appInfo);
//Log.i(TAG, "Found dictionary plugin package: " + pkgName);
int langId = res.getIdentifier("dict_language", "string", pkgName);
if (langId == 0) continue;
String lang = res.getString(langId);
int[] rawIds = null;
// Try single-file version first
int rawId = res.getIdentifier("main", "raw", pkgName);
if (rawId != 0) {
rawIds = new int[] { rawId };
} else {
// try multi-part version
int parts = 0;
List<Integer> ids = new ArrayList<Integer>();
while (true) {
int id = res.getIdentifier("main" + parts, "raw", pkgName);
if (id == 0) break;
ids.add(id);
++parts;
}
if (parts == 0) continue; // no parts found
rawIds = new int[parts];
for (int i = 0; i < parts; ++i) rawIds[i] = ids.get(i);
}
DictPluginSpec spec = new DictPluginSpecHK(pkgName, rawIds);
mPluginDicts.put(lang, spec);
Log.i(TAG, "Found plugin dictionary: lang=" + lang + ", pkg=" + pkgName);
success = true;
} catch (NameNotFoundException e) {
Log.i(TAG, "bad");
} finally {
if (!success) {
Log.i(TAG, "failed to load plugin dictionary spec from " + pkgName);
}
}
}
}
static void getPluginDictionaries(Context context) {
mPluginDicts.clear();
PackageManager packageManager = context.getPackageManager();
getSoftKeyboardDictionaries(packageManager);
getHKDictionaries(packageManager);
}
static BinaryDictionary getDictionary(Context context, String lang) {
//Log.i(TAG, "Looking for plugin dictionary for lang=" + lang);
DictPluginSpec spec = mPluginDicts.get(lang);
if (spec == null) spec = mPluginDicts.get(lang.substring(0, 2));
if (spec == null) {
//Log.i(TAG, "No plugin found.");
return null;
}
BinaryDictionary dict = spec.getDict(context);
Log.i(TAG, "Found plugin dictionary for " + lang + (dict == null ? " is null" : ", size=" + dict.getSize()));
return dict;
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/PluginManager.java
|
Java
|
asf20
| 10,528
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.LinkedList;
import android.content.Context;
import android.os.AsyncTask;
/**
* Base class for an in-memory dictionary that can grow dynamically and can
* be searched for suggestions and valid words.
*/
public class ExpandableDictionary extends Dictionary {
/**
* There is difference between what java and native code can handle.
* It uses 32 because Java stack overflows when greater value is used.
*/
protected static final int MAX_WORD_LENGTH = 32;
private Context mContext;
private char[] mWordBuilder = new char[MAX_WORD_LENGTH];
private int mDicTypeId;
private int mMaxDepth;
private int mInputLength;
private int[] mNextLettersFrequencies;
private StringBuilder sb = new StringBuilder(MAX_WORD_LENGTH);
private static final char QUOTE = '\'';
private boolean mRequiresReload;
private boolean mUpdatingDictionary;
// Use this lock before touching mUpdatingDictionary & mRequiresDownload
private Object mUpdatingLock = new Object();
static class Node {
char code;
int frequency;
boolean terminal;
Node parent;
NodeArray children;
LinkedList<NextWord> ngrams; // Supports ngram
}
static class NodeArray {
Node[] data;
int length = 0;
private static final int INCREMENT = 2;
NodeArray() {
data = new Node[INCREMENT];
}
void add(Node n) {
if (length + 1 > data.length) {
Node[] tempData = new Node[length + INCREMENT];
if (length > 0) {
System.arraycopy(data, 0, tempData, 0, length);
}
data = tempData;
}
data[length++] = n;
}
}
static class NextWord {
Node word;
NextWord nextWord;
int frequency;
NextWord(Node word, int frequency) {
this.word = word;
this.frequency = frequency;
}
}
private NodeArray mRoots;
private int[][] mCodes;
ExpandableDictionary(Context context, int dicTypeId) {
mContext = context;
clearDictionary();
mCodes = new int[MAX_WORD_LENGTH][];
mDicTypeId = dicTypeId;
}
public void loadDictionary() {
synchronized (mUpdatingLock) {
startDictionaryLoadingTaskLocked();
}
}
public void startDictionaryLoadingTaskLocked() {
if (!mUpdatingDictionary) {
mUpdatingDictionary = true;
mRequiresReload = false;
new LoadDictionaryTask().execute();
}
}
public void setRequiresReload(boolean reload) {
synchronized (mUpdatingLock) {
mRequiresReload = reload;
}
}
public boolean getRequiresReload() {
return mRequiresReload;
}
/** Override to load your dictionary here, on a background thread. */
public void loadDictionaryAsync() {
}
Context getContext() {
return mContext;
}
int getMaxWordLength() {
return MAX_WORD_LENGTH;
}
public void addWord(String word, int frequency) {
addWordRec(mRoots, word, 0, frequency, null);
}
private void addWordRec(NodeArray children, final String word, final int depth,
final int frequency, Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
final int childrenLength = children.length;
Node childNode = null;
boolean found = false;
for (int i = 0; i < childrenLength; i++) {
childNode = children.data[i];
if (childNode.code == c) {
found = true;
break;
}
}
if (!found) {
childNode = new Node();
childNode.code = c;
childNode.parent = parentNode;
children.add(childNode);
}
if (wordLength == depth + 1) {
// Terminate this word
childNode.terminal = true;
childNode.frequency = Math.max(frequency, childNode.frequency);
if (childNode.frequency > 255) childNode.frequency = 255;
return;
}
if (childNode.children == null) {
childNode.children = new NodeArray();
}
addWordRec(childNode.children, word, depth + 1, frequency, childNode);
}
@Override
public void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
// Currently updating contacts, don't return any results.
if (mUpdatingDictionary) return;
}
mInputLength = codes.size();
mNextLettersFrequencies = nextLettersFrequencies;
if (mCodes.length < mInputLength) mCodes = new int[mInputLength][];
// Cache the codes so that we don't have to lookup an array list
for (int i = 0; i < mInputLength; i++) {
mCodes[i] = codes.getCodesAt(i);
}
mMaxDepth = mInputLength * 3;
getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, -1, callback);
for (int i = 0; i < mInputLength; i++) {
getWordsRec(mRoots, codes, mWordBuilder, 0, false, 1, 0, i, callback);
}
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
if (mUpdatingDictionary) return false;
}
final int freq = getWordFrequency(word);
return freq > -1;
}
/**
* Returns the word's frequency or -1 if not found
*/
public int getWordFrequency(CharSequence word) {
Node node = searchNode(mRoots, word, 0, word.length());
return (node == null) ? -1 : node.frequency;
}
/**
* Recursively traverse the tree for words that match the input. Input consists of
* a list of arrays. Each item in the list is one input character position. An input
* character is actually an array of multiple possible candidates. This function is not
* optimized for speed, assuming that the user dictionary will only be a few hundred words in
* size.
* @param roots node whose children have to be search for matches
* @param codes the input character codes
* @param word the word being composed as a possible match
* @param depth the depth of traversal - the length of the word being composed thus far
* @param completion whether the traversal is now in completion mode - meaning that we've
* exhausted the input and we're looking for all possible suffixes.
* @param snr current weight of the word being formed
* @param inputIndex position in the input characters. This can be off from the depth in
* case we skip over some punctuations such as apostrophe in the traversal. That is, if you type
* "wouldve", it could be matching "would've", so the depth will be one more than the
* inputIndex
* @param callback the callback class for adding a word
*/
protected void getWordsRec(NodeArray roots, final WordComposer codes, final char[] word,
final int depth, boolean completion, int snr, int inputIndex, int skipPos,
WordCallback callback) {
final int count = roots.length;
final int codeSize = mInputLength;
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > mMaxDepth) {
return;
}
int[] currentChars = null;
if (codeSize <= inputIndex) {
completion = true;
} else {
currentChars = mCodes[inputIndex];
}
for (int i = 0; i < count; i++) {
final Node node = roots.data[i];
final char c = node.code;
final char lowerC = toLowerCase(c);
final boolean terminal = node.terminal;
final NodeArray children = node.children;
final int freq = node.frequency;
if (completion) {
word[depth] = c;
if (terminal) {
if (!callback.addWord(word, 0, depth + 1, freq * snr, mDicTypeId,
DataType.UNIGRAM)) {
return;
}
// Add to frequency of next letters for predictive correction
if (mNextLettersFrequencies != null && depth >= inputIndex && skipPos < 0
&& mNextLettersFrequencies.length > word[inputIndex]) {
mNextLettersFrequencies[word[inputIndex]]++;
}
}
if (children != null) {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || depth == skipPos) {
// Skip the ' and continue deeper
word[depth] = c;
if (children != null) {
getWordsRec(children, codes, word, depth + 1, completion, snr, inputIndex,
skipPos, callback);
}
} else {
// Don't use alternatives if we're looking for missing characters
final int alternativesSize = skipPos >= 0? 1 : currentChars.length;
for (int j = 0; j < alternativesSize; j++) {
final int addedAttenuation = (j > 0 ? 1 : 2);
final int currentChar = currentChars[j];
if (currentChar == -1) {
break;
}
if (currentChar == lowerC || currentChar == c) {
word[depth] = c;
if (codeSize == inputIndex + 1) {
if (terminal) {
if (INCLUDE_TYPED_WORD_IF_VALID
|| !same(word, depth + 1, codes.getTypedWord())) {
int finalFreq = freq * snr * addedAttenuation;
if (skipPos < 0) finalFreq *= FULL_WORD_FREQ_MULTIPLIER;
callback.addWord(word, 0, depth + 1, finalFreq, mDicTypeId,
DataType.UNIGRAM);
}
}
if (children != null) {
getWordsRec(children, codes, word, depth + 1,
true, snr * addedAttenuation, inputIndex + 1,
skipPos, callback);
}
} else if (children != null) {
getWordsRec(children, codes, word, depth + 1,
false, snr * addedAttenuation, inputIndex + 1,
skipPos, callback);
}
}
}
}
}
}
protected int setBigram(String word1, String word2, int frequency) {
return addOrSetBigram(word1, word2, frequency, false);
}
protected int addBigram(String word1, String word2, int frequency) {
return addOrSetBigram(word1, word2, frequency, true);
}
/**
* Adds bigrams to the in-memory trie structure that is being used to retrieve any word
* @param frequency frequency for this bigrams
* @param addFrequency if true, it adds to current frequency
* @return returns the final frequency
*/
private int addOrSetBigram(String word1, String word2, int frequency, boolean addFrequency) {
Node firstWord = searchWord(mRoots, word1, 0, null);
Node secondWord = searchWord(mRoots, word2, 0, null);
LinkedList<NextWord> bigram = firstWord.ngrams;
if (bigram == null || bigram.size() == 0) {
firstWord.ngrams = new LinkedList<NextWord>();
bigram = firstWord.ngrams;
} else {
for (NextWord nw : bigram) {
if (nw.word == secondWord) {
if (addFrequency) {
nw.frequency += frequency;
} else {
nw.frequency = frequency;
}
return nw.frequency;
}
}
}
NextWord nw = new NextWord(secondWord, frequency);
firstWord.ngrams.add(nw);
return frequency;
}
/**
* Searches for the word and add the word if it does not exist.
* @return Returns the terminal node of the word we are searching for.
*/
private Node searchWord(NodeArray children, String word, int depth, Node parentNode) {
final int wordLength = word.length();
final char c = word.charAt(depth);
// Does children have the current character?
final int childrenLength = children.length;
Node childNode = null;
boolean found = false;
for (int i = 0; i < childrenLength; i++) {
childNode = children.data[i];
if (childNode.code == c) {
found = true;
break;
}
}
if (!found) {
childNode = new Node();
childNode.code = c;
childNode.parent = parentNode;
children.add(childNode);
}
if (wordLength == depth + 1) {
// Terminate this word
childNode.terminal = true;
return childNode;
}
if (childNode.children == null) {
childNode.children = new NodeArray();
}
return searchWord(childNode.children, word, depth + 1, childNode);
}
// @VisibleForTesting
boolean reloadDictionaryIfRequired() {
synchronized (mUpdatingLock) {
// If we need to update, start off a background task
if (mRequiresReload) startDictionaryLoadingTaskLocked();
// Currently updating contacts, don't return any results.
return mUpdatingDictionary;
}
}
private void runReverseLookUp(final CharSequence previousWord, final WordCallback callback) {
Node prevWord = searchNode(mRoots, previousWord, 0, previousWord.length());
if (prevWord != null && prevWord.ngrams != null) {
reverseLookUp(prevWord.ngrams, callback);
}
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
if (!reloadDictionaryIfRequired()) {
runReverseLookUp(previousWord, callback);
}
}
/**
* Used only for testing purposes
* This function will wait for loading from database to be done
*/
void waitForDictionaryLoading() {
while (mUpdatingDictionary) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
/**
* reverseLookUp retrieves the full word given a list of terminal nodes and adds those words
* through callback.
* @param terminalNodes list of terminal nodes we want to add
*/
private void reverseLookUp(LinkedList<NextWord> terminalNodes,
final WordCallback callback) {
Node node;
int freq;
for (NextWord nextWord : terminalNodes) {
node = nextWord.word;
freq = nextWord.frequency;
// TODO Not the best way to limit suggestion threshold
if (freq >= UserBigramDictionary.SUGGEST_THRESHOLD) {
sb.setLength(0);
do {
sb.insert(0, node.code);
node = node.parent;
} while(node != null);
// TODO better way to feed char array?
callback.addWord(sb.toString().toCharArray(), 0, sb.length(), freq, mDicTypeId,
DataType.BIGRAM);
}
}
}
/**
* Search for the terminal node of the word
* @return Returns the terminal node of the word if the word exists
*/
private Node searchNode(final NodeArray children, final CharSequence word, final int offset,
final int length) {
// TODO Consider combining with addWordRec
final int count = children.length;
char currentChar = word.charAt(offset);
for (int j = 0; j < count; j++) {
final Node node = children.data[j];
if (node.code == currentChar) {
if (offset == length - 1) {
if (node.terminal) {
return node;
}
} else {
if (node.children != null) {
Node returnNode = searchNode(node.children, word, offset + 1, length);
if (returnNode != null) return returnNode;
}
}
}
}
return null;
}
protected void clearDictionary() {
mRoots = new NodeArray();
}
private class LoadDictionaryTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... v) {
loadDictionaryAsync();
synchronized (mUpdatingLock) {
mUpdatingDictionary = false;
}
return null;
}
}
static char toLowerCase(char c) {
if (c < BASE_CHARS.length) {
c = BASE_CHARS[c];
}
if (c >= 'A' && c <= 'Z') {
c = (char) (c | 32);
} else if (c > 127) {
c = Character.toLowerCase(c);
}
return c;
}
/**
* Table mapping most combined Latin, Greek, and Cyrillic characters
* to their base characters. If c is in range, BASE_CHARS[c] == c
* if c is not a combined character, or the base character if it
* is combined.
*/
static final char BASE_CHARS[] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020,
0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7,
0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf,
0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043,
0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049,
0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7,
0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f
// Manually changed df to 73
0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063,
0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069,
0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7,
0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f
0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063,
0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064,
0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067,
0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127,
0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069,
0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b,
0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c,
0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e,
0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f,
0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072,
0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073,
0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167,
0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075,
0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079,
0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073,
0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187,
0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f,
0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197,
0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f,
0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7,
0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055,
0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7,
0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf,
0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c,
0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049,
0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc,
0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4,
0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067,
0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292,
0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7,
0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8,
0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065,
0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f,
0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075,
0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068,
0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061,
0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f,
0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237,
0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f,
0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247,
0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f,
0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257,
0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f,
0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267,
0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f,
0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277,
0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f,
0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287,
0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f,
0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297,
0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f,
0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7,
0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af,
0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077,
0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf,
0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7,
0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf,
0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7,
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df,
0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7,
0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef,
0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7,
0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff,
0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307,
0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f,
0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317,
0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f,
0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327,
0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f,
0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337,
0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f,
0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347,
0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f,
0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357,
0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f,
0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367,
0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f,
0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377,
0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f,
0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7,
0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9,
0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f,
0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9,
0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7,
0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf,
0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7,
0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df,
0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7,
0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef,
0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7,
0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff,
0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406,
0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f,
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f,
0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f,
0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f,
0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f,
0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456,
0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f,
0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467,
0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f,
0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475,
0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f,
0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487,
0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f,
0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497,
0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f,
0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7,
0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af,
0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7,
0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf,
0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7,
0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf,
0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435,
0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437,
0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e,
0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443,
0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7,
0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff,
};
// generated with:
// cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }'
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/ExpandableDictionary.java
|
Java
|
asf20
| 31,364
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
public class PrefScreenFeedback extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_feedback);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
@Override
protected void onResume() {
super.onResume();
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/PrefScreenFeedback.java
|
Java
|
asf20
| 1,711
|
/*
* Copyright (C) 2008-2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
public class InputLanguageSelection extends PreferenceActivity {
private static final String TAG = "PCKeyboardILS";
private ArrayList<Loc> mAvailableLanguages = new ArrayList<Loc>();
private static final String[] BLACKLIST_LANGUAGES = {
"ko", "ja", "zh"
};
// Languages for which auto-caps should be disabled
public static final Set<String> NOCAPS_LANGUAGES = new HashSet<String>();
static {
NOCAPS_LANGUAGES.add("ar");
NOCAPS_LANGUAGES.add("iw");
NOCAPS_LANGUAGES.add("th");
}
// Languages which should not use dead key logic. The modifier is entered after the base character.
public static final Set<String> NODEADKEY_LANGUAGES = new HashSet<String>();
static {
NODEADKEY_LANGUAGES.add("ar");
NODEADKEY_LANGUAGES.add("iw"); // TODO: currently no niqqud in the keymap?
NODEADKEY_LANGUAGES.add("th");
}
// Languages which should not auto-add space after completions
public static final Set<String> NOAUTOSPACE_LANGUAGES = new HashSet<String>();
static {
NOAUTOSPACE_LANGUAGES.add("th");
}
// Run the GetLanguages.sh script to update the following lists based on
// the available keyboard resources and dictionaries.
private static final String[] KBD_LOCALIZATIONS = {
"ar", "bg", "ca", "cs", "cs_QY", "da", "de", "el", "en", "en_DV",
"en_GB", "es", "es_LA", "es_US", "fa", "fi", "fr", "fr_CA", "he",
"hr", "hu", "hu_QY", "hy", "in", "it", "iw", "ja", "ka", "ko",
"lo", "lt", "lv", "nb", "nl", "pl", "pt", "pt_PT", "rm", "ro",
"ru", "ru_PH", "si", "sk", "sk_QY", "sl", "sr", "sv", "ta", "th",
"tl", "tr", "uk", "vi", "zh_CN", "zh_TW"
};
private static final String[] KBD_5_ROW = {
"ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "en_GB",
"es", "es_LA", "fa", "fi", "fr", "fr_CA", "he", "hr", "hu", "hu_QY",
"hy", "it", "iw", "lo", "nb", "pt_PT", "ro", "ru", "ru_PH", "si",
"sk", "sk_QY", "sl", "sr", "sv", "ta", "th", "tr", "uk"
};
private static final String[] KBD_4_ROW = {
"ar", "bg", "cs", "cs_QY", "da", "de", "el", "en", "en_DV", "es",
"es_LA", "es_US", "fa", "fr", "fr_CA", "he", "hr", "hu", "hu_QY",
"iw", "nb", "ru", "ru_PH", "sk", "sk_QY", "sl", "sr", "sv", "tr",
"uk"
};
private static String getLocaleName(Locale l) {
String lang = l.getLanguage();
String country = l.getCountry();
if (lang.equals("en") && country.equals("DV")) {
return "English (Dvorak)";
} else if (lang.equals("en") && country.equals("EX")) {
return "English (4x11)";
} else if (lang.equals("es") && country.equals("LA")) {
return "Español (Latinoamérica)";
} else if (lang.equals("cs") && country.equals("QY")) {
return "Čeština (QWERTY)";
} else if (lang.equals("hu") && country.equals("QY")) {
return "Magyar (QWERTY)";
} else if (lang.equals("sk") && country.equals("QY")) {
return "Slovenčina (QWERTY)";
} else if (lang.equals("ru") && country.equals("PH")) {
return "Русский (Phonetic)";
} else {
return LanguageSwitcher.toTitleCase(l.getDisplayName(l));
}
}
private static class Loc implements Comparable<Object> {
static Collator sCollator = Collator.getInstance();
String label;
Locale locale;
public Loc(String label, Locale locale) {
this.label = label;
this.locale = locale;
}
@Override
public String toString() {
return this.label;
}
public int compareTo(Object o) {
return sCollator.compare(this.label, ((Loc) o).label);
}
}
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.language_prefs);
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String selectedLanguagePref = sp.getString(LatinIME.PREF_SELECTED_LANGUAGES, "");
Log.i(TAG, "selected languages: " + selectedLanguagePref);
String[] languageList = selectedLanguagePref.split(",");
mAvailableLanguages = getUniqueLocales();
// Compatibility hack for v1.22 and older - if a selected language 5-code isn't
// found in the current list of available languages, try adding the 2-letter
// language code. For example, "en_US" is no longer listed, so use "en" instead.
Set<String> availableLanguages = new HashSet<String>();
for (int i = 0; i < mAvailableLanguages.size(); i++) {
Locale locale = mAvailableLanguages.get(i).locale;
availableLanguages.add(get5Code(locale));
}
Set<String> languageSelections = new HashSet<String>();
for (int i = 0; i < languageList.length; ++i) {
String spec = languageList[i];
if (availableLanguages.contains(spec)) {
languageSelections.add(spec);
} else if (spec.length() > 2) {
String lang = spec.substring(0, 2);
if (availableLanguages.contains(lang)) languageSelections.add(lang);
}
}
PreferenceGroup parent = getPreferenceScreen();
for (int i = 0; i < mAvailableLanguages.size(); i++) {
CheckBoxPreference pref = new CheckBoxPreference(this);
Locale locale = mAvailableLanguages.get(i).locale;
pref.setTitle(mAvailableLanguages.get(i).label +
" [" + locale.toString() + "]");
String fivecode = get5Code(locale);
String language = locale.getLanguage();
boolean checked = languageSelections.contains(fivecode);
pref.setChecked(checked);
boolean has4Row = arrayContains(KBD_4_ROW, fivecode) || arrayContains(KBD_4_ROW, language);
boolean has5Row = arrayContains(KBD_5_ROW, fivecode) || arrayContains(KBD_5_ROW, language);
List<String> summaries = new ArrayList<String>(3);
if (has5Row) summaries.add("5-row");
if (has4Row) summaries.add("4-row");
if (hasDictionary(locale)) {
summaries.add(getResources().getString(R.string.has_dictionary));
}
if (!summaries.isEmpty()) {
StringBuilder summary = new StringBuilder();
for (int j = 0; j < summaries.size(); ++j) {
if (j > 0) summary.append(", ");
summary.append(summaries.get(j));
}
pref.setSummary(summary.toString());
}
parent.addPreference(pref);
}
}
private boolean hasDictionary(Locale locale) {
Resources res = getResources();
Configuration conf = res.getConfiguration();
Locale saveLocale = conf.locale;
boolean haveDictionary = false;
conf.locale = locale;
res.updateConfiguration(conf, res.getDisplayMetrics());
int[] dictionaries = LatinIME.getDictionary(res);
BinaryDictionary bd = new BinaryDictionary(this, dictionaries, Suggest.DIC_MAIN);
// Is the dictionary larger than a placeholder? Arbitrarily chose a lower limit of
// 4000-5000 words, whereas the LARGE_DICTIONARY is about 20000+ words.
if (bd.getSize() > Suggest.LARGE_DICTIONARY_THRESHOLD / 4) {
haveDictionary = true;
} else {
BinaryDictionary plug = PluginManager.getDictionary(getApplicationContext(), locale.getLanguage());
if (plug != null) {
bd.close();
bd = plug;
haveDictionary = true;
}
}
bd.close();
conf.locale = saveLocale;
res.updateConfiguration(conf, res.getDisplayMetrics());
return haveDictionary;
}
private String get5Code(Locale locale) {
String country = locale.getCountry();
return locale.getLanguage()
+ (TextUtils.isEmpty(country) ? "" : "_" + country);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
// Save the selected languages
String checkedLanguages = "";
PreferenceGroup parent = getPreferenceScreen();
int count = parent.getPreferenceCount();
for (int i = 0; i < count; i++) {
CheckBoxPreference pref = (CheckBoxPreference) parent.getPreference(i);
if (pref.isChecked()) {
Locale locale = mAvailableLanguages.get(i).locale;
checkedLanguages += get5Code(locale) + ",";
}
}
if (checkedLanguages.length() < 1) checkedLanguages = null; // Save null
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sp.edit();
editor.putString(LatinIME.PREF_SELECTED_LANGUAGES, checkedLanguages);
SharedPreferencesCompat.apply(editor);
}
private static String asString(Set<String> set) {
StringBuilder out = new StringBuilder();
out.append("set(");
String[] parts = new String[set.size()];
parts = set.toArray(parts);
Arrays.sort(parts);
for (int i = 0; i < parts.length; ++i) {
if (i > 0) out.append(", ");
out.append(parts[i]);
}
out.append(")");
return out.toString();
}
ArrayList<Loc> getUniqueLocales() {
Set<String> localeSet = new HashSet<String>();
Set<String> langSet = new HashSet<String>();
// Ignore the system (asset) locale list, it's inconsistent and incomplete
// String[] sysLocales = getAssets().getLocales();
//
// // First, add zz_ZZ style full language+country locales
// for (int i = 0; i < sysLocales.length; ++i) {
// String sl = sysLocales[i];
// if (sl.length() != 5) continue;
// localeSet.add(sl);
// langSet.add(sl.substring(0, 2));
// }
//
// // Add entries for system languages without country, but only if there's
// // no full locale for that language yet.
// for (int i = 0; i < sysLocales.length; ++i) {
// String sl = sysLocales[i];
// if (sl.length() != 2 || langSet.contains(sl)) continue;
// localeSet.add(sl);
// }
// Add entries for additional languages supported by the keyboard.
for (int i = 0; i < KBD_LOCALIZATIONS.length; ++i) {
String kl = KBD_LOCALIZATIONS[i];
if (kl.length() == 2 && langSet.contains(kl)) continue;
// replace zz_rYY with zz_YY
if (kl.length() == 6) kl = kl.substring(0, 2) + "_" + kl.substring(4, 6);
localeSet.add(kl);
}
Log.i(TAG, "localeSet=" + asString(localeSet));
Log.i(TAG, "langSet=" + asString(langSet));
// Now build the locale list for display
String[] locales = new String[localeSet.size()];
locales = localeSet.toArray(locales);
Arrays.sort(locales);
ArrayList<Loc> uniqueLocales = new ArrayList<Loc>();
final int origSize = locales.length;
Loc[] preprocess = new Loc[origSize];
int finalSize = 0;
for (int i = 0 ; i < origSize; i++ ) {
String s = locales[i];
int len = s.length();
if (len == 2 || len == 5 || len == 6) {
String language = s.substring(0, 2);
Locale l;
if (len == 5) {
// zz_YY
String country = s.substring(3, 5);
l = new Locale(language, country);
} else if (len == 6) {
// zz_rYY
l = new Locale(language, s.substring(4, 6));
} else {
l = new Locale(language);
}
// Exclude languages that are not relevant to LatinIME
if (arrayContains(BLACKLIST_LANGUAGES, language)) continue;
if (finalSize == 0) {
preprocess[finalSize++] =
new Loc(LanguageSwitcher.toTitleCase(l.getDisplayName(l)), l);
} else {
// check previous entry:
// same lang and a country -> upgrade to full name and
// insert ours with full name
// diff lang -> insert ours with lang-only name
if (preprocess[finalSize-1].locale.getLanguage().equals(
language)) {
preprocess[finalSize-1].label = getLocaleName(preprocess[finalSize-1].locale);
preprocess[finalSize++] =
new Loc(getLocaleName(l), l);
} else {
String displayName;
if (s.equals("zz_ZZ")) {
} else {
displayName = getLocaleName(l);
preprocess[finalSize++] = new Loc(displayName, l);
}
}
}
}
}
for (int i = 0; i < finalSize ; i++) {
uniqueLocales.add(preprocess[i]);
}
return uniqueLocales;
}
private boolean arrayContains(String[] array, String value) {
for (int i = 0; i < array.length; i++) {
if (array[i].equalsIgnoreCase(value)) return true;
}
return false;
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/InputLanguageSelection.java
|
Java
|
asf20
| 15,082
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CandidateView extends View {
private static final int OUT_OF_BOUNDS_WORD_INDEX = -1;
private static final int OUT_OF_BOUNDS_X_COORD = -1;
private LatinIME mService;
private final ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
private boolean mShowingCompletions;
private CharSequence mSelectedString;
private int mSelectedIndex;
private int mTouchX = OUT_OF_BOUNDS_X_COORD;
private final Drawable mSelectionHighlight;
private boolean mTypedWordValid;
private boolean mHaveMinimalSuggestion;
private Rect mBgPadding;
private final TextView mPreviewText;
private final PopupWindow mPreviewPopup;
private int mCurrentWordIndex;
private Drawable mDivider;
private static final int MAX_SUGGESTIONS = 32;
private static final int SCROLL_PIXELS = 20;
private final int[] mWordWidth = new int[MAX_SUGGESTIONS];
private final int[] mWordX = new int[MAX_SUGGESTIONS];
private int mPopupPreviewX;
private int mPopupPreviewY;
private static final int X_GAP = 10;
private final int mColorNormal;
private final int mColorRecommended;
private final int mColorOther;
private final Paint mPaint;
private final int mDescent;
private boolean mScrolled;
private boolean mShowingAddToDictionary;
private CharSequence mAddToDictionaryHint;
private int mTargetScrollX;
private final int mMinTouchableWidth;
private int mTotalWidth;
private final GestureDetector mGestureDetector;
/**
* Construct a CandidateView for showing suggested words for completion.
* @param context
* @param attrs
*/
public CandidateView(Context context, AttributeSet attrs) {
super(context, attrs);
mSelectionHighlight = context.getResources().getDrawable(
R.drawable.list_selector_background_pressed);
LayoutInflater inflate =
(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resources res = context.getResources();
mPreviewPopup = new PopupWindow(context);
mPreviewText = (TextView) inflate.inflate(R.layout.candidate_preview, null);
mPreviewPopup.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
mPreviewPopup.setAnimationStyle(R.style.KeyPreviewAnimation);
mColorNormal = res.getColor(R.color.candidate_normal);
mColorRecommended = res.getColor(R.color.candidate_recommended);
mColorOther = res.getColor(R.color.candidate_other);
mDivider = res.getDrawable(R.drawable.keyboard_suggest_strip_divider);
mAddToDictionaryHint = res.getString(R.string.hint_add_to_dictionary);
mPaint = new Paint();
mPaint.setColor(mColorNormal);
mPaint.setAntiAlias(true);
mPaint.setTextSize(mPreviewText.getTextSize() * LatinIME.sKeyboardSettings.candidateScalePref);
mPaint.setStrokeWidth(0);
mPaint.setTextAlign(Align.CENTER);
mDescent = (int) mPaint.descent();
mMinTouchableWidth = (int)res.getDimension(R.dimen.candidate_min_touchable_width);
mGestureDetector = new GestureDetector(
new CandidateStripGestureListener(mMinTouchableWidth));
setWillNotDraw(false);
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
scrollTo(0, getScrollY());
}
private class CandidateStripGestureListener extends GestureDetector.SimpleOnGestureListener {
private final int mTouchSlopSquare;
public CandidateStripGestureListener(int touchSlop) {
// Slightly reluctant to scroll to be able to easily choose the suggestion
mTouchSlopSquare = touchSlop * touchSlop;
}
@Override
public void onLongPress(MotionEvent me) {
if (mSuggestions.size() > 0) {
if (me.getX() + getScrollX() < mWordWidth[0] && getScrollX() < 10) {
longPressFirstWord();
}
}
}
@Override
public boolean onDown(MotionEvent e) {
mScrolled = false;
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!mScrolled) {
// This is applied only when we recognize that scrolling is starting.
final int deltaX = (int) (e2.getX() - e1.getX());
final int deltaY = (int) (e2.getY() - e1.getY());
final int distance = (deltaX * deltaX) + (deltaY * deltaY);
if (distance < mTouchSlopSquare) {
return true;
}
mScrolled = true;
}
final int width = getWidth();
mScrolled = true;
int scrollX = getScrollX();
scrollX += (int) distanceX;
if (scrollX < 0) {
scrollX = 0;
}
if (distanceX > 0 && scrollX + width > mTotalWidth) {
scrollX -= (int) distanceX;
}
mTargetScrollX = scrollX;
scrollTo(scrollX, getScrollY());
hidePreview();
invalidate();
return true;
}
}
/**
* A connection back to the service to communicate with the text field
* @param listener
*/
public void setService(LatinIME listener) {
mService = listener;
}
@Override
public int computeHorizontalScrollRange() {
return mTotalWidth;
}
/**
* If the canvas is null, then only touch calculations are performed to pick the target
* candidate.
*/
@Override
protected void onDraw(Canvas canvas) {
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth = 0;
final int height = getHeight();
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0, 0, mDivider.getIntrinsicWidth(),
mDivider.getIntrinsicHeight());
}
final int count = mSuggestions.size();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int touchX = mTouchX;
final int scrollX = getScrollX();
final boolean scrolled = mScrolled;
final boolean typedWordValid = mTypedWordValid;
final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2;
boolean existsAutoCompletion = false;
int x = 0;
for (int i = 0; i < count; i++) {
CharSequence suggestion = mSuggestions.get(i);
if (suggestion == null) continue;
final int wordLength = suggestion.length();
paint.setColor(mColorNormal);
if (mHaveMinimalSuggestion
&& ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
existsAutoCompletion = true;
} else if (i != 0 || (wordLength == 1 && count > 1)) {
// HACK: even if i == 0, we use mColorOther when this suggestion's length is 1 and
// there are multiple suggestions, such as the default punctuation list.
paint.setColor(mColorOther);
}
int wordWidth;
if ((wordWidth = mWordWidth[i]) == 0) {
float textWidth = paint.measureText(suggestion, 0, wordLength);
wordWidth = Math.max(mMinTouchableWidth, (int) textWidth + X_GAP * 2);
mWordWidth[i] = wordWidth;
}
mWordX[i] = x;
if (touchX != OUT_OF_BOUNDS_X_COORD && !scrolled
&& touchX + scrollX >= x && touchX + scrollX < x + wordWidth) {
if (canvas != null && !mShowingAddToDictionary) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
}
mSelectedString = suggestion;
mSelectedIndex = i;
}
if (canvas != null) {
canvas.drawText(suggestion, 0, wordLength, x + wordWidth / 2, y, paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth, 0);
// Draw a divider unless it's after the hint
if (!(mShowingAddToDictionary && i == 1)) {
mDivider.draw(canvas);
}
canvas.translate(-x - wordWidth, 0);
}
paint.setTypeface(Typeface.DEFAULT);
x += wordWidth;
}
mService.onAutoCompletionStateChanged(existsAutoCompletion);
mTotalWidth = x;
if (mTargetScrollX != scrollX) {
scrollToTarget();
}
}
private void scrollToTarget() {
int scrollX = getScrollX();
if (mTargetScrollX > scrollX) {
scrollX += SCROLL_PIXELS;
if (scrollX >= mTargetScrollX) {
scrollX = mTargetScrollX;
scrollTo(scrollX, getScrollY());
requestLayout();
} else {
scrollTo(scrollX, getScrollY());
}
} else {
scrollX -= SCROLL_PIXELS;
if (scrollX <= mTargetScrollX) {
scrollX = mTargetScrollX;
scrollTo(scrollX, getScrollY());
requestLayout();
} else {
scrollTo(scrollX, getScrollY());
}
}
invalidate();
}
public void setSuggestions(List<CharSequence> suggestions, boolean completions,
boolean typedWordValid, boolean haveMinimalSuggestion) {
clear();
if (suggestions != null) {
int insertCount = Math.min(suggestions.size(), MAX_SUGGESTIONS);
for (CharSequence suggestion : suggestions) {
mSuggestions.add(suggestion);
if (--insertCount == 0)
break;
}
}
mShowingCompletions = completions;
mTypedWordValid = typedWordValid;
scrollTo(0, getScrollY());
mTargetScrollX = 0;
mHaveMinimalSuggestion = haveMinimalSuggestion;
// Compute the total width
onDraw(null);
invalidate();
requestLayout();
}
public boolean isShowingAddToDictionaryHint() {
return mShowingAddToDictionary;
}
public void showAddToDictionaryHint(CharSequence word) {
ArrayList<CharSequence> suggestions = new ArrayList<CharSequence>();
suggestions.add(word);
suggestions.add(mAddToDictionaryHint);
setSuggestions(suggestions, false, false, false);
mShowingAddToDictionary = true;
}
public boolean dismissAddToDictionaryHint() {
if (!mShowingAddToDictionary) return false;
clear();
return true;
}
/* package */ List<CharSequence> getSuggestions() {
return mSuggestions;
}
public void clear() {
// Don't call mSuggestions.clear() because it's being used for logging
// in LatinIME.pickSuggestionManually().
mSuggestions.clear();
mTouchX = OUT_OF_BOUNDS_X_COORD;
mSelectedString = null;
mSelectedIndex = -1;
mShowingAddToDictionary = false;
invalidate();
Arrays.fill(mWordWidth, 0);
Arrays.fill(mWordX, 0);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
if (mGestureDetector.onTouchEvent(me)) {
return true;
}
int action = me.getAction();
int x = (int) me.getX();
int y = (int) me.getY();
mTouchX = x;
switch (action) {
case MotionEvent.ACTION_DOWN:
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (y <= 0) {
// Fling up!?
if (mSelectedString != null) {
// If there are completions from the application, we don't change the state to
// STATE_PICKED_SUGGESTION
if (!mShowingCompletions) {
// This "acceptedSuggestion" will not be counted as a word because
// it will be counted in pickSuggestion instead.
//TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
//TextEntryState.manualTyped(mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
mSelectedString = null;
mSelectedIndex = -1;
}
}
break;
case MotionEvent.ACTION_UP:
if (!mScrolled) {
if (mSelectedString != null) {
if (mShowingAddToDictionary) {
longPressFirstWord();
clear();
} else {
if (!mShowingCompletions) {
//TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
//TextEntryState.manualTyped(mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
}
}
}
mSelectedString = null;
mSelectedIndex = -1;
requestLayout();
hidePreview();
invalidate();
break;
}
return true;
}
private void hidePreview() {
mTouchX = OUT_OF_BOUNDS_X_COORD;
mCurrentWordIndex = OUT_OF_BOUNDS_WORD_INDEX;
mPreviewPopup.dismiss();
}
private void showPreview(int wordIndex, String altText) {
int oldWordIndex = mCurrentWordIndex;
mCurrentWordIndex = wordIndex;
// If index changed or changing text
if (oldWordIndex != mCurrentWordIndex || altText != null) {
if (wordIndex == OUT_OF_BOUNDS_WORD_INDEX) {
hidePreview();
} else {
CharSequence word = altText != null? altText : mSuggestions.get(wordIndex);
mPreviewText.setText(word);
mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int wordWidth = (int) (mPaint.measureText(word, 0, word.length()) + X_GAP * 2);
final int popupWidth = wordWidth
+ mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight();
final int popupHeight = mPreviewText.getMeasuredHeight();
//mPreviewText.setVisibility(INVISIBLE);
mPopupPreviewX = mWordX[wordIndex] - mPreviewText.getPaddingLeft() - getScrollX()
+ (mWordWidth[wordIndex] - wordWidth) / 2;
mPopupPreviewY = - popupHeight;
int [] offsetInWindow = new int[2];
getLocationInWindow(offsetInWindow);
if (mPreviewPopup.isShowing()) {
mPreviewPopup.update(mPopupPreviewX, mPopupPreviewY + offsetInWindow[1],
popupWidth, popupHeight);
} else {
mPreviewPopup.setWidth(popupWidth);
mPreviewPopup.setHeight(popupHeight);
mPreviewPopup.showAtLocation(this, Gravity.NO_GRAVITY, mPopupPreviewX,
mPopupPreviewY + offsetInWindow[1]);
}
mPreviewText.setVisibility(VISIBLE);
}
}
}
private void longPressFirstWord() {
CharSequence word = mSuggestions.get(0);
if (word.length() < 2) return;
if (mService.addWordToDictionary(word.toString())) {
showPreview(0, getContext().getResources().getString(R.string.added_word, word));
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
hidePreview();
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/CandidateView.java
|
Java
|
asf20
| 18,067
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.util.HashMap;
import java.util.Map;
import android.app.Dialog;
import android.app.backup.BackupManager;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.text.AutoText;
import android.text.InputType;
import android.util.Log;
public class LatinIMESettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener,
DialogInterface.OnDismissListener {
private static final String QUICK_FIXES_KEY = "quick_fixes";
private static final String PREDICTION_SETTINGS_KEY = "prediction_settings";
private static final String VOICE_SETTINGS_KEY = "voice_mode";
/* package */ static final String PREF_SETTINGS_KEY = "settings_key";
static final String INPUT_CONNECTION_INFO = "input_connection_info";
private static final String TAG = "LatinIMESettings";
// Dialog ids
private static final int VOICE_INPUT_CONFIRM_DIALOG = 0;
private CheckBoxPreference mQuickFixes;
private ListPreference mVoicePreference;
private ListPreference mSettingsKeyPreference;
private ListPreference mKeyboardModePortraitPreference;
private ListPreference mKeyboardModeLandscapePreference;
private Preference mInputConnectionInfo;
private boolean mVoiceOn;
private boolean mOkClicked = false;
private String mVoiceModeOff;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs);
mQuickFixes = (CheckBoxPreference) findPreference(QUICK_FIXES_KEY);
mVoicePreference = (ListPreference) findPreference(VOICE_SETTINGS_KEY);
mSettingsKeyPreference = (ListPreference) findPreference(PREF_SETTINGS_KEY);
mInputConnectionInfo = (Preference) findPreference(INPUT_CONNECTION_INFO);
// TODO(klausw): remove these when no longer needed
mKeyboardModePortraitPreference = (ListPreference) findPreference("pref_keyboard_mode_portrait");
mKeyboardModeLandscapePreference = (ListPreference) findPreference("pref_keyboard_mode_landscape");
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mVoiceModeOff = getString(R.string.voice_mode_off);
mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff));
}
@Override
protected void onResume() {
super.onResume();
int autoTextSize = AutoText.getSize(getListView());
if (autoTextSize < 1) {
((PreferenceGroup) findPreference(PREDICTION_SETTINGS_KEY))
.removePreference(mQuickFixes);
}
Log.i(TAG, "compactModeEnabled=" + LatinIME.sKeyboardSettings.compactModeEnabled);
if (!LatinIME.sKeyboardSettings.compactModeEnabled) {
CharSequence[] oldEntries = mKeyboardModePortraitPreference.getEntries();
CharSequence[] oldValues = mKeyboardModePortraitPreference.getEntryValues();
if (oldEntries.length > 2) {
CharSequence[] newEntries = new CharSequence[] { oldEntries[0], oldEntries[2] };
CharSequence[] newValues = new CharSequence[] { oldValues[0], oldValues[2] };
mKeyboardModePortraitPreference.setEntries(newEntries);
mKeyboardModePortraitPreference.setEntryValues(newValues);
mKeyboardModeLandscapePreference.setEntries(newEntries);
mKeyboardModeLandscapePreference.setEntryValues(newValues);
}
}
updateSummaries();
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
// If turning on voice input, show dialog
if (key.equals(VOICE_SETTINGS_KEY) && !mVoiceOn) {
if (!prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff)
.equals(mVoiceModeOff)) {
showVoiceConfirmation();
}
}
mVoiceOn = !(prefs.getString(VOICE_SETTINGS_KEY, mVoiceModeOff).equals(mVoiceModeOff));
updateVoiceModeSummary();
updateSummaries();
}
static Map<Integer, String> INPUT_CLASSES = new HashMap<Integer, String>();
static Map<Integer, String> DATETIME_VARIATIONS = new HashMap<Integer, String>();
static Map<Integer, String> TEXT_VARIATIONS = new HashMap<Integer, String>();
static Map<Integer, String> NUMBER_VARIATIONS = new HashMap<Integer, String>();
static {
INPUT_CLASSES.put(0x00000004, "DATETIME");
INPUT_CLASSES.put(0x00000002, "NUMBER");
INPUT_CLASSES.put(0x00000003, "PHONE");
INPUT_CLASSES.put(0x00000001, "TEXT");
INPUT_CLASSES.put(0x00000000, "NULL");
DATETIME_VARIATIONS.put(0x00000010, "DATE");
DATETIME_VARIATIONS.put(0x00000020, "TIME");
NUMBER_VARIATIONS.put(0x00000010, "PASSWORD");
TEXT_VARIATIONS.put(0x00000020, "EMAIL_ADDRESS");
TEXT_VARIATIONS.put(0x00000030, "EMAIL_SUBJECT");
TEXT_VARIATIONS.put(0x000000b0, "FILTER");
TEXT_VARIATIONS.put(0x00000050, "LONG_MESSAGE");
TEXT_VARIATIONS.put(0x00000080, "PASSWORD");
TEXT_VARIATIONS.put(0x00000060, "PERSON_NAME");
TEXT_VARIATIONS.put(0x000000c0, "PHONETIC");
TEXT_VARIATIONS.put(0x00000070, "POSTAL_ADDRESS");
TEXT_VARIATIONS.put(0x00000040, "SHORT_MESSAGE");
TEXT_VARIATIONS.put(0x00000010, "URI");
TEXT_VARIATIONS.put(0x00000090, "VISIBLE_PASSWORD");
TEXT_VARIATIONS.put(0x000000a0, "WEB_EDIT_TEXT");
TEXT_VARIATIONS.put(0x000000d0, "WEB_EMAIL_ADDRESS");
TEXT_VARIATIONS.put(0x000000e0, "WEB_PASSWORD");
}
private static void addBit(StringBuffer buf, int bit, String str) {
if (bit != 0) {
buf.append("|");
buf.append(str);
}
}
private static String inputTypeDesc(int type) {
int cls = type & 0x0000000f; // MASK_CLASS
int flags = type & 0x00fff000; // MASK_FLAGS
int var = type & 0x00000ff0; // MASK_VARIATION
StringBuffer out = new StringBuffer();
String clsName = INPUT_CLASSES.get(cls);
out.append(clsName != null ? clsName : "?");
if (cls == InputType.TYPE_CLASS_TEXT) {
String varName = TEXT_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
addBit(out, flags & 0x00010000, "AUTO_COMPLETE");
addBit(out, flags & 0x00008000, "AUTO_CORRECT");
addBit(out, flags & 0x00001000, "CAP_CHARACTERS");
addBit(out, flags & 0x00004000, "CAP_SENTENCES");
addBit(out, flags & 0x00002000, "CAP_WORDS");
addBit(out, flags & 0x00040000, "IME_MULTI_LINE");
addBit(out, flags & 0x00020000, "MULTI_LINE");
addBit(out, flags & 0x00080000, "NO_SUGGESTIONS");
} else if (cls == InputType.TYPE_CLASS_NUMBER) {
String varName = NUMBER_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
addBit(out, flags & 0x00002000, "DECIMAL");
addBit(out, flags & 0x00001000, "SIGNED");
} else if (cls == InputType.TYPE_CLASS_DATETIME) {
String varName = DATETIME_VARIATIONS.get(var);
if (varName != null) {
out.append(".");
out.append(varName);
}
}
return out.toString();
}
private void updateSummaries() {
Resources res = getResources();
mSettingsKeyPreference.setSummary(
res.getStringArray(R.array.settings_key_modes)
[mSettingsKeyPreference.findIndexOfValue(mSettingsKeyPreference.getValue())]);
mInputConnectionInfo.setSummary(String.format("%s type=%s",
LatinIME.sKeyboardSettings.editorPackageName,
inputTypeDesc(LatinIME.sKeyboardSettings.editorInputType)
));
}
private void showVoiceConfirmation() {
mOkClicked = false;
showDialog(VOICE_INPUT_CONFIRM_DIALOG);
}
private void updateVoiceModeSummary() {
mVoicePreference.setSummary(
getResources().getStringArray(R.array.voice_input_modes_summary)
[mVoicePreference.findIndexOfValue(mVoicePreference.getValue())]);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
default:
Log.e(TAG, "unknown dialog " + id);
return null;
}
}
public void onDismiss(DialogInterface dialog) {
if (!mOkClicked) {
// This assumes that onPreferenceClick gets called first, and this if the user
// agreed after the warning, we set the mOkClicked value to true.
mVoicePreference.setValue(mVoiceModeOff);
}
}
private void updateVoicePreference() {
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/LatinIMESettings.java
|
Java
|
asf20
| 10,307
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.util.Log;
public class LatinIMEDebugSettings extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIMEDebugSettings";
private static final String DEBUG_MODE_KEY = "debug_mode";
private CheckBoxPreference mDebugMode;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_for_debug);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
mDebugMode = (CheckBoxPreference) findPreference(DEBUG_MODE_KEY);
updateDebugMode();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals(DEBUG_MODE_KEY)) {
if (mDebugMode != null) {
mDebugMode.setChecked(prefs.getBoolean(DEBUG_MODE_KEY, false));
updateDebugMode();
}
}
}
private void updateDebugMode() {
if (mDebugMode == null) {
return;
}
boolean isDebugMode = mDebugMode.isChecked();
String version = "";
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
version = "Version " + info.versionName;
} catch (NameNotFoundException e) {
Log.e(TAG, "Could not find version info.");
}
if (!isDebugMode) {
mDebugMode.setTitle(version);
mDebugMode.setSummary("");
} else {
mDebugMode.setTitle(getResources().getString(R.string.prefs_debug_mode));
mDebugMode.setSummary(version);
}
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/LatinIMEDebugSettings.java
|
Java
|
asf20
| 2,686
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pocketworkstation.pckeyboard;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.provider.UserDictionary.Words;
import android.util.Log;
public class UserDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
Words._ID,
Words.WORD,
Words.FREQUENCY
};
private static final int INDEX_WORD = 1;
private static final int INDEX_FREQUENCY = 2;
private static final String TAG = "HK/UserDictionary";
private ContentObserver mObserver;
private String mLocale;
public UserDictionary(Context context, String locale) {
super(context, Suggest.DIC_USER);
mLocale = locale;
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(Words.CONTENT_URI, true, mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
setRequiresReload(true);
}
});
loadDictionary();
}
@Override
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
super.close();
}
@Override
public void loadDictionaryAsync() {
Cursor cursor = getContext().getContentResolver()
.query(Words.CONTENT_URI, PROJECTION, "(locale IS NULL) or (locale=?)",
new String[] { mLocale }, null);
addWords(cursor);
}
/**
* Adds a word to the dictionary and makes it persistent.
* @param word the word to add. If the word is capitalized, then the dictionary will
* recognize it as a capitalized word when searched.
* @param frequency the frequency of occurrence of the word. A frequency of 255 is considered
* the highest.
* @TODO use a higher or float range for frequency
*/
@Override
public synchronized void addWord(String word, int frequency) {
// Force load the dictionary here synchronously
if (getRequiresReload()) loadDictionaryAsync();
// Safeguard against adding long words. Can cause stack overflow.
if (word.length() >= getMaxWordLength()) return;
super.addWord(word, frequency);
// Update the user dictionary provider
final ContentValues values = new ContentValues(5);
values.put(Words.WORD, word);
values.put(Words.FREQUENCY, frequency);
values.put(Words.LOCALE, mLocale);
values.put(Words.APP_ID, 0);
final ContentResolver contentResolver = getContext().getContentResolver();
new Thread("addWord") {
public void run() {
contentResolver.insert(Words.CONTENT_URI, values);
}
}.start();
// In case the above does a synchronous callback of the change observer
setRequiresReload(false);
}
@Override
public synchronized void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
super.getWords(codes, callback, nextLettersFrequencies);
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
return super.isValidWord(word);
}
private void addWords(Cursor cursor) {
if (cursor == null) {
Log.w(TAG, "Unexpected null cursor in addWords()");
return;
}
clearDictionary();
final int maxWordLength = getMaxWordLength();
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String word = cursor.getString(INDEX_WORD);
int frequency = cursor.getInt(INDEX_FREQUENCY);
// Safeguard against adding really long words. Stack may overflow due
// to recursion
if (word.length() < maxWordLength) {
super.addWord(word, frequency);
}
cursor.moveToNext();
}
}
cursor.close();
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/UserDictionary.java
|
Java
|
asf20
| 4,998
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
/**
* Backs up the Latin IME shared preferences.
*/
public class LatinIMEBackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
addHelper("shared_pref", new SharedPreferencesBackupHelper(this,
getPackageName() + "_preferences"));
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/LatinIMEBackupAgent.java
|
Java
|
asf20
| 1,058
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.Channels;
import java.util.Arrays;
import android.content.Context;
import android.util.Log;
/**
* Implements a static, compacted, binary dictionary of standard words.
*/
public class BinaryDictionary extends Dictionary {
/**
* There is difference between what java and native code can handle.
* This value should only be used in BinaryDictionary.java
* It is necessary to keep it at this value because some languages e.g. German have
* really long words.
*/
protected static final int MAX_WORD_LENGTH = 48;
private static final String TAG = "BinaryDictionary";
private static final int MAX_ALTERNATIVES = 16;
private static final int MAX_WORDS = 18;
private static final int MAX_BIGRAMS = 60;
private static final int TYPED_LETTER_MULTIPLIER = 2;
private static final boolean ENABLE_MISSED_CHARACTERS = true;
private int mDicTypeId;
private int mNativeDict;
private int mDictLength;
private int[] mInputCodes = new int[MAX_WORD_LENGTH * MAX_ALTERNATIVES];
private char[] mOutputChars = new char[MAX_WORD_LENGTH * MAX_WORDS];
private char[] mOutputChars_bigrams = new char[MAX_WORD_LENGTH * MAX_BIGRAMS];
private int[] mFrequencies = new int[MAX_WORDS];
private int[] mFrequencies_bigrams = new int[MAX_BIGRAMS];
// Keep a reference to the native dict direct buffer in Java to avoid
// unexpected deallocation of the direct buffer.
private ByteBuffer mNativeDictDirectBuffer;
static {
try {
System.loadLibrary("jni_pckeyboard");
Log.i("PCKeyboard", "loaded jni_pckeyboard");
} catch (UnsatisfiedLinkError ule) {
Log.e("BinaryDictionary", "Could not load native library jni_pckeyboard");
}
}
/**
* Create a dictionary from a raw resource file
* @param context application context for reading resources
* @param resId the resource containing the raw binary dictionary
*/
public BinaryDictionary(Context context, int[] resId, int dicTypeId) {
if (resId != null && resId.length > 0 && resId[0] != 0) {
loadDictionary(context, resId);
}
mDicTypeId = dicTypeId;
}
/**
* Create a dictionary from input streams
* @param context application context for reading resources
* @param streams the resource streams containing the raw binary dictionary
*/
public BinaryDictionary(Context context, InputStream[] streams, int dicTypeId) {
if (streams != null && streams.length > 0) {
loadDictionary(streams);
}
mDicTypeId = dicTypeId;
}
/**
* Create a dictionary from a byte buffer. This is used for testing.
* @param context application context for reading resources
* @param byteBuffer a ByteBuffer containing the binary dictionary
*/
public BinaryDictionary(Context context, ByteBuffer byteBuffer, int dicTypeId) {
if (byteBuffer != null) {
if (byteBuffer.isDirect()) {
mNativeDictDirectBuffer = byteBuffer;
} else {
mNativeDictDirectBuffer = ByteBuffer.allocateDirect(byteBuffer.capacity());
byteBuffer.rewind();
mNativeDictDirectBuffer.put(byteBuffer);
}
mDictLength = byteBuffer.capacity();
mNativeDict = openNative(mNativeDictDirectBuffer,
TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, mDictLength);
}
mDicTypeId = dicTypeId;
}
private native int openNative(ByteBuffer bb, int typedLetterMultiplier,
int fullWordMultiplier, int dictSize);
private native void closeNative(int dict);
private native boolean isValidWordNative(int nativeData, char[] word, int wordLength);
private native int getSuggestionsNative(int dict, int[] inputCodes, int codesSize,
char[] outputChars, int[] frequencies, int maxWordLength, int maxWords,
int maxAlternatives, int skipPos, int[] nextLettersFrequencies, int nextLettersSize);
private native int getBigramsNative(int dict, char[] prevWord, int prevWordLength,
int[] inputCodes, int inputCodesLength, char[] outputChars, int[] frequencies,
int maxWordLength, int maxBigrams, int maxAlternatives);
private final void loadDictionary(InputStream[] is) {
try {
// merging separated dictionary into one if dictionary is separated
int total = 0;
for (int i = 0; i < is.length; i++) {
total += is[i].available();
}
mNativeDictDirectBuffer =
ByteBuffer.allocateDirect(total).order(ByteOrder.nativeOrder());
int got = 0;
for (int i = 0; i < is.length; i++) {
got += Channels.newChannel(is[i]).read(mNativeDictDirectBuffer);
}
if (got != total) {
Log.e(TAG, "Read " + got + " bytes, expected " + total);
} else {
mNativeDict = openNative(mNativeDictDirectBuffer,
TYPED_LETTER_MULTIPLIER, FULL_WORD_FREQ_MULTIPLIER, total);
mDictLength = total;
}
if (mDictLength > 10000) Log.i("PCKeyboard", "Loaded dictionary, len=" + mDictLength);
} catch (IOException e) {
Log.w(TAG, "No available memory for binary dictionary");
} catch (UnsatisfiedLinkError e) {
Log.w(TAG, "Failed to load native dictionary", e);
} finally {
try {
if (is != null) {
for (int i = 0; i < is.length; i++) {
is[i].close();
}
}
} catch (IOException e) {
Log.w(TAG, "Failed to close input stream");
}
}
}
private final void loadDictionary(Context context, int[] resId) {
InputStream[] is = null;
is = new InputStream[resId.length];
for (int i = 0; i < resId.length; i++) {
is[i] = context.getResources().openRawResource(resId[i]);
}
loadDictionary(is);
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback, int[] nextLettersFrequencies) {
char[] chars = previousWord.toString().toCharArray();
Arrays.fill(mOutputChars_bigrams, (char) 0);
Arrays.fill(mFrequencies_bigrams, 0);
int codesSize = codes.size();
Arrays.fill(mInputCodes, -1);
int[] alternatives = codes.getCodesAt(0);
System.arraycopy(alternatives, 0, mInputCodes, 0,
Math.min(alternatives.length, MAX_ALTERNATIVES));
int count = getBigramsNative(mNativeDict, chars, chars.length, mInputCodes, codesSize,
mOutputChars_bigrams, mFrequencies_bigrams, MAX_WORD_LENGTH, MAX_BIGRAMS,
MAX_ALTERNATIVES);
for (int j = 0; j < count; j++) {
if (mFrequencies_bigrams[j] < 1) break;
int start = j * MAX_WORD_LENGTH;
int len = 0;
while (mOutputChars_bigrams[start + len] != 0) {
len++;
}
if (len > 0) {
callback.addWord(mOutputChars_bigrams, start, len, mFrequencies_bigrams[j],
mDicTypeId, DataType.BIGRAM);
}
}
}
@Override
public void getWords(final WordComposer codes, final WordCallback callback,
int[] nextLettersFrequencies) {
final int codesSize = codes.size();
// Won't deal with really long words.
if (codesSize > MAX_WORD_LENGTH - 1) return;
Arrays.fill(mInputCodes, -1);
for (int i = 0; i < codesSize; i++) {
int[] alternatives = codes.getCodesAt(i);
System.arraycopy(alternatives, 0, mInputCodes, i * MAX_ALTERNATIVES,
Math.min(alternatives.length, MAX_ALTERNATIVES));
}
Arrays.fill(mOutputChars, (char) 0);
Arrays.fill(mFrequencies, 0);
if (mNativeDict == 0)
return;
int count = getSuggestionsNative(mNativeDict, mInputCodes, codesSize,
mOutputChars, mFrequencies,
MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, -1,
nextLettersFrequencies,
nextLettersFrequencies != null ? nextLettersFrequencies.length : 0);
// If there aren't sufficient suggestions, search for words by allowing wild cards at
// the different character positions. This feature is not ready for prime-time as we need
// to figure out the best ranking for such words compared to proximity corrections and
// completions.
if (ENABLE_MISSED_CHARACTERS && count < 5) {
for (int skip = 0; skip < codesSize; skip++) {
int tempCount = getSuggestionsNative(mNativeDict, mInputCodes, codesSize,
mOutputChars, mFrequencies,
MAX_WORD_LENGTH, MAX_WORDS, MAX_ALTERNATIVES, skip,
null, 0);
count = Math.max(count, tempCount);
if (tempCount > 0) break;
}
}
for (int j = 0; j < count; j++) {
if (mFrequencies[j] < 1) break;
int start = j * MAX_WORD_LENGTH;
int len = 0;
while (mOutputChars[start + len] != 0) {
len++;
}
if (len > 0) {
callback.addWord(mOutputChars, start, len, mFrequencies[j], mDicTypeId,
DataType.UNIGRAM);
}
}
}
@Override
public boolean isValidWord(CharSequence word) {
if (word == null || mNativeDict == 0) return false;
char[] chars = word.toString().toCharArray();
return isValidWordNative(mNativeDict, chars, chars.length);
}
public int getSize() {
return mDictLength; // This value is initialized on the call to openNative()
}
@Override
public synchronized void close() {
if (mNativeDict != 0) {
closeNative(mNativeDict);
mNativeDict = 0;
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/BinaryDictionary.java
|
Java
|
asf20
| 11,174
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.pocketworkstation.pckeyboard;
import android.app.backup.BackupManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefScreenActions extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.prefs_actions);
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onDestroy() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
super.onDestroy();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
(new BackupManager(this)).dataChanged();
}
}
|
09bicsekanjam-clone
|
java/src/org/pocketworkstation/pckeyboard/PrefScreenActions.java
|
Java
|
asf20
| 1,584
|
#!/usr/bin/perl
binmode(STDOUT, ":utf8");
use Getopt::Std;
getopts('c') || die;
# Character used to display combining diacritics
my $placeholder = "\x{25cc}"; # dotted circle
#my $placeholder = "\x{25ab}"; # very small square
#my $placeholder = " "; # space
my %entities = (
'amp' => '&',
'lt' => '<',
'gt' => '>',
);
sub expand_entity {
my $in = shift;
if ($entities{$in}) {
return $entities{$in};
}
if ($in =~ /^#x(\w+)$/) {
return chr(hex($1));
} elsif ($in =~ /^#(\d+)$/) {
return chr(0+$1);
} else {
return '[???]';
}
}
sub prefix_diacritic {
my $in = shift;
return $in if $in =~ /^[\040-\176]/;
#$in =~ s/^(\p{Diacritic})/$placeholder$1/;
$in =~ s/^(\p{BidiClass:NSM})/$placeholder$1/;
return $in;
}
my @std_map = (
['key_tlde', 'key_ae01', 'key_ae02', 'key_ae03', 'key_ae04', 'key_ae05',
'key_ae06', 'key_ae07', 'key_ae08', 'key_ae09', 'key_ae10', 'key_ae11',
'key_ae12'],
['key_ad01', 'key_ad02', 'key_ad03', 'key_ad04', 'key_ad05', 'key_ad06',
'key_ad07', 'key_ad08', 'key_ad09', 'key_ad10', 'key_ad11', 'key_ad12',
'key_bksl'],
['key_ac01', 'key_ac02', 'key_ac03', 'key_ac04', 'key_ac05', 'key_ac06',
'key_ac07', 'key_ac08', 'key_ac09', 'key_ac10', 'key_ac11'],
['key_lsgt', 'key_ab01', 'key_ab02', 'key_ab03', 'key_ab04', 'key_ab05',
'key_ab06', 'key_ab07', 'key_ab08', 'key_ab09', 'key_ab10'],
);
my %edge = (
'key_ae12' => 1,
'key_bksl' => 1,
'key_ac11' => 1,
);
my %std_col = ();
my %std_row = ();
for (my $i = 0; $i < @std_map; ++$i) {
my @row = @{$std_map[$i]};
for (my $j = 0; $j < @row; ++$j) {
my $key = $row[$j];
$std_row{$key} = $i;
$std_col{$key} = $j;
}
}
sub read_strings {
my ($href, $file) = @_;
open(my $in, '<:utf8', $file) or die;
while (<$in>) {
#print;
if (/string\s+name="(.*)"\s*>(.*)</) {
my $name = $1;
my $chars = $2;
if ($chars =~ /\@string\/(\w+)/) {
$chars = $$href{$1};
} else {
print STDERR "ERROR: trailing backslash for $name; " if $chars =~ /[^\\]\\$/;
$chars =~ s/&(\#?\w+);/expand_entity($1)/eg;
$chars =~ s/\\(.)/$1/g; # Backslashes
}
$$href{$name} = $chars;
}
}
close $in;
}
sub main {
my %res = ();
foreach my $arg (@ARGV) {
read_strings(\%res, $arg);
}
my %found = ();
for (my $c = 33; $c < 127; ++$c) {
$found{chr($c)} = 0;
}
my $missing_digits = '';
my %keys = ();
foreach my $key (sort keys %res) {
next unless $key =~ /^key_/;
$keys{substr($key, 0, length('key_ae01'))} = 1;
my $chars = $res{$key};
## Replace entities
#$chars =~ s/\&(\w+)\;/entities{$1}/eg;
## Unescape backslashes
#$chars =~ s/\\(.)/$1/g;
for (my $i = 0; $i < length($chars); ++$i) {
my $char = substr($chars, $i, 1);
#print "$key $chars: char at $i = $char\n";
++ $found{$char};
}
if ($key =~ /key_ad(\d(\d))_alt/) {
my $keynum = $1;
next if $keynum > 10;
my $digit = $2;
#print "Digit check: key=$key chars=$chars\n";
$missing_digits .= $digit unless $chars =~ /$digit/;
}
}
if ($opt_c) {
my $prev_row = 0;
for my $key (sort {
$std_row{$a} <=> $std_row{$b}
||
$std_col{$a} <=> $std_col{$b}
||
$a cmp $b
} keys %keys) {
my $row = $std_row{$key};
if ($row != $prev_row) {
print "\n";
$prev_row = $row;
}
my $main = $res{$key . '_main'};
my $shift = $res{$key . '_shift'};
my $alt = $res{$key . '_alt'};
$main = prefix_diacritic($main);
$shift = prefix_diacritic($shift);
my @alt_list = split('', $alt);
@alt_list = map { prefix_diacritic($_) } @alt_list;
my $alt_join = join(' ', @alt_list);
print "$key\t$main\t$shift\t$alt_join\n";
}
}
my $missing = '';
if ($missing_digits ne '') {
$missing .= "Digits '$missing_digits', ";
}
foreach my $c (sort keys %found) {
if ($found{$c} == 0) {
$missing .= $c;
}
}
if (length($missing) > 0) {
print STDERR "Missing: $missing\n";
} else {
print STDERR "All present.\n" unless $opt_c;
}
}
&main();
|
09bicsekanjam-clone
|
java/CheckMap.pl
|
Raku
|
asf20
| 4,184
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
namespace latinime {
struct LatinCapitalSmallPair {
unsigned short capital;
unsigned short small;
};
// Generated from http://unicode.org/Public/UNIDATA/UnicodeData.txt
//
// 1. Run the following code. Bascially taken from
// Dictionary::toLowerCase(unsigned short c) in dictionary.cpp.
// Then, get the list of chars where cc != ccc.
//
// unsigned short c, cc, ccc, ccc2;
// for (c = 0; c < 0xFFFF ; c++) {
// if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
// cc = BASE_CHARS[c];
// } else {
// cc = c;
// }
//
// // tolower
// int isBase = 0;
// if (cc >='A' && cc <= 'Z') {
// ccc = (cc | 0x20);
// ccc2 = ccc;
// isBase = 1;
// } else if (cc > 0x7F) {
// ccc = u_tolower(cc);
// ccc2 = latin_tolower(cc);
// } else {
// ccc = cc;
// ccc2 = ccc;
// }
// if (!isBase && cc != ccc) {
// wprintf(L" 0x%04X => 0x%04X => 0x%04X %lc => %lc => %lc \n",
// c, cc, ccc, c, cc, ccc);
// //assert(ccc == ccc2);
// }
// }
//
// Initially, started with an empty latin_tolower() as below.
//
// unsigned short latin_tolower(unsigned short c) {
// return c;
// }
//
//
// 2. Process the list obtained by 1 by the following perl script and apply
// 'sort -u' as well. Get the SORTED_CHAR_MAP[].
// Note that '$1' in the perl script is 'cc' in the above C code.
//
// while(<>) {
// / 0x\w* => 0x(\w*) =/;
// open(HDL, "grep -iw ^" . $1 . " UnicodeData.txt | ");
// $line = <HDL>;
// chomp $line;
// @cols = split(/;/, $line);
// print " { 0x$1, 0x$cols[13] }, // $cols[1]\n";
// }
//
//
// 3. Update the latin_tolower() function above with SORTED_CHAR_MAP. Enable
// the assert(ccc == ccc2) above and confirm the function exits successfully.
//
static const struct LatinCapitalSmallPair SORTED_CHAR_MAP[] = {
{ 0x00C4, 0x00E4 }, // LATIN CAPITAL LETTER A WITH DIAERESIS
{ 0x00C5, 0x00E5 }, // LATIN CAPITAL LETTER A WITH RING ABOVE
{ 0x00C6, 0x00E6 }, // LATIN CAPITAL LETTER AE
{ 0x00D0, 0x00F0 }, // LATIN CAPITAL LETTER ETH
{ 0x00D5, 0x00F5 }, // LATIN CAPITAL LETTER O WITH TILDE
{ 0x00D6, 0x00F6 }, // LATIN CAPITAL LETTER O WITH DIAERESIS
{ 0x00D8, 0x00F8 }, // LATIN CAPITAL LETTER O WITH STROKE
{ 0x00DC, 0x00FC }, // LATIN CAPITAL LETTER U WITH DIAERESIS
{ 0x00DE, 0x00FE }, // LATIN CAPITAL LETTER THORN
{ 0x0110, 0x0111 }, // LATIN CAPITAL LETTER D WITH STROKE
{ 0x0126, 0x0127 }, // LATIN CAPITAL LETTER H WITH STROKE
{ 0x0141, 0x0142 }, // LATIN CAPITAL LETTER L WITH STROKE
{ 0x014A, 0x014B }, // LATIN CAPITAL LETTER ENG
{ 0x0152, 0x0153 }, // LATIN CAPITAL LIGATURE OE
{ 0x0166, 0x0167 }, // LATIN CAPITAL LETTER T WITH STROKE
{ 0x0181, 0x0253 }, // LATIN CAPITAL LETTER B WITH HOOK
{ 0x0182, 0x0183 }, // LATIN CAPITAL LETTER B WITH TOPBAR
{ 0x0184, 0x0185 }, // LATIN CAPITAL LETTER TONE SIX
{ 0x0186, 0x0254 }, // LATIN CAPITAL LETTER OPEN O
{ 0x0187, 0x0188 }, // LATIN CAPITAL LETTER C WITH HOOK
{ 0x0189, 0x0256 }, // LATIN CAPITAL LETTER AFRICAN D
{ 0x018A, 0x0257 }, // LATIN CAPITAL LETTER D WITH HOOK
{ 0x018B, 0x018C }, // LATIN CAPITAL LETTER D WITH TOPBAR
{ 0x018E, 0x01DD }, // LATIN CAPITAL LETTER REVERSED E
{ 0x018F, 0x0259 }, // LATIN CAPITAL LETTER SCHWA
{ 0x0190, 0x025B }, // LATIN CAPITAL LETTER OPEN E
{ 0x0191, 0x0192 }, // LATIN CAPITAL LETTER F WITH HOOK
{ 0x0193, 0x0260 }, // LATIN CAPITAL LETTER G WITH HOOK
{ 0x0194, 0x0263 }, // LATIN CAPITAL LETTER GAMMA
{ 0x0196, 0x0269 }, // LATIN CAPITAL LETTER IOTA
{ 0x0197, 0x0268 }, // LATIN CAPITAL LETTER I WITH STROKE
{ 0x0198, 0x0199 }, // LATIN CAPITAL LETTER K WITH HOOK
{ 0x019C, 0x026F }, // LATIN CAPITAL LETTER TURNED M
{ 0x019D, 0x0272 }, // LATIN CAPITAL LETTER N WITH LEFT HOOK
{ 0x019F, 0x0275 }, // LATIN CAPITAL LETTER O WITH MIDDLE TILDE
{ 0x01A2, 0x01A3 }, // LATIN CAPITAL LETTER OI
{ 0x01A4, 0x01A5 }, // LATIN CAPITAL LETTER P WITH HOOK
{ 0x01A6, 0x0280 }, // LATIN LETTER YR
{ 0x01A7, 0x01A8 }, // LATIN CAPITAL LETTER TONE TWO
{ 0x01A9, 0x0283 }, // LATIN CAPITAL LETTER ESH
{ 0x01AC, 0x01AD }, // LATIN CAPITAL LETTER T WITH HOOK
{ 0x01AE, 0x0288 }, // LATIN CAPITAL LETTER T WITH RETROFLEX HOOK
{ 0x01B1, 0x028A }, // LATIN CAPITAL LETTER UPSILON
{ 0x01B2, 0x028B }, // LATIN CAPITAL LETTER V WITH HOOK
{ 0x01B3, 0x01B4 }, // LATIN CAPITAL LETTER Y WITH HOOK
{ 0x01B5, 0x01B6 }, // LATIN CAPITAL LETTER Z WITH STROKE
{ 0x01B7, 0x0292 }, // LATIN CAPITAL LETTER EZH
{ 0x01B8, 0x01B9 }, // LATIN CAPITAL LETTER EZH REVERSED
{ 0x01BC, 0x01BD }, // LATIN CAPITAL LETTER TONE FIVE
{ 0x01E4, 0x01E5 }, // LATIN CAPITAL LETTER G WITH STROKE
{ 0x01EA, 0x01EB }, // LATIN CAPITAL LETTER O WITH OGONEK
{ 0x01F6, 0x0195 }, // LATIN CAPITAL LETTER HWAIR
{ 0x01F7, 0x01BF }, // LATIN CAPITAL LETTER WYNN
{ 0x021C, 0x021D }, // LATIN CAPITAL LETTER YOGH
{ 0x0220, 0x019E }, // LATIN CAPITAL LETTER N WITH LONG RIGHT LEG
{ 0x0222, 0x0223 }, // LATIN CAPITAL LETTER OU
{ 0x0224, 0x0225 }, // LATIN CAPITAL LETTER Z WITH HOOK
{ 0x0226, 0x0227 }, // LATIN CAPITAL LETTER A WITH DOT ABOVE
{ 0x022E, 0x022F }, // LATIN CAPITAL LETTER O WITH DOT ABOVE
{ 0x023A, 0x2C65 }, // LATIN CAPITAL LETTER A WITH STROKE
{ 0x023B, 0x023C }, // LATIN CAPITAL LETTER C WITH STROKE
{ 0x023D, 0x019A }, // LATIN CAPITAL LETTER L WITH BAR
{ 0x023E, 0x2C66 }, // LATIN CAPITAL LETTER T WITH DIAGONAL STROKE
{ 0x0241, 0x0242 }, // LATIN CAPITAL LETTER GLOTTAL STOP
{ 0x0243, 0x0180 }, // LATIN CAPITAL LETTER B WITH STROKE
{ 0x0244, 0x0289 }, // LATIN CAPITAL LETTER U BAR
{ 0x0245, 0x028C }, // LATIN CAPITAL LETTER TURNED V
{ 0x0246, 0x0247 }, // LATIN CAPITAL LETTER E WITH STROKE
{ 0x0248, 0x0249 }, // LATIN CAPITAL LETTER J WITH STROKE
{ 0x024A, 0x024B }, // LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL
{ 0x024C, 0x024D }, // LATIN CAPITAL LETTER R WITH STROKE
{ 0x024E, 0x024F }, // LATIN CAPITAL LETTER Y WITH STROKE
{ 0x0370, 0x0371 }, // GREEK CAPITAL LETTER HETA
{ 0x0372, 0x0373 }, // GREEK CAPITAL LETTER ARCHAIC SAMPI
{ 0x0376, 0x0377 }, // GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA
{ 0x0391, 0x03B1 }, // GREEK CAPITAL LETTER ALPHA
{ 0x0392, 0x03B2 }, // GREEK CAPITAL LETTER BETA
{ 0x0393, 0x03B3 }, // GREEK CAPITAL LETTER GAMMA
{ 0x0394, 0x03B4 }, // GREEK CAPITAL LETTER DELTA
{ 0x0395, 0x03B5 }, // GREEK CAPITAL LETTER EPSILON
{ 0x0396, 0x03B6 }, // GREEK CAPITAL LETTER ZETA
{ 0x0397, 0x03B7 }, // GREEK CAPITAL LETTER ETA
{ 0x0398, 0x03B8 }, // GREEK CAPITAL LETTER THETA
{ 0x0399, 0x03B9 }, // GREEK CAPITAL LETTER IOTA
{ 0x039A, 0x03BA }, // GREEK CAPITAL LETTER KAPPA
{ 0x039B, 0x03BB }, // GREEK CAPITAL LETTER LAMDA
{ 0x039C, 0x03BC }, // GREEK CAPITAL LETTER MU
{ 0x039D, 0x03BD }, // GREEK CAPITAL LETTER NU
{ 0x039E, 0x03BE }, // GREEK CAPITAL LETTER XI
{ 0x039F, 0x03BF }, // GREEK CAPITAL LETTER OMICRON
{ 0x03A0, 0x03C0 }, // GREEK CAPITAL LETTER PI
{ 0x03A1, 0x03C1 }, // GREEK CAPITAL LETTER RHO
{ 0x03A3, 0x03C3 }, // GREEK CAPITAL LETTER SIGMA
{ 0x03A4, 0x03C4 }, // GREEK CAPITAL LETTER TAU
{ 0x03A5, 0x03C5 }, // GREEK CAPITAL LETTER UPSILON
{ 0x03A6, 0x03C6 }, // GREEK CAPITAL LETTER PHI
{ 0x03A7, 0x03C7 }, // GREEK CAPITAL LETTER CHI
{ 0x03A8, 0x03C8 }, // GREEK CAPITAL LETTER PSI
{ 0x03A9, 0x03C9 }, // GREEK CAPITAL LETTER OMEGA
{ 0x03CF, 0x03D7 }, // GREEK CAPITAL KAI SYMBOL
{ 0x03D8, 0x03D9 }, // GREEK LETTER ARCHAIC KOPPA
{ 0x03DA, 0x03DB }, // GREEK LETTER STIGMA
{ 0x03DC, 0x03DD }, // GREEK LETTER DIGAMMA
{ 0x03DE, 0x03DF }, // GREEK LETTER KOPPA
{ 0x03E0, 0x03E1 }, // GREEK LETTER SAMPI
{ 0x03E2, 0x03E3 }, // COPTIC CAPITAL LETTER SHEI
{ 0x03E4, 0x03E5 }, // COPTIC CAPITAL LETTER FEI
{ 0x03E6, 0x03E7 }, // COPTIC CAPITAL LETTER KHEI
{ 0x03E8, 0x03E9 }, // COPTIC CAPITAL LETTER HORI
{ 0x03EA, 0x03EB }, // COPTIC CAPITAL LETTER GANGIA
{ 0x03EC, 0x03ED }, // COPTIC CAPITAL LETTER SHIMA
{ 0x03EE, 0x03EF }, // COPTIC CAPITAL LETTER DEI
{ 0x03F7, 0x03F8 }, // GREEK CAPITAL LETTER SHO
{ 0x03FA, 0x03FB }, // GREEK CAPITAL LETTER SAN
{ 0x03FD, 0x037B }, // GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL
{ 0x03FE, 0x037C }, // GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL
{ 0x03FF, 0x037D }, // GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL
{ 0x0402, 0x0452 }, // CYRILLIC CAPITAL LETTER DJE
{ 0x0404, 0x0454 }, // CYRILLIC CAPITAL LETTER UKRAINIAN IE
{ 0x0405, 0x0455 }, // CYRILLIC CAPITAL LETTER DZE
{ 0x0406, 0x0456 }, // CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
{ 0x0408, 0x0458 }, // CYRILLIC CAPITAL LETTER JE
{ 0x0409, 0x0459 }, // CYRILLIC CAPITAL LETTER LJE
{ 0x040A, 0x045A }, // CYRILLIC CAPITAL LETTER NJE
{ 0x040B, 0x045B }, // CYRILLIC CAPITAL LETTER TSHE
{ 0x040F, 0x045F }, // CYRILLIC CAPITAL LETTER DZHE
{ 0x0410, 0x0430 }, // CYRILLIC CAPITAL LETTER A
{ 0x0411, 0x0431 }, // CYRILLIC CAPITAL LETTER BE
{ 0x0412, 0x0432 }, // CYRILLIC CAPITAL LETTER VE
{ 0x0413, 0x0433 }, // CYRILLIC CAPITAL LETTER GHE
{ 0x0414, 0x0434 }, // CYRILLIC CAPITAL LETTER DE
{ 0x0415, 0x0435 }, // CYRILLIC CAPITAL LETTER IE
{ 0x0416, 0x0436 }, // CYRILLIC CAPITAL LETTER ZHE
{ 0x0417, 0x0437 }, // CYRILLIC CAPITAL LETTER ZE
{ 0x0418, 0x0438 }, // CYRILLIC CAPITAL LETTER I
{ 0x041A, 0x043A }, // CYRILLIC CAPITAL LETTER KA
{ 0x041B, 0x043B }, // CYRILLIC CAPITAL LETTER EL
{ 0x041C, 0x043C }, // CYRILLIC CAPITAL LETTER EM
{ 0x041D, 0x043D }, // CYRILLIC CAPITAL LETTER EN
{ 0x041E, 0x043E }, // CYRILLIC CAPITAL LETTER O
{ 0x041F, 0x043F }, // CYRILLIC CAPITAL LETTER PE
{ 0x0420, 0x0440 }, // CYRILLIC CAPITAL LETTER ER
{ 0x0421, 0x0441 }, // CYRILLIC CAPITAL LETTER ES
{ 0x0422, 0x0442 }, // CYRILLIC CAPITAL LETTER TE
{ 0x0423, 0x0443 }, // CYRILLIC CAPITAL LETTER U
{ 0x0424, 0x0444 }, // CYRILLIC CAPITAL LETTER EF
{ 0x0425, 0x0445 }, // CYRILLIC CAPITAL LETTER HA
{ 0x0426, 0x0446 }, // CYRILLIC CAPITAL LETTER TSE
{ 0x0427, 0x0447 }, // CYRILLIC CAPITAL LETTER CHE
{ 0x0428, 0x0448 }, // CYRILLIC CAPITAL LETTER SHA
{ 0x0429, 0x0449 }, // CYRILLIC CAPITAL LETTER SHCHA
{ 0x042A, 0x044A }, // CYRILLIC CAPITAL LETTER HARD SIGN
{ 0x042B, 0x044B }, // CYRILLIC CAPITAL LETTER YERU
{ 0x042C, 0x044C }, // CYRILLIC CAPITAL LETTER SOFT SIGN
{ 0x042D, 0x044D }, // CYRILLIC CAPITAL LETTER E
{ 0x042E, 0x044E }, // CYRILLIC CAPITAL LETTER YU
{ 0x042F, 0x044F }, // CYRILLIC CAPITAL LETTER YA
{ 0x0460, 0x0461 }, // CYRILLIC CAPITAL LETTER OMEGA
{ 0x0462, 0x0463 }, // CYRILLIC CAPITAL LETTER YAT
{ 0x0464, 0x0465 }, // CYRILLIC CAPITAL LETTER IOTIFIED E
{ 0x0466, 0x0467 }, // CYRILLIC CAPITAL LETTER LITTLE YUS
{ 0x0468, 0x0469 }, // CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS
{ 0x046A, 0x046B }, // CYRILLIC CAPITAL LETTER BIG YUS
{ 0x046C, 0x046D }, // CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS
{ 0x046E, 0x046F }, // CYRILLIC CAPITAL LETTER KSI
{ 0x0470, 0x0471 }, // CYRILLIC CAPITAL LETTER PSI
{ 0x0472, 0x0473 }, // CYRILLIC CAPITAL LETTER FITA
{ 0x0474, 0x0475 }, // CYRILLIC CAPITAL LETTER IZHITSA
{ 0x0478, 0x0479 }, // CYRILLIC CAPITAL LETTER UK
{ 0x047A, 0x047B }, // CYRILLIC CAPITAL LETTER ROUND OMEGA
{ 0x047C, 0x047D }, // CYRILLIC CAPITAL LETTER OMEGA WITH TITLO
{ 0x047E, 0x047F }, // CYRILLIC CAPITAL LETTER OT
{ 0x0480, 0x0481 }, // CYRILLIC CAPITAL LETTER KOPPA
{ 0x048A, 0x048B }, // CYRILLIC CAPITAL LETTER SHORT I WITH TAIL
{ 0x048C, 0x048D }, // CYRILLIC CAPITAL LETTER SEMISOFT SIGN
{ 0x048E, 0x048F }, // CYRILLIC CAPITAL LETTER ER WITH TICK
{ 0x0490, 0x0491 }, // CYRILLIC CAPITAL LETTER GHE WITH UPTURN
{ 0x0492, 0x0493 }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE
{ 0x0494, 0x0495 }, // CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK
{ 0x0496, 0x0497 }, // CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER
{ 0x0498, 0x0499 }, // CYRILLIC CAPITAL LETTER ZE WITH DESCENDER
{ 0x049A, 0x049B }, // CYRILLIC CAPITAL LETTER KA WITH DESCENDER
{ 0x049C, 0x049D }, // CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE
{ 0x049E, 0x049F }, // CYRILLIC CAPITAL LETTER KA WITH STROKE
{ 0x04A0, 0x04A1 }, // CYRILLIC CAPITAL LETTER BASHKIR KA
{ 0x04A2, 0x04A3 }, // CYRILLIC CAPITAL LETTER EN WITH DESCENDER
{ 0x04A4, 0x04A5 }, // CYRILLIC CAPITAL LIGATURE EN GHE
{ 0x04A6, 0x04A7 }, // CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK
{ 0x04A8, 0x04A9 }, // CYRILLIC CAPITAL LETTER ABKHASIAN HA
{ 0x04AA, 0x04AB }, // CYRILLIC CAPITAL LETTER ES WITH DESCENDER
{ 0x04AC, 0x04AD }, // CYRILLIC CAPITAL LETTER TE WITH DESCENDER
{ 0x04AE, 0x04AF }, // CYRILLIC CAPITAL LETTER STRAIGHT U
{ 0x04B0, 0x04B1 }, // CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE
{ 0x04B2, 0x04B3 }, // CYRILLIC CAPITAL LETTER HA WITH DESCENDER
{ 0x04B4, 0x04B5 }, // CYRILLIC CAPITAL LIGATURE TE TSE
{ 0x04B6, 0x04B7 }, // CYRILLIC CAPITAL LETTER CHE WITH DESCENDER
{ 0x04B8, 0x04B9 }, // CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE
{ 0x04BA, 0x04BB }, // CYRILLIC CAPITAL LETTER SHHA
{ 0x04BC, 0x04BD }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE
{ 0x04BE, 0x04BF }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER
{ 0x04C0, 0x04CF }, // CYRILLIC LETTER PALOCHKA
{ 0x04C3, 0x04C4 }, // CYRILLIC CAPITAL LETTER KA WITH HOOK
{ 0x04C5, 0x04C6 }, // CYRILLIC CAPITAL LETTER EL WITH TAIL
{ 0x04C7, 0x04C8 }, // CYRILLIC CAPITAL LETTER EN WITH HOOK
{ 0x04C9, 0x04CA }, // CYRILLIC CAPITAL LETTER EN WITH TAIL
{ 0x04CB, 0x04CC }, // CYRILLIC CAPITAL LETTER KHAKASSIAN CHE
{ 0x04CD, 0x04CE }, // CYRILLIC CAPITAL LETTER EM WITH TAIL
{ 0x04D4, 0x04D5 }, // CYRILLIC CAPITAL LIGATURE A IE
{ 0x04D8, 0x04D9 }, // CYRILLIC CAPITAL LETTER SCHWA
{ 0x04E0, 0x04E1 }, // CYRILLIC CAPITAL LETTER ABKHASIAN DZE
{ 0x04E8, 0x04E9 }, // CYRILLIC CAPITAL LETTER BARRED O
{ 0x04F6, 0x04F7 }, // CYRILLIC CAPITAL LETTER GHE WITH DESCENDER
{ 0x04FA, 0x04FB }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK
{ 0x04FC, 0x04FD }, // CYRILLIC CAPITAL LETTER HA WITH HOOK
{ 0x04FE, 0x04FF }, // CYRILLIC CAPITAL LETTER HA WITH STROKE
{ 0x0500, 0x0501 }, // CYRILLIC CAPITAL LETTER KOMI DE
{ 0x0502, 0x0503 }, // CYRILLIC CAPITAL LETTER KOMI DJE
{ 0x0504, 0x0505 }, // CYRILLIC CAPITAL LETTER KOMI ZJE
{ 0x0506, 0x0507 }, // CYRILLIC CAPITAL LETTER KOMI DZJE
{ 0x0508, 0x0509 }, // CYRILLIC CAPITAL LETTER KOMI LJE
{ 0x050A, 0x050B }, // CYRILLIC CAPITAL LETTER KOMI NJE
{ 0x050C, 0x050D }, // CYRILLIC CAPITAL LETTER KOMI SJE
{ 0x050E, 0x050F }, // CYRILLIC CAPITAL LETTER KOMI TJE
{ 0x0510, 0x0511 }, // CYRILLIC CAPITAL LETTER REVERSED ZE
{ 0x0512, 0x0513 }, // CYRILLIC CAPITAL LETTER EL WITH HOOK
{ 0x0514, 0x0515 }, // CYRILLIC CAPITAL LETTER LHA
{ 0x0516, 0x0517 }, // CYRILLIC CAPITAL LETTER RHA
{ 0x0518, 0x0519 }, // CYRILLIC CAPITAL LETTER YAE
{ 0x051A, 0x051B }, // CYRILLIC CAPITAL LETTER QA
{ 0x051C, 0x051D }, // CYRILLIC CAPITAL LETTER WE
{ 0x051E, 0x051F }, // CYRILLIC CAPITAL LETTER ALEUT KA
{ 0x0520, 0x0521 }, // CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK
{ 0x0522, 0x0523 }, // CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK
{ 0x0524, 0x0525 }, // CYRILLIC CAPITAL LETTER PE WITH DESCENDER
{ 0x0531, 0x0561 }, // ARMENIAN CAPITAL LETTER AYB
{ 0x0532, 0x0562 }, // ARMENIAN CAPITAL LETTER BEN
{ 0x0533, 0x0563 }, // ARMENIAN CAPITAL LETTER GIM
{ 0x0534, 0x0564 }, // ARMENIAN CAPITAL LETTER DA
{ 0x0535, 0x0565 }, // ARMENIAN CAPITAL LETTER ECH
{ 0x0536, 0x0566 }, // ARMENIAN CAPITAL LETTER ZA
{ 0x0537, 0x0567 }, // ARMENIAN CAPITAL LETTER EH
{ 0x0538, 0x0568 }, // ARMENIAN CAPITAL LETTER ET
{ 0x0539, 0x0569 }, // ARMENIAN CAPITAL LETTER TO
{ 0x053A, 0x056A }, // ARMENIAN CAPITAL LETTER ZHE
{ 0x053B, 0x056B }, // ARMENIAN CAPITAL LETTER INI
{ 0x053C, 0x056C }, // ARMENIAN CAPITAL LETTER LIWN
{ 0x053D, 0x056D }, // ARMENIAN CAPITAL LETTER XEH
{ 0x053E, 0x056E }, // ARMENIAN CAPITAL LETTER CA
{ 0x053F, 0x056F }, // ARMENIAN CAPITAL LETTER KEN
{ 0x0540, 0x0570 }, // ARMENIAN CAPITAL LETTER HO
{ 0x0541, 0x0571 }, // ARMENIAN CAPITAL LETTER JA
{ 0x0542, 0x0572 }, // ARMENIAN CAPITAL LETTER GHAD
{ 0x0543, 0x0573 }, // ARMENIAN CAPITAL LETTER CHEH
{ 0x0544, 0x0574 }, // ARMENIAN CAPITAL LETTER MEN
{ 0x0545, 0x0575 }, // ARMENIAN CAPITAL LETTER YI
{ 0x0546, 0x0576 }, // ARMENIAN CAPITAL LETTER NOW
{ 0x0547, 0x0577 }, // ARMENIAN CAPITAL LETTER SHA
{ 0x0548, 0x0578 }, // ARMENIAN CAPITAL LETTER VO
{ 0x0549, 0x0579 }, // ARMENIAN CAPITAL LETTER CHA
{ 0x054A, 0x057A }, // ARMENIAN CAPITAL LETTER PEH
{ 0x054B, 0x057B }, // ARMENIAN CAPITAL LETTER JHEH
{ 0x054C, 0x057C }, // ARMENIAN CAPITAL LETTER RA
{ 0x054D, 0x057D }, // ARMENIAN CAPITAL LETTER SEH
{ 0x054E, 0x057E }, // ARMENIAN CAPITAL LETTER VEW
{ 0x054F, 0x057F }, // ARMENIAN CAPITAL LETTER TIWN
{ 0x0550, 0x0580 }, // ARMENIAN CAPITAL LETTER REH
{ 0x0551, 0x0581 }, // ARMENIAN CAPITAL LETTER CO
{ 0x0552, 0x0582 }, // ARMENIAN CAPITAL LETTER YIWN
{ 0x0553, 0x0583 }, // ARMENIAN CAPITAL LETTER PIWR
{ 0x0554, 0x0584 }, // ARMENIAN CAPITAL LETTER KEH
{ 0x0555, 0x0585 }, // ARMENIAN CAPITAL LETTER OH
{ 0x0556, 0x0586 }, // ARMENIAN CAPITAL LETTER FEH
{ 0x10A0, 0x2D00 }, // GEORGIAN CAPITAL LETTER AN
{ 0x10A1, 0x2D01 }, // GEORGIAN CAPITAL LETTER BAN
{ 0x10A2, 0x2D02 }, // GEORGIAN CAPITAL LETTER GAN
{ 0x10A3, 0x2D03 }, // GEORGIAN CAPITAL LETTER DON
{ 0x10A4, 0x2D04 }, // GEORGIAN CAPITAL LETTER EN
{ 0x10A5, 0x2D05 }, // GEORGIAN CAPITAL LETTER VIN
{ 0x10A6, 0x2D06 }, // GEORGIAN CAPITAL LETTER ZEN
{ 0x10A7, 0x2D07 }, // GEORGIAN CAPITAL LETTER TAN
{ 0x10A8, 0x2D08 }, // GEORGIAN CAPITAL LETTER IN
{ 0x10A9, 0x2D09 }, // GEORGIAN CAPITAL LETTER KAN
{ 0x10AA, 0x2D0A }, // GEORGIAN CAPITAL LETTER LAS
{ 0x10AB, 0x2D0B }, // GEORGIAN CAPITAL LETTER MAN
{ 0x10AC, 0x2D0C }, // GEORGIAN CAPITAL LETTER NAR
{ 0x10AD, 0x2D0D }, // GEORGIAN CAPITAL LETTER ON
{ 0x10AE, 0x2D0E }, // GEORGIAN CAPITAL LETTER PAR
{ 0x10AF, 0x2D0F }, // GEORGIAN CAPITAL LETTER ZHAR
{ 0x10B0, 0x2D10 }, // GEORGIAN CAPITAL LETTER RAE
{ 0x10B1, 0x2D11 }, // GEORGIAN CAPITAL LETTER SAN
{ 0x10B2, 0x2D12 }, // GEORGIAN CAPITAL LETTER TAR
{ 0x10B3, 0x2D13 }, // GEORGIAN CAPITAL LETTER UN
{ 0x10B4, 0x2D14 }, // GEORGIAN CAPITAL LETTER PHAR
{ 0x10B5, 0x2D15 }, // GEORGIAN CAPITAL LETTER KHAR
{ 0x10B6, 0x2D16 }, // GEORGIAN CAPITAL LETTER GHAN
{ 0x10B7, 0x2D17 }, // GEORGIAN CAPITAL LETTER QAR
{ 0x10B8, 0x2D18 }, // GEORGIAN CAPITAL LETTER SHIN
{ 0x10B9, 0x2D19 }, // GEORGIAN CAPITAL LETTER CHIN
{ 0x10BA, 0x2D1A }, // GEORGIAN CAPITAL LETTER CAN
{ 0x10BB, 0x2D1B }, // GEORGIAN CAPITAL LETTER JIL
{ 0x10BC, 0x2D1C }, // GEORGIAN CAPITAL LETTER CIL
{ 0x10BD, 0x2D1D }, // GEORGIAN CAPITAL LETTER CHAR
{ 0x10BE, 0x2D1E }, // GEORGIAN CAPITAL LETTER XAN
{ 0x10BF, 0x2D1F }, // GEORGIAN CAPITAL LETTER JHAN
{ 0x10C0, 0x2D20 }, // GEORGIAN CAPITAL LETTER HAE
{ 0x10C1, 0x2D21 }, // GEORGIAN CAPITAL LETTER HE
{ 0x10C2, 0x2D22 }, // GEORGIAN CAPITAL LETTER HIE
{ 0x10C3, 0x2D23 }, // GEORGIAN CAPITAL LETTER WE
{ 0x10C4, 0x2D24 }, // GEORGIAN CAPITAL LETTER HAR
{ 0x10C5, 0x2D25 }, // GEORGIAN CAPITAL LETTER HOE
{ 0x1E00, 0x1E01 }, // LATIN CAPITAL LETTER A WITH RING BELOW
{ 0x1E02, 0x1E03 }, // LATIN CAPITAL LETTER B WITH DOT ABOVE
{ 0x1E04, 0x1E05 }, // LATIN CAPITAL LETTER B WITH DOT BELOW
{ 0x1E06, 0x1E07 }, // LATIN CAPITAL LETTER B WITH LINE BELOW
{ 0x1E08, 0x1E09 }, // LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE
{ 0x1E0A, 0x1E0B }, // LATIN CAPITAL LETTER D WITH DOT ABOVE
{ 0x1E0C, 0x1E0D }, // LATIN CAPITAL LETTER D WITH DOT BELOW
{ 0x1E0E, 0x1E0F }, // LATIN CAPITAL LETTER D WITH LINE BELOW
{ 0x1E10, 0x1E11 }, // LATIN CAPITAL LETTER D WITH CEDILLA
{ 0x1E12, 0x1E13 }, // LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW
{ 0x1E14, 0x1E15 }, // LATIN CAPITAL LETTER E WITH MACRON AND GRAVE
{ 0x1E16, 0x1E17 }, // LATIN CAPITAL LETTER E WITH MACRON AND ACUTE
{ 0x1E18, 0x1E19 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW
{ 0x1E1A, 0x1E1B }, // LATIN CAPITAL LETTER E WITH TILDE BELOW
{ 0x1E1C, 0x1E1D }, // LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE
{ 0x1E1E, 0x1E1F }, // LATIN CAPITAL LETTER F WITH DOT ABOVE
{ 0x1E20, 0x1E21 }, // LATIN CAPITAL LETTER G WITH MACRON
{ 0x1E22, 0x1E23 }, // LATIN CAPITAL LETTER H WITH DOT ABOVE
{ 0x1E24, 0x1E25 }, // LATIN CAPITAL LETTER H WITH DOT BELOW
{ 0x1E26, 0x1E27 }, // LATIN CAPITAL LETTER H WITH DIAERESIS
{ 0x1E28, 0x1E29 }, // LATIN CAPITAL LETTER H WITH CEDILLA
{ 0x1E2A, 0x1E2B }, // LATIN CAPITAL LETTER H WITH BREVE BELOW
{ 0x1E2C, 0x1E2D }, // LATIN CAPITAL LETTER I WITH TILDE BELOW
{ 0x1E2E, 0x1E2F }, // LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE
{ 0x1E30, 0x1E31 }, // LATIN CAPITAL LETTER K WITH ACUTE
{ 0x1E32, 0x1E33 }, // LATIN CAPITAL LETTER K WITH DOT BELOW
{ 0x1E34, 0x1E35 }, // LATIN CAPITAL LETTER K WITH LINE BELOW
{ 0x1E36, 0x1E37 }, // LATIN CAPITAL LETTER L WITH DOT BELOW
{ 0x1E38, 0x1E39 }, // LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON
{ 0x1E3A, 0x1E3B }, // LATIN CAPITAL LETTER L WITH LINE BELOW
{ 0x1E3C, 0x1E3D }, // LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW
{ 0x1E3E, 0x1E3F }, // LATIN CAPITAL LETTER M WITH ACUTE
{ 0x1E40, 0x1E41 }, // LATIN CAPITAL LETTER M WITH DOT ABOVE
{ 0x1E42, 0x1E43 }, // LATIN CAPITAL LETTER M WITH DOT BELOW
{ 0x1E44, 0x1E45 }, // LATIN CAPITAL LETTER N WITH DOT ABOVE
{ 0x1E46, 0x1E47 }, // LATIN CAPITAL LETTER N WITH DOT BELOW
{ 0x1E48, 0x1E49 }, // LATIN CAPITAL LETTER N WITH LINE BELOW
{ 0x1E4A, 0x1E4B }, // LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW
{ 0x1E4C, 0x1E4D }, // LATIN CAPITAL LETTER O WITH TILDE AND ACUTE
{ 0x1E4E, 0x1E4F }, // LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS
{ 0x1E50, 0x1E51 }, // LATIN CAPITAL LETTER O WITH MACRON AND GRAVE
{ 0x1E52, 0x1E53 }, // LATIN CAPITAL LETTER O WITH MACRON AND ACUTE
{ 0x1E54, 0x1E55 }, // LATIN CAPITAL LETTER P WITH ACUTE
{ 0x1E56, 0x1E57 }, // LATIN CAPITAL LETTER P WITH DOT ABOVE
{ 0x1E58, 0x1E59 }, // LATIN CAPITAL LETTER R WITH DOT ABOVE
{ 0x1E5A, 0x1E5B }, // LATIN CAPITAL LETTER R WITH DOT BELOW
{ 0x1E5C, 0x1E5D }, // LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON
{ 0x1E5E, 0x1E5F }, // LATIN CAPITAL LETTER R WITH LINE BELOW
{ 0x1E60, 0x1E61 }, // LATIN CAPITAL LETTER S WITH DOT ABOVE
{ 0x1E62, 0x1E63 }, // LATIN CAPITAL LETTER S WITH DOT BELOW
{ 0x1E64, 0x1E65 }, // LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE
{ 0x1E66, 0x1E67 }, // LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE
{ 0x1E68, 0x1E69 }, // LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE
{ 0x1E6A, 0x1E6B }, // LATIN CAPITAL LETTER T WITH DOT ABOVE
{ 0x1E6C, 0x1E6D }, // LATIN CAPITAL LETTER T WITH DOT BELOW
{ 0x1E6E, 0x1E6F }, // LATIN CAPITAL LETTER T WITH LINE BELOW
{ 0x1E70, 0x1E71 }, // LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW
{ 0x1E72, 0x1E73 }, // LATIN CAPITAL LETTER U WITH DIAERESIS BELOW
{ 0x1E74, 0x1E75 }, // LATIN CAPITAL LETTER U WITH TILDE BELOW
{ 0x1E76, 0x1E77 }, // LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW
{ 0x1E78, 0x1E79 }, // LATIN CAPITAL LETTER U WITH TILDE AND ACUTE
{ 0x1E7A, 0x1E7B }, // LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS
{ 0x1E7C, 0x1E7D }, // LATIN CAPITAL LETTER V WITH TILDE
{ 0x1E7E, 0x1E7F }, // LATIN CAPITAL LETTER V WITH DOT BELOW
{ 0x1E80, 0x1E81 }, // LATIN CAPITAL LETTER W WITH GRAVE
{ 0x1E82, 0x1E83 }, // LATIN CAPITAL LETTER W WITH ACUTE
{ 0x1E84, 0x1E85 }, // LATIN CAPITAL LETTER W WITH DIAERESIS
{ 0x1E86, 0x1E87 }, // LATIN CAPITAL LETTER W WITH DOT ABOVE
{ 0x1E88, 0x1E89 }, // LATIN CAPITAL LETTER W WITH DOT BELOW
{ 0x1E8A, 0x1E8B }, // LATIN CAPITAL LETTER X WITH DOT ABOVE
{ 0x1E8C, 0x1E8D }, // LATIN CAPITAL LETTER X WITH DIAERESIS
{ 0x1E8E, 0x1E8F }, // LATIN CAPITAL LETTER Y WITH DOT ABOVE
{ 0x1E90, 0x1E91 }, // LATIN CAPITAL LETTER Z WITH CIRCUMFLEX
{ 0x1E92, 0x1E93 }, // LATIN CAPITAL LETTER Z WITH DOT BELOW
{ 0x1E94, 0x1E95 }, // LATIN CAPITAL LETTER Z WITH LINE BELOW
{ 0x1E9E, 0x00DF }, // LATIN CAPITAL LETTER SHARP S
{ 0x1EA0, 0x1EA1 }, // LATIN CAPITAL LETTER A WITH DOT BELOW
{ 0x1EA2, 0x1EA3 }, // LATIN CAPITAL LETTER A WITH HOOK ABOVE
{ 0x1EA4, 0x1EA5 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE
{ 0x1EA6, 0x1EA7 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE
{ 0x1EA8, 0x1EA9 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EAA, 0x1EAB }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE
{ 0x1EAC, 0x1EAD }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EAE, 0x1EAF }, // LATIN CAPITAL LETTER A WITH BREVE AND ACUTE
{ 0x1EB0, 0x1EB1 }, // LATIN CAPITAL LETTER A WITH BREVE AND GRAVE
{ 0x1EB2, 0x1EB3 }, // LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE
{ 0x1EB4, 0x1EB5 }, // LATIN CAPITAL LETTER A WITH BREVE AND TILDE
{ 0x1EB6, 0x1EB7 }, // LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW
{ 0x1EB8, 0x1EB9 }, // LATIN CAPITAL LETTER E WITH DOT BELOW
{ 0x1EBA, 0x1EBB }, // LATIN CAPITAL LETTER E WITH HOOK ABOVE
{ 0x1EBC, 0x1EBD }, // LATIN CAPITAL LETTER E WITH TILDE
{ 0x1EBE, 0x1EBF }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE
{ 0x1EC0, 0x1EC1 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE
{ 0x1EC2, 0x1EC3 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EC4, 0x1EC5 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE
{ 0x1EC6, 0x1EC7 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EC8, 0x1EC9 }, // LATIN CAPITAL LETTER I WITH HOOK ABOVE
{ 0x1ECA, 0x1ECB }, // LATIN CAPITAL LETTER I WITH DOT BELOW
{ 0x1ECC, 0x1ECD }, // LATIN CAPITAL LETTER O WITH DOT BELOW
{ 0x1ECE, 0x1ECF }, // LATIN CAPITAL LETTER O WITH HOOK ABOVE
{ 0x1ED0, 0x1ED1 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE
{ 0x1ED2, 0x1ED3 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE
{ 0x1ED4, 0x1ED5 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1ED6, 0x1ED7 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE
{ 0x1ED8, 0x1ED9 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EDA, 0x1EDB }, // LATIN CAPITAL LETTER O WITH HORN AND ACUTE
{ 0x1EDC, 0x1EDD }, // LATIN CAPITAL LETTER O WITH HORN AND GRAVE
{ 0x1EDE, 0x1EDF }, // LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE
{ 0x1EE0, 0x1EE1 }, // LATIN CAPITAL LETTER O WITH HORN AND TILDE
{ 0x1EE2, 0x1EE3 }, // LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW
{ 0x1EE4, 0x1EE5 }, // LATIN CAPITAL LETTER U WITH DOT BELOW
{ 0x1EE6, 0x1EE7 }, // LATIN CAPITAL LETTER U WITH HOOK ABOVE
{ 0x1EE8, 0x1EE9 }, // LATIN CAPITAL LETTER U WITH HORN AND ACUTE
{ 0x1EEA, 0x1EEB }, // LATIN CAPITAL LETTER U WITH HORN AND GRAVE
{ 0x1EEC, 0x1EED }, // LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE
{ 0x1EEE, 0x1EEF }, // LATIN CAPITAL LETTER U WITH HORN AND TILDE
{ 0x1EF0, 0x1EF1 }, // LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW
{ 0x1EF2, 0x1EF3 }, // LATIN CAPITAL LETTER Y WITH GRAVE
{ 0x1EF4, 0x1EF5 }, // LATIN CAPITAL LETTER Y WITH DOT BELOW
{ 0x1EF6, 0x1EF7 }, // LATIN CAPITAL LETTER Y WITH HOOK ABOVE
{ 0x1EF8, 0x1EF9 }, // LATIN CAPITAL LETTER Y WITH TILDE
{ 0x1EFA, 0x1EFB }, // LATIN CAPITAL LETTER MIDDLE-WELSH LL
{ 0x1EFC, 0x1EFD }, // LATIN CAPITAL LETTER MIDDLE-WELSH V
{ 0x1EFE, 0x1EFF }, // LATIN CAPITAL LETTER Y WITH LOOP
{ 0x1F08, 0x1F00 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI
{ 0x1F09, 0x1F01 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA
{ 0x1F0A, 0x1F02 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA
{ 0x1F0B, 0x1F03 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA
{ 0x1F0C, 0x1F04 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA
{ 0x1F0D, 0x1F05 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA
{ 0x1F0E, 0x1F06 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI
{ 0x1F0F, 0x1F07 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI
{ 0x1F18, 0x1F10 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI
{ 0x1F19, 0x1F11 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA
{ 0x1F1A, 0x1F12 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA
{ 0x1F1B, 0x1F13 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA
{ 0x1F1C, 0x1F14 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA
{ 0x1F1D, 0x1F15 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
{ 0x1F28, 0x1F20 }, // GREEK CAPITAL LETTER ETA WITH PSILI
{ 0x1F29, 0x1F21 }, // GREEK CAPITAL LETTER ETA WITH DASIA
{ 0x1F2A, 0x1F22 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA
{ 0x1F2B, 0x1F23 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA
{ 0x1F2C, 0x1F24 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA
{ 0x1F2D, 0x1F25 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA
{ 0x1F2E, 0x1F26 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI
{ 0x1F2F, 0x1F27 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI
{ 0x1F38, 0x1F30 }, // GREEK CAPITAL LETTER IOTA WITH PSILI
{ 0x1F39, 0x1F31 }, // GREEK CAPITAL LETTER IOTA WITH DASIA
{ 0x1F3A, 0x1F32 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA
{ 0x1F3B, 0x1F33 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA
{ 0x1F3C, 0x1F34 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA
{ 0x1F3D, 0x1F35 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA
{ 0x1F3E, 0x1F36 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI
{ 0x1F3F, 0x1F37 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI
{ 0x1F48, 0x1F40 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI
{ 0x1F49, 0x1F41 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA
{ 0x1F4A, 0x1F42 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA
{ 0x1F4B, 0x1F43 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA
{ 0x1F4C, 0x1F44 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA
{ 0x1F4D, 0x1F45 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
{ 0x1F59, 0x1F51 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA
{ 0x1F5B, 0x1F53 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
{ 0x1F5D, 0x1F55 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
{ 0x1F5F, 0x1F57 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI
{ 0x1F68, 0x1F60 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI
{ 0x1F69, 0x1F61 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA
{ 0x1F6A, 0x1F62 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA
{ 0x1F6B, 0x1F63 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA
{ 0x1F6C, 0x1F64 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA
{ 0x1F6D, 0x1F65 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA
{ 0x1F6E, 0x1F66 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI
{ 0x1F6F, 0x1F67 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI
{ 0x1F88, 0x1F80 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F89, 0x1F81 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F8A, 0x1F82 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F8B, 0x1F83 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F8C, 0x1F84 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F8D, 0x1F85 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F8E, 0x1F86 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F8F, 0x1F87 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F98, 0x1F90 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F99, 0x1F91 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F9A, 0x1F92 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F9B, 0x1F93 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F9C, 0x1F94 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F9D, 0x1F95 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F9E, 0x1F96 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F9F, 0x1F97 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FA8, 0x1FA0 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI
{ 0x1FA9, 0x1FA1 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI
{ 0x1FAA, 0x1FA2 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1FAB, 0x1FA3 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1FAC, 0x1FA4 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1FAD, 0x1FA5 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1FAE, 0x1FA6 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FAF, 0x1FA7 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FB8, 0x1FB0 }, // GREEK CAPITAL LETTER ALPHA WITH VRACHY
{ 0x1FB9, 0x1FB1 }, // GREEK CAPITAL LETTER ALPHA WITH MACRON
{ 0x1FBA, 0x1F70 }, // GREEK CAPITAL LETTER ALPHA WITH VARIA
{ 0x1FBB, 0x1F71 }, // GREEK CAPITAL LETTER ALPHA WITH OXIA
{ 0x1FBC, 0x1FB3 }, // GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
{ 0x1FC8, 0x1F72 }, // GREEK CAPITAL LETTER EPSILON WITH VARIA
{ 0x1FC9, 0x1F73 }, // GREEK CAPITAL LETTER EPSILON WITH OXIA
{ 0x1FCA, 0x1F74 }, // GREEK CAPITAL LETTER ETA WITH VARIA
{ 0x1FCB, 0x1F75 }, // GREEK CAPITAL LETTER ETA WITH OXIA
{ 0x1FCC, 0x1FC3 }, // GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
{ 0x1FD8, 0x1FD0 }, // GREEK CAPITAL LETTER IOTA WITH VRACHY
{ 0x1FD9, 0x1FD1 }, // GREEK CAPITAL LETTER IOTA WITH MACRON
{ 0x1FDA, 0x1F76 }, // GREEK CAPITAL LETTER IOTA WITH VARIA
{ 0x1FDB, 0x1F77 }, // GREEK CAPITAL LETTER IOTA WITH OXIA
{ 0x1FE8, 0x1FE0 }, // GREEK CAPITAL LETTER UPSILON WITH VRACHY
{ 0x1FE9, 0x1FE1 }, // GREEK CAPITAL LETTER UPSILON WITH MACRON
{ 0x1FEA, 0x1F7A }, // GREEK CAPITAL LETTER UPSILON WITH VARIA
{ 0x1FEB, 0x1F7B }, // GREEK CAPITAL LETTER UPSILON WITH OXIA
{ 0x1FEC, 0x1FE5 }, // GREEK CAPITAL LETTER RHO WITH DASIA
{ 0x1FF8, 0x1F78 }, // GREEK CAPITAL LETTER OMICRON WITH VARIA
{ 0x1FF9, 0x1F79 }, // GREEK CAPITAL LETTER OMICRON WITH OXIA
{ 0x1FFA, 0x1F7C }, // GREEK CAPITAL LETTER OMEGA WITH VARIA
{ 0x1FFB, 0x1F7D }, // GREEK CAPITAL LETTER OMEGA WITH OXIA
{ 0x1FFC, 0x1FF3 }, // GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
{ 0x2126, 0x03C9 }, // OHM SIGN
{ 0x212A, 0x006B }, // KELVIN SIGN
{ 0x212B, 0x00E5 }, // ANGSTROM SIGN
{ 0x2132, 0x214E }, // TURNED CAPITAL F
{ 0x2160, 0x2170 }, // ROMAN NUMERAL ONE
{ 0x2161, 0x2171 }, // ROMAN NUMERAL TWO
{ 0x2162, 0x2172 }, // ROMAN NUMERAL THREE
{ 0x2163, 0x2173 }, // ROMAN NUMERAL FOUR
{ 0x2164, 0x2174 }, // ROMAN NUMERAL FIVE
{ 0x2165, 0x2175 }, // ROMAN NUMERAL SIX
{ 0x2166, 0x2176 }, // ROMAN NUMERAL SEVEN
{ 0x2167, 0x2177 }, // ROMAN NUMERAL EIGHT
{ 0x2168, 0x2178 }, // ROMAN NUMERAL NINE
{ 0x2169, 0x2179 }, // ROMAN NUMERAL TEN
{ 0x216A, 0x217A }, // ROMAN NUMERAL ELEVEN
{ 0x216B, 0x217B }, // ROMAN NUMERAL TWELVE
{ 0x216C, 0x217C }, // ROMAN NUMERAL FIFTY
{ 0x216D, 0x217D }, // ROMAN NUMERAL ONE HUNDRED
{ 0x216E, 0x217E }, // ROMAN NUMERAL FIVE HUNDRED
{ 0x216F, 0x217F }, // ROMAN NUMERAL ONE THOUSAND
{ 0x2183, 0x2184 }, // ROMAN NUMERAL REVERSED ONE HUNDRED
{ 0x24B6, 0x24D0 }, // CIRCLED LATIN CAPITAL LETTER A
{ 0x24B7, 0x24D1 }, // CIRCLED LATIN CAPITAL LETTER B
{ 0x24B8, 0x24D2 }, // CIRCLED LATIN CAPITAL LETTER C
{ 0x24B9, 0x24D3 }, // CIRCLED LATIN CAPITAL LETTER D
{ 0x24BA, 0x24D4 }, // CIRCLED LATIN CAPITAL LETTER E
{ 0x24BB, 0x24D5 }, // CIRCLED LATIN CAPITAL LETTER F
{ 0x24BC, 0x24D6 }, // CIRCLED LATIN CAPITAL LETTER G
{ 0x24BD, 0x24D7 }, // CIRCLED LATIN CAPITAL LETTER H
{ 0x24BE, 0x24D8 }, // CIRCLED LATIN CAPITAL LETTER I
{ 0x24BF, 0x24D9 }, // CIRCLED LATIN CAPITAL LETTER J
{ 0x24C0, 0x24DA }, // CIRCLED LATIN CAPITAL LETTER K
{ 0x24C1, 0x24DB }, // CIRCLED LATIN CAPITAL LETTER L
{ 0x24C2, 0x24DC }, // CIRCLED LATIN CAPITAL LETTER M
{ 0x24C3, 0x24DD }, // CIRCLED LATIN CAPITAL LETTER N
{ 0x24C4, 0x24DE }, // CIRCLED LATIN CAPITAL LETTER O
{ 0x24C5, 0x24DF }, // CIRCLED LATIN CAPITAL LETTER P
{ 0x24C6, 0x24E0 }, // CIRCLED LATIN CAPITAL LETTER Q
{ 0x24C7, 0x24E1 }, // CIRCLED LATIN CAPITAL LETTER R
{ 0x24C8, 0x24E2 }, // CIRCLED LATIN CAPITAL LETTER S
{ 0x24C9, 0x24E3 }, // CIRCLED LATIN CAPITAL LETTER T
{ 0x24CA, 0x24E4 }, // CIRCLED LATIN CAPITAL LETTER U
{ 0x24CB, 0x24E5 }, // CIRCLED LATIN CAPITAL LETTER V
{ 0x24CC, 0x24E6 }, // CIRCLED LATIN CAPITAL LETTER W
{ 0x24CD, 0x24E7 }, // CIRCLED LATIN CAPITAL LETTER X
{ 0x24CE, 0x24E8 }, // CIRCLED LATIN CAPITAL LETTER Y
{ 0x24CF, 0x24E9 }, // CIRCLED LATIN CAPITAL LETTER Z
{ 0x2C00, 0x2C30 }, // GLAGOLITIC CAPITAL LETTER AZU
{ 0x2C01, 0x2C31 }, // GLAGOLITIC CAPITAL LETTER BUKY
{ 0x2C02, 0x2C32 }, // GLAGOLITIC CAPITAL LETTER VEDE
{ 0x2C03, 0x2C33 }, // GLAGOLITIC CAPITAL LETTER GLAGOLI
{ 0x2C04, 0x2C34 }, // GLAGOLITIC CAPITAL LETTER DOBRO
{ 0x2C05, 0x2C35 }, // GLAGOLITIC CAPITAL LETTER YESTU
{ 0x2C06, 0x2C36 }, // GLAGOLITIC CAPITAL LETTER ZHIVETE
{ 0x2C07, 0x2C37 }, // GLAGOLITIC CAPITAL LETTER DZELO
{ 0x2C08, 0x2C38 }, // GLAGOLITIC CAPITAL LETTER ZEMLJA
{ 0x2C09, 0x2C39 }, // GLAGOLITIC CAPITAL LETTER IZHE
{ 0x2C0A, 0x2C3A }, // GLAGOLITIC CAPITAL LETTER INITIAL IZHE
{ 0x2C0B, 0x2C3B }, // GLAGOLITIC CAPITAL LETTER I
{ 0x2C0C, 0x2C3C }, // GLAGOLITIC CAPITAL LETTER DJERVI
{ 0x2C0D, 0x2C3D }, // GLAGOLITIC CAPITAL LETTER KAKO
{ 0x2C0E, 0x2C3E }, // GLAGOLITIC CAPITAL LETTER LJUDIJE
{ 0x2C0F, 0x2C3F }, // GLAGOLITIC CAPITAL LETTER MYSLITE
{ 0x2C10, 0x2C40 }, // GLAGOLITIC CAPITAL LETTER NASHI
{ 0x2C11, 0x2C41 }, // GLAGOLITIC CAPITAL LETTER ONU
{ 0x2C12, 0x2C42 }, // GLAGOLITIC CAPITAL LETTER POKOJI
{ 0x2C13, 0x2C43 }, // GLAGOLITIC CAPITAL LETTER RITSI
{ 0x2C14, 0x2C44 }, // GLAGOLITIC CAPITAL LETTER SLOVO
{ 0x2C15, 0x2C45 }, // GLAGOLITIC CAPITAL LETTER TVRIDO
{ 0x2C16, 0x2C46 }, // GLAGOLITIC CAPITAL LETTER UKU
{ 0x2C17, 0x2C47 }, // GLAGOLITIC CAPITAL LETTER FRITU
{ 0x2C18, 0x2C48 }, // GLAGOLITIC CAPITAL LETTER HERU
{ 0x2C19, 0x2C49 }, // GLAGOLITIC CAPITAL LETTER OTU
{ 0x2C1A, 0x2C4A }, // GLAGOLITIC CAPITAL LETTER PE
{ 0x2C1B, 0x2C4B }, // GLAGOLITIC CAPITAL LETTER SHTA
{ 0x2C1C, 0x2C4C }, // GLAGOLITIC CAPITAL LETTER TSI
{ 0x2C1D, 0x2C4D }, // GLAGOLITIC CAPITAL LETTER CHRIVI
{ 0x2C1E, 0x2C4E }, // GLAGOLITIC CAPITAL LETTER SHA
{ 0x2C1F, 0x2C4F }, // GLAGOLITIC CAPITAL LETTER YERU
{ 0x2C20, 0x2C50 }, // GLAGOLITIC CAPITAL LETTER YERI
{ 0x2C21, 0x2C51 }, // GLAGOLITIC CAPITAL LETTER YATI
{ 0x2C22, 0x2C52 }, // GLAGOLITIC CAPITAL LETTER SPIDERY HA
{ 0x2C23, 0x2C53 }, // GLAGOLITIC CAPITAL LETTER YU
{ 0x2C24, 0x2C54 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS
{ 0x2C25, 0x2C55 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL
{ 0x2C26, 0x2C56 }, // GLAGOLITIC CAPITAL LETTER YO
{ 0x2C27, 0x2C57 }, // GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS
{ 0x2C28, 0x2C58 }, // GLAGOLITIC CAPITAL LETTER BIG YUS
{ 0x2C29, 0x2C59 }, // GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS
{ 0x2C2A, 0x2C5A }, // GLAGOLITIC CAPITAL LETTER FITA
{ 0x2C2B, 0x2C5B }, // GLAGOLITIC CAPITAL LETTER IZHITSA
{ 0x2C2C, 0x2C5C }, // GLAGOLITIC CAPITAL LETTER SHTAPIC
{ 0x2C2D, 0x2C5D }, // GLAGOLITIC CAPITAL LETTER TROKUTASTI A
{ 0x2C2E, 0x2C5E }, // GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE
{ 0x2C60, 0x2C61 }, // LATIN CAPITAL LETTER L WITH DOUBLE BAR
{ 0x2C62, 0x026B }, // LATIN CAPITAL LETTER L WITH MIDDLE TILDE
{ 0x2C63, 0x1D7D }, // LATIN CAPITAL LETTER P WITH STROKE
{ 0x2C64, 0x027D }, // LATIN CAPITAL LETTER R WITH TAIL
{ 0x2C67, 0x2C68 }, // LATIN CAPITAL LETTER H WITH DESCENDER
{ 0x2C69, 0x2C6A }, // LATIN CAPITAL LETTER K WITH DESCENDER
{ 0x2C6B, 0x2C6C }, // LATIN CAPITAL LETTER Z WITH DESCENDER
{ 0x2C6D, 0x0251 }, // LATIN CAPITAL LETTER ALPHA
{ 0x2C6E, 0x0271 }, // LATIN CAPITAL LETTER M WITH HOOK
{ 0x2C6F, 0x0250 }, // LATIN CAPITAL LETTER TURNED A
{ 0x2C70, 0x0252 }, // LATIN CAPITAL LETTER TURNED ALPHA
{ 0x2C72, 0x2C73 }, // LATIN CAPITAL LETTER W WITH HOOK
{ 0x2C75, 0x2C76 }, // LATIN CAPITAL LETTER HALF H
{ 0x2C7E, 0x023F }, // LATIN CAPITAL LETTER S WITH SWASH TAIL
{ 0x2C7F, 0x0240 }, // LATIN CAPITAL LETTER Z WITH SWASH TAIL
{ 0x2C80, 0x2C81 }, // COPTIC CAPITAL LETTER ALFA
{ 0x2C82, 0x2C83 }, // COPTIC CAPITAL LETTER VIDA
{ 0x2C84, 0x2C85 }, // COPTIC CAPITAL LETTER GAMMA
{ 0x2C86, 0x2C87 }, // COPTIC CAPITAL LETTER DALDA
{ 0x2C88, 0x2C89 }, // COPTIC CAPITAL LETTER EIE
{ 0x2C8A, 0x2C8B }, // COPTIC CAPITAL LETTER SOU
{ 0x2C8C, 0x2C8D }, // COPTIC CAPITAL LETTER ZATA
{ 0x2C8E, 0x2C8F }, // COPTIC CAPITAL LETTER HATE
{ 0x2C90, 0x2C91 }, // COPTIC CAPITAL LETTER THETHE
{ 0x2C92, 0x2C93 }, // COPTIC CAPITAL LETTER IAUDA
{ 0x2C94, 0x2C95 }, // COPTIC CAPITAL LETTER KAPA
{ 0x2C96, 0x2C97 }, // COPTIC CAPITAL LETTER LAULA
{ 0x2C98, 0x2C99 }, // COPTIC CAPITAL LETTER MI
{ 0x2C9A, 0x2C9B }, // COPTIC CAPITAL LETTER NI
{ 0x2C9C, 0x2C9D }, // COPTIC CAPITAL LETTER KSI
{ 0x2C9E, 0x2C9F }, // COPTIC CAPITAL LETTER O
{ 0x2CA0, 0x2CA1 }, // COPTIC CAPITAL LETTER PI
{ 0x2CA2, 0x2CA3 }, // COPTIC CAPITAL LETTER RO
{ 0x2CA4, 0x2CA5 }, // COPTIC CAPITAL LETTER SIMA
{ 0x2CA6, 0x2CA7 }, // COPTIC CAPITAL LETTER TAU
{ 0x2CA8, 0x2CA9 }, // COPTIC CAPITAL LETTER UA
{ 0x2CAA, 0x2CAB }, // COPTIC CAPITAL LETTER FI
{ 0x2CAC, 0x2CAD }, // COPTIC CAPITAL LETTER KHI
{ 0x2CAE, 0x2CAF }, // COPTIC CAPITAL LETTER PSI
{ 0x2CB0, 0x2CB1 }, // COPTIC CAPITAL LETTER OOU
{ 0x2CB2, 0x2CB3 }, // COPTIC CAPITAL LETTER DIALECT-P ALEF
{ 0x2CB4, 0x2CB5 }, // COPTIC CAPITAL LETTER OLD COPTIC AIN
{ 0x2CB6, 0x2CB7 }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE
{ 0x2CB8, 0x2CB9 }, // COPTIC CAPITAL LETTER DIALECT-P KAPA
{ 0x2CBA, 0x2CBB }, // COPTIC CAPITAL LETTER DIALECT-P NI
{ 0x2CBC, 0x2CBD }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI
{ 0x2CBE, 0x2CBF }, // COPTIC CAPITAL LETTER OLD COPTIC OOU
{ 0x2CC0, 0x2CC1 }, // COPTIC CAPITAL LETTER SAMPI
{ 0x2CC2, 0x2CC3 }, // COPTIC CAPITAL LETTER CROSSED SHEI
{ 0x2CC4, 0x2CC5 }, // COPTIC CAPITAL LETTER OLD COPTIC SHEI
{ 0x2CC6, 0x2CC7 }, // COPTIC CAPITAL LETTER OLD COPTIC ESH
{ 0x2CC8, 0x2CC9 }, // COPTIC CAPITAL LETTER AKHMIMIC KHEI
{ 0x2CCA, 0x2CCB }, // COPTIC CAPITAL LETTER DIALECT-P HORI
{ 0x2CCC, 0x2CCD }, // COPTIC CAPITAL LETTER OLD COPTIC HORI
{ 0x2CCE, 0x2CCF }, // COPTIC CAPITAL LETTER OLD COPTIC HA
{ 0x2CD0, 0x2CD1 }, // COPTIC CAPITAL LETTER L-SHAPED HA
{ 0x2CD2, 0x2CD3 }, // COPTIC CAPITAL LETTER OLD COPTIC HEI
{ 0x2CD4, 0x2CD5 }, // COPTIC CAPITAL LETTER OLD COPTIC HAT
{ 0x2CD6, 0x2CD7 }, // COPTIC CAPITAL LETTER OLD COPTIC GANGIA
{ 0x2CD8, 0x2CD9 }, // COPTIC CAPITAL LETTER OLD COPTIC DJA
{ 0x2CDA, 0x2CDB }, // COPTIC CAPITAL LETTER OLD COPTIC SHIMA
{ 0x2CDC, 0x2CDD }, // COPTIC CAPITAL LETTER OLD NUBIAN SHIMA
{ 0x2CDE, 0x2CDF }, // COPTIC CAPITAL LETTER OLD NUBIAN NGI
{ 0x2CE0, 0x2CE1 }, // COPTIC CAPITAL LETTER OLD NUBIAN NYI
{ 0x2CE2, 0x2CE3 }, // COPTIC CAPITAL LETTER OLD NUBIAN WAU
{ 0x2CEB, 0x2CEC }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI
{ 0x2CED, 0x2CEE }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA
{ 0xA640, 0xA641 }, // CYRILLIC CAPITAL LETTER ZEMLYA
{ 0xA642, 0xA643 }, // CYRILLIC CAPITAL LETTER DZELO
{ 0xA644, 0xA645 }, // CYRILLIC CAPITAL LETTER REVERSED DZE
{ 0xA646, 0xA647 }, // CYRILLIC CAPITAL LETTER IOTA
{ 0xA648, 0xA649 }, // CYRILLIC CAPITAL LETTER DJERV
{ 0xA64A, 0xA64B }, // CYRILLIC CAPITAL LETTER MONOGRAPH UK
{ 0xA64C, 0xA64D }, // CYRILLIC CAPITAL LETTER BROAD OMEGA
{ 0xA64E, 0xA64F }, // CYRILLIC CAPITAL LETTER NEUTRAL YER
{ 0xA650, 0xA651 }, // CYRILLIC CAPITAL LETTER YERU WITH BACK YER
{ 0xA652, 0xA653 }, // CYRILLIC CAPITAL LETTER IOTIFIED YAT
{ 0xA654, 0xA655 }, // CYRILLIC CAPITAL LETTER REVERSED YU
{ 0xA656, 0xA657 }, // CYRILLIC CAPITAL LETTER IOTIFIED A
{ 0xA658, 0xA659 }, // CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS
{ 0xA65A, 0xA65B }, // CYRILLIC CAPITAL LETTER BLENDED YUS
{ 0xA65C, 0xA65D }, // CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS
{ 0xA65E, 0xA65F }, // CYRILLIC CAPITAL LETTER YN
{ 0xA662, 0xA663 }, // CYRILLIC CAPITAL LETTER SOFT DE
{ 0xA664, 0xA665 }, // CYRILLIC CAPITAL LETTER SOFT EL
{ 0xA666, 0xA667 }, // CYRILLIC CAPITAL LETTER SOFT EM
{ 0xA668, 0xA669 }, // CYRILLIC CAPITAL LETTER MONOCULAR O
{ 0xA66A, 0xA66B }, // CYRILLIC CAPITAL LETTER BINOCULAR O
{ 0xA66C, 0xA66D }, // CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O
{ 0xA680, 0xA681 }, // CYRILLIC CAPITAL LETTER DWE
{ 0xA682, 0xA683 }, // CYRILLIC CAPITAL LETTER DZWE
{ 0xA684, 0xA685 }, // CYRILLIC CAPITAL LETTER ZHWE
{ 0xA686, 0xA687 }, // CYRILLIC CAPITAL LETTER CCHE
{ 0xA688, 0xA689 }, // CYRILLIC CAPITAL LETTER DZZE
{ 0xA68A, 0xA68B }, // CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK
{ 0xA68C, 0xA68D }, // CYRILLIC CAPITAL LETTER TWE
{ 0xA68E, 0xA68F }, // CYRILLIC CAPITAL LETTER TSWE
{ 0xA690, 0xA691 }, // CYRILLIC CAPITAL LETTER TSSE
{ 0xA692, 0xA693 }, // CYRILLIC CAPITAL LETTER TCHE
{ 0xA694, 0xA695 }, // CYRILLIC CAPITAL LETTER HWE
{ 0xA696, 0xA697 }, // CYRILLIC CAPITAL LETTER SHWE
{ 0xA722, 0xA723 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF
{ 0xA724, 0xA725 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL AIN
{ 0xA726, 0xA727 }, // LATIN CAPITAL LETTER HENG
{ 0xA728, 0xA729 }, // LATIN CAPITAL LETTER TZ
{ 0xA72A, 0xA72B }, // LATIN CAPITAL LETTER TRESILLO
{ 0xA72C, 0xA72D }, // LATIN CAPITAL LETTER CUATRILLO
{ 0xA72E, 0xA72F }, // LATIN CAPITAL LETTER CUATRILLO WITH COMMA
{ 0xA732, 0xA733 }, // LATIN CAPITAL LETTER AA
{ 0xA734, 0xA735 }, // LATIN CAPITAL LETTER AO
{ 0xA736, 0xA737 }, // LATIN CAPITAL LETTER AU
{ 0xA738, 0xA739 }, // LATIN CAPITAL LETTER AV
{ 0xA73A, 0xA73B }, // LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR
{ 0xA73C, 0xA73D }, // LATIN CAPITAL LETTER AY
{ 0xA73E, 0xA73F }, // LATIN CAPITAL LETTER REVERSED C WITH DOT
{ 0xA740, 0xA741 }, // LATIN CAPITAL LETTER K WITH STROKE
{ 0xA742, 0xA743 }, // LATIN CAPITAL LETTER K WITH DIAGONAL STROKE
{ 0xA744, 0xA745 }, // LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE
{ 0xA746, 0xA747 }, // LATIN CAPITAL LETTER BROKEN L
{ 0xA748, 0xA749 }, // LATIN CAPITAL LETTER L WITH HIGH STROKE
{ 0xA74A, 0xA74B }, // LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY
{ 0xA74C, 0xA74D }, // LATIN CAPITAL LETTER O WITH LOOP
{ 0xA74E, 0xA74F }, // LATIN CAPITAL LETTER OO
{ 0xA750, 0xA751 }, // LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER
{ 0xA752, 0xA753 }, // LATIN CAPITAL LETTER P WITH FLOURISH
{ 0xA754, 0xA755 }, // LATIN CAPITAL LETTER P WITH SQUIRREL TAIL
{ 0xA756, 0xA757 }, // LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER
{ 0xA758, 0xA759 }, // LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE
{ 0xA75A, 0xA75B }, // LATIN CAPITAL LETTER R ROTUNDA
{ 0xA75C, 0xA75D }, // LATIN CAPITAL LETTER RUM ROTUNDA
{ 0xA75E, 0xA75F }, // LATIN CAPITAL LETTER V WITH DIAGONAL STROKE
{ 0xA760, 0xA761 }, // LATIN CAPITAL LETTER VY
{ 0xA762, 0xA763 }, // LATIN CAPITAL LETTER VISIGOTHIC Z
{ 0xA764, 0xA765 }, // LATIN CAPITAL LETTER THORN WITH STROKE
{ 0xA766, 0xA767 }, // LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER
{ 0xA768, 0xA769 }, // LATIN CAPITAL LETTER VEND
{ 0xA76A, 0xA76B }, // LATIN CAPITAL LETTER ET
{ 0xA76C, 0xA76D }, // LATIN CAPITAL LETTER IS
{ 0xA76E, 0xA76F }, // LATIN CAPITAL LETTER CON
{ 0xA779, 0xA77A }, // LATIN CAPITAL LETTER INSULAR D
{ 0xA77B, 0xA77C }, // LATIN CAPITAL LETTER INSULAR F
{ 0xA77D, 0x1D79 }, // LATIN CAPITAL LETTER INSULAR G
{ 0xA77E, 0xA77F }, // LATIN CAPITAL LETTER TURNED INSULAR G
{ 0xA780, 0xA781 }, // LATIN CAPITAL LETTER TURNED L
{ 0xA782, 0xA783 }, // LATIN CAPITAL LETTER INSULAR R
{ 0xA784, 0xA785 }, // LATIN CAPITAL LETTER INSULAR S
{ 0xA786, 0xA787 }, // LATIN CAPITAL LETTER INSULAR T
{ 0xA78B, 0xA78C }, // LATIN CAPITAL LETTER SALTILLO
{ 0xFF21, 0xFF41 }, // FULLWIDTH LATIN CAPITAL LETTER A
{ 0xFF22, 0xFF42 }, // FULLWIDTH LATIN CAPITAL LETTER B
{ 0xFF23, 0xFF43 }, // FULLWIDTH LATIN CAPITAL LETTER C
{ 0xFF24, 0xFF44 }, // FULLWIDTH LATIN CAPITAL LETTER D
{ 0xFF25, 0xFF45 }, // FULLWIDTH LATIN CAPITAL LETTER E
{ 0xFF26, 0xFF46 }, // FULLWIDTH LATIN CAPITAL LETTER F
{ 0xFF27, 0xFF47 }, // FULLWIDTH LATIN CAPITAL LETTER G
{ 0xFF28, 0xFF48 }, // FULLWIDTH LATIN CAPITAL LETTER H
{ 0xFF29, 0xFF49 }, // FULLWIDTH LATIN CAPITAL LETTER I
{ 0xFF2A, 0xFF4A }, // FULLWIDTH LATIN CAPITAL LETTER J
{ 0xFF2B, 0xFF4B }, // FULLWIDTH LATIN CAPITAL LETTER K
{ 0xFF2C, 0xFF4C }, // FULLWIDTH LATIN CAPITAL LETTER L
{ 0xFF2D, 0xFF4D }, // FULLWIDTH LATIN CAPITAL LETTER M
{ 0xFF2E, 0xFF4E }, // FULLWIDTH LATIN CAPITAL LETTER N
{ 0xFF2F, 0xFF4F }, // FULLWIDTH LATIN CAPITAL LETTER O
{ 0xFF30, 0xFF50 }, // FULLWIDTH LATIN CAPITAL LETTER P
{ 0xFF31, 0xFF51 }, // FULLWIDTH LATIN CAPITAL LETTER Q
{ 0xFF32, 0xFF52 }, // FULLWIDTH LATIN CAPITAL LETTER R
{ 0xFF33, 0xFF53 }, // FULLWIDTH LATIN CAPITAL LETTER S
{ 0xFF34, 0xFF54 }, // FULLWIDTH LATIN CAPITAL LETTER T
{ 0xFF35, 0xFF55 }, // FULLWIDTH LATIN CAPITAL LETTER U
{ 0xFF36, 0xFF56 }, // FULLWIDTH LATIN CAPITAL LETTER V
{ 0xFF37, 0xFF57 }, // FULLWIDTH LATIN CAPITAL LETTER W
{ 0xFF38, 0xFF58 }, // FULLWIDTH LATIN CAPITAL LETTER X
{ 0xFF39, 0xFF59 }, // FULLWIDTH LATIN CAPITAL LETTER Y
{ 0xFF3A, 0xFF5A } // FULLWIDTH LATIN CAPITAL LETTER Z
};
static int compare_pair_capital(const void *a, const void *b) {
return (int)(*(unsigned short *)a)
- (int)((struct LatinCapitalSmallPair*)b)->capital;
}
unsigned short latin_tolower(unsigned short c) {
struct LatinCapitalSmallPair *p =
(struct LatinCapitalSmallPair *)bsearch(&c, SORTED_CHAR_MAP,
sizeof(SORTED_CHAR_MAP) / sizeof(SORTED_CHAR_MAP[0]),
sizeof(SORTED_CHAR_MAP[0]),
compare_pair_capital);
return p ? p->small : c;
}
} // namespace latinime
|
09bicsekanjam-clone
|
java/jni/src/char_utils.cpp
|
C++
|
asf20
| 53,690
|
/**
* Table mapping most combined Latin, Greek, and Cyrillic characters
* to their base characters. If c is in range, BASE_CHARS[c] == c
* if c is not a combined character, or the base character if it
* is combined.
*/
static unsigned short BASE_CHARS[] = {
0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f,
0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f,
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f,
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f,
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f,
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f,
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f,
0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b, 0x008c, 0x008d, 0x008e, 0x008f,
0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b, 0x009c, 0x009d, 0x009e, 0x009f,
0x0020, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x0020, 0x00a9, 0x0061, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x0020,
0x00b0, 0x00b1, 0x0032, 0x0033, 0x0020, 0x03bc, 0x00b6, 0x00b7,
0x0020, 0x0031, 0x006f, 0x00bb, 0x0031, 0x0031, 0x0033, 0x00bf,
0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x0041, 0x00c6, 0x0043,
0x0045, 0x0045, 0x0045, 0x0045, 0x0049, 0x0049, 0x0049, 0x0049,
0x00d0, 0x004e, 0x004f, 0x004f, 0x004f, 0x004f, 0x004f, 0x00d7,
0x004f, 0x0055, 0x0055, 0x0055, 0x0055, 0x0059, 0x00de, 0x0073, // Manually changed d8 to 4f
// Manually changed df to 73
0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x0061, 0x00e6, 0x0063,
0x0065, 0x0065, 0x0065, 0x0065, 0x0069, 0x0069, 0x0069, 0x0069,
0x00f0, 0x006e, 0x006f, 0x006f, 0x006f, 0x006f, 0x006f, 0x00f7,
0x006f, 0x0075, 0x0075, 0x0075, 0x0075, 0x0079, 0x00fe, 0x0079, // Manually changed f8 to 6f
0x0041, 0x0061, 0x0041, 0x0061, 0x0041, 0x0061, 0x0043, 0x0063,
0x0043, 0x0063, 0x0043, 0x0063, 0x0043, 0x0063, 0x0044, 0x0064,
0x0110, 0x0111, 0x0045, 0x0065, 0x0045, 0x0065, 0x0045, 0x0065,
0x0045, 0x0065, 0x0045, 0x0065, 0x0047, 0x0067, 0x0047, 0x0067,
0x0047, 0x0067, 0x0047, 0x0067, 0x0048, 0x0068, 0x0126, 0x0127,
0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069, 0x0049, 0x0069,
0x0049, 0x0131, 0x0049, 0x0069, 0x004a, 0x006a, 0x004b, 0x006b,
0x0138, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c, 0x006c, 0x004c,
0x006c, 0x0141, 0x0142, 0x004e, 0x006e, 0x004e, 0x006e, 0x004e,
0x006e, 0x02bc, 0x014a, 0x014b, 0x004f, 0x006f, 0x004f, 0x006f,
0x004f, 0x006f, 0x0152, 0x0153, 0x0052, 0x0072, 0x0052, 0x0072,
0x0052, 0x0072, 0x0053, 0x0073, 0x0053, 0x0073, 0x0053, 0x0073,
0x0053, 0x0073, 0x0054, 0x0074, 0x0054, 0x0074, 0x0166, 0x0167,
0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075, 0x0055, 0x0075,
0x0055, 0x0075, 0x0055, 0x0075, 0x0057, 0x0077, 0x0059, 0x0079,
0x0059, 0x005a, 0x007a, 0x005a, 0x007a, 0x005a, 0x007a, 0x0073,
0x0180, 0x0181, 0x0182, 0x0183, 0x0184, 0x0185, 0x0186, 0x0187,
0x0188, 0x0189, 0x018a, 0x018b, 0x018c, 0x018d, 0x018e, 0x018f,
0x0190, 0x0191, 0x0192, 0x0193, 0x0194, 0x0195, 0x0196, 0x0197,
0x0198, 0x0199, 0x019a, 0x019b, 0x019c, 0x019d, 0x019e, 0x019f,
0x004f, 0x006f, 0x01a2, 0x01a3, 0x01a4, 0x01a5, 0x01a6, 0x01a7,
0x01a8, 0x01a9, 0x01aa, 0x01ab, 0x01ac, 0x01ad, 0x01ae, 0x0055,
0x0075, 0x01b1, 0x01b2, 0x01b3, 0x01b4, 0x01b5, 0x01b6, 0x01b7,
0x01b8, 0x01b9, 0x01ba, 0x01bb, 0x01bc, 0x01bd, 0x01be, 0x01bf,
0x01c0, 0x01c1, 0x01c2, 0x01c3, 0x0044, 0x0044, 0x0064, 0x004c,
0x004c, 0x006c, 0x004e, 0x004e, 0x006e, 0x0041, 0x0061, 0x0049,
0x0069, 0x004f, 0x006f, 0x0055, 0x0075, 0x00dc, 0x00fc, 0x00dc,
0x00fc, 0x00dc, 0x00fc, 0x00dc, 0x00fc, 0x01dd, 0x00c4, 0x00e4,
0x0226, 0x0227, 0x00c6, 0x00e6, 0x01e4, 0x01e5, 0x0047, 0x0067,
0x004b, 0x006b, 0x004f, 0x006f, 0x01ea, 0x01eb, 0x01b7, 0x0292,
0x006a, 0x0044, 0x0044, 0x0064, 0x0047, 0x0067, 0x01f6, 0x01f7,
0x004e, 0x006e, 0x00c5, 0x00e5, 0x00c6, 0x00e6, 0x00d8, 0x00f8,
0x0041, 0x0061, 0x0041, 0x0061, 0x0045, 0x0065, 0x0045, 0x0065,
0x0049, 0x0069, 0x0049, 0x0069, 0x004f, 0x006f, 0x004f, 0x006f,
0x0052, 0x0072, 0x0052, 0x0072, 0x0055, 0x0075, 0x0055, 0x0075,
0x0053, 0x0073, 0x0054, 0x0074, 0x021c, 0x021d, 0x0048, 0x0068,
0x0220, 0x0221, 0x0222, 0x0223, 0x0224, 0x0225, 0x0041, 0x0061,
0x0045, 0x0065, 0x00d6, 0x00f6, 0x00d5, 0x00f5, 0x004f, 0x006f,
0x022e, 0x022f, 0x0059, 0x0079, 0x0234, 0x0235, 0x0236, 0x0237,
0x0238, 0x0239, 0x023a, 0x023b, 0x023c, 0x023d, 0x023e, 0x023f,
0x0240, 0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247,
0x0248, 0x0249, 0x024a, 0x024b, 0x024c, 0x024d, 0x024e, 0x024f,
0x0250, 0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257,
0x0258, 0x0259, 0x025a, 0x025b, 0x025c, 0x025d, 0x025e, 0x025f,
0x0260, 0x0261, 0x0262, 0x0263, 0x0264, 0x0265, 0x0266, 0x0267,
0x0268, 0x0269, 0x026a, 0x026b, 0x026c, 0x026d, 0x026e, 0x026f,
0x0270, 0x0271, 0x0272, 0x0273, 0x0274, 0x0275, 0x0276, 0x0277,
0x0278, 0x0279, 0x027a, 0x027b, 0x027c, 0x027d, 0x027e, 0x027f,
0x0280, 0x0281, 0x0282, 0x0283, 0x0284, 0x0285, 0x0286, 0x0287,
0x0288, 0x0289, 0x028a, 0x028b, 0x028c, 0x028d, 0x028e, 0x028f,
0x0290, 0x0291, 0x0292, 0x0293, 0x0294, 0x0295, 0x0296, 0x0297,
0x0298, 0x0299, 0x029a, 0x029b, 0x029c, 0x029d, 0x029e, 0x029f,
0x02a0, 0x02a1, 0x02a2, 0x02a3, 0x02a4, 0x02a5, 0x02a6, 0x02a7,
0x02a8, 0x02a9, 0x02aa, 0x02ab, 0x02ac, 0x02ad, 0x02ae, 0x02af,
0x0068, 0x0266, 0x006a, 0x0072, 0x0279, 0x027b, 0x0281, 0x0077,
0x0079, 0x02b9, 0x02ba, 0x02bb, 0x02bc, 0x02bd, 0x02be, 0x02bf,
0x02c0, 0x02c1, 0x02c2, 0x02c3, 0x02c4, 0x02c5, 0x02c6, 0x02c7,
0x02c8, 0x02c9, 0x02ca, 0x02cb, 0x02cc, 0x02cd, 0x02ce, 0x02cf,
0x02d0, 0x02d1, 0x02d2, 0x02d3, 0x02d4, 0x02d5, 0x02d6, 0x02d7,
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x02de, 0x02df,
0x0263, 0x006c, 0x0073, 0x0078, 0x0295, 0x02e5, 0x02e6, 0x02e7,
0x02e8, 0x02e9, 0x02ea, 0x02eb, 0x02ec, 0x02ed, 0x02ee, 0x02ef,
0x02f0, 0x02f1, 0x02f2, 0x02f3, 0x02f4, 0x02f5, 0x02f6, 0x02f7,
0x02f8, 0x02f9, 0x02fa, 0x02fb, 0x02fc, 0x02fd, 0x02fe, 0x02ff,
0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307,
0x0308, 0x0309, 0x030a, 0x030b, 0x030c, 0x030d, 0x030e, 0x030f,
0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317,
0x0318, 0x0319, 0x031a, 0x031b, 0x031c, 0x031d, 0x031e, 0x031f,
0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327,
0x0328, 0x0329, 0x032a, 0x032b, 0x032c, 0x032d, 0x032e, 0x032f,
0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337,
0x0338, 0x0339, 0x033a, 0x033b, 0x033c, 0x033d, 0x033e, 0x033f,
0x0300, 0x0301, 0x0342, 0x0313, 0x0308, 0x0345, 0x0346, 0x0347,
0x0348, 0x0349, 0x034a, 0x034b, 0x034c, 0x034d, 0x034e, 0x034f,
0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357,
0x0358, 0x0359, 0x035a, 0x035b, 0x035c, 0x035d, 0x035e, 0x035f,
0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367,
0x0368, 0x0369, 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f,
0x0370, 0x0371, 0x0372, 0x0373, 0x02b9, 0x0375, 0x0376, 0x0377,
0x0378, 0x0379, 0x0020, 0x037b, 0x037c, 0x037d, 0x003b, 0x037f,
0x0380, 0x0381, 0x0382, 0x0383, 0x0020, 0x00a8, 0x0391, 0x00b7,
0x0395, 0x0397, 0x0399, 0x038b, 0x039f, 0x038d, 0x03a5, 0x03a9,
0x03ca, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f,
0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
0x03a8, 0x03a9, 0x0399, 0x03a5, 0x03b1, 0x03b5, 0x03b7, 0x03b9,
0x03cb, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7,
0x03c8, 0x03c9, 0x03b9, 0x03c5, 0x03bf, 0x03c5, 0x03c9, 0x03cf,
0x03b2, 0x03b8, 0x03a5, 0x03d2, 0x03d2, 0x03c6, 0x03c0, 0x03d7,
0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df,
0x03e0, 0x03e1, 0x03e2, 0x03e3, 0x03e4, 0x03e5, 0x03e6, 0x03e7,
0x03e8, 0x03e9, 0x03ea, 0x03eb, 0x03ec, 0x03ed, 0x03ee, 0x03ef,
0x03ba, 0x03c1, 0x03c2, 0x03f3, 0x0398, 0x03b5, 0x03f6, 0x03f7,
0x03f8, 0x03a3, 0x03fa, 0x03fb, 0x03fc, 0x03fd, 0x03fe, 0x03ff,
0x0415, 0x0415, 0x0402, 0x0413, 0x0404, 0x0405, 0x0406, 0x0406,
0x0408, 0x0409, 0x040a, 0x040b, 0x041a, 0x0418, 0x0423, 0x040f,
0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
0x0418, 0x0418, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f,
0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f,
0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
0x0438, 0x0438, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f,
0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f,
0x0435, 0x0435, 0x0452, 0x0433, 0x0454, 0x0455, 0x0456, 0x0456,
0x0458, 0x0459, 0x045a, 0x045b, 0x043a, 0x0438, 0x0443, 0x045f,
0x0460, 0x0461, 0x0462, 0x0463, 0x0464, 0x0465, 0x0466, 0x0467,
0x0468, 0x0469, 0x046a, 0x046b, 0x046c, 0x046d, 0x046e, 0x046f,
0x0470, 0x0471, 0x0472, 0x0473, 0x0474, 0x0475, 0x0474, 0x0475,
0x0478, 0x0479, 0x047a, 0x047b, 0x047c, 0x047d, 0x047e, 0x047f,
0x0480, 0x0481, 0x0482, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487,
0x0488, 0x0489, 0x048a, 0x048b, 0x048c, 0x048d, 0x048e, 0x048f,
0x0490, 0x0491, 0x0492, 0x0493, 0x0494, 0x0495, 0x0496, 0x0497,
0x0498, 0x0499, 0x049a, 0x049b, 0x049c, 0x049d, 0x049e, 0x049f,
0x04a0, 0x04a1, 0x04a2, 0x04a3, 0x04a4, 0x04a5, 0x04a6, 0x04a7,
0x04a8, 0x04a9, 0x04aa, 0x04ab, 0x04ac, 0x04ad, 0x04ae, 0x04af,
0x04b0, 0x04b1, 0x04b2, 0x04b3, 0x04b4, 0x04b5, 0x04b6, 0x04b7,
0x04b8, 0x04b9, 0x04ba, 0x04bb, 0x04bc, 0x04bd, 0x04be, 0x04bf,
0x04c0, 0x0416, 0x0436, 0x04c3, 0x04c4, 0x04c5, 0x04c6, 0x04c7,
0x04c8, 0x04c9, 0x04ca, 0x04cb, 0x04cc, 0x04cd, 0x04ce, 0x04cf,
0x0410, 0x0430, 0x0410, 0x0430, 0x04d4, 0x04d5, 0x0415, 0x0435,
0x04d8, 0x04d9, 0x04d8, 0x04d9, 0x0416, 0x0436, 0x0417, 0x0437,
0x04e0, 0x04e1, 0x0418, 0x0438, 0x0418, 0x0438, 0x041e, 0x043e,
0x04e8, 0x04e9, 0x04e8, 0x04e9, 0x042d, 0x044d, 0x0423, 0x0443,
0x0423, 0x0443, 0x0423, 0x0443, 0x0427, 0x0447, 0x04f6, 0x04f7,
0x042b, 0x044b, 0x04fa, 0x04fb, 0x04fc, 0x04fd, 0x04fe, 0x04ff,
};
// generated with:
// cat UnicodeData.txt | perl -e 'while (<>) { @foo = split(/;/); $foo[5] =~ s/<.*> //; $base[hex($foo[0])] = hex($foo[5]);} for ($i = 0; $i < 0x500; $i += 8) { for ($j = $i; $j < $i + 8; $j++) { printf("0x%04x, ", $base[$j] ? $base[$j] : $j)}; print "\n"; }'
|
09bicsekanjam-clone
|
java/jni/src/basechars.h
|
C
|
asf20
| 11,582
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_DICTIONARY_H
#define LATINIME_DICTIONARY_H
namespace latinime {
// 22-bit address = ~4MB dictionary size limit, which on average would be about 200k-300k words
#define ADDRESS_MASK 0x3FFFFF
// The bit that decides if an address follows in the next 22 bits
#define FLAG_ADDRESS_MASK 0x40
// The bit that decides if this is a terminal node for a word. The node could still have children,
// if the word has other endings.
#define FLAG_TERMINAL_MASK 0x80
#define FLAG_BIGRAM_READ 0x80
#define FLAG_BIGRAM_CHILDEXIST 0x40
#define FLAG_BIGRAM_CONTINUED 0x80
#define FLAG_BIGRAM_FREQ 0x7F
class Dictionary {
public:
Dictionary(void *dict, int typedLetterMultipler, int fullWordMultiplier, int dictSize);
int getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize);
int getBigrams(unsigned short *word, int length, int *codes, int codesSize,
unsigned short *outWords, int *frequencies, int maxWordLength, int maxBigrams,
int maxAlternatives);
bool isValidWord(unsigned short *word, int length);
void setAsset(void *asset) { mAsset = asset; }
void *getAsset() { return mAsset; }
~Dictionary();
private:
void getVersionNumber();
bool checkIfDictVersionIsLatest();
int getAddress(int *pos);
int getBigramAddress(int *pos, bool advance);
int getFreq(int *pos);
int getBigramFreq(int *pos);
void searchForTerminalNode(int address, int frequency);
bool getFirstBitOfByte(int *pos) { return (mDict[*pos] & 0x80) > 0; }
bool getSecondBitOfByte(int *pos) { return (mDict[*pos] & 0x40) > 0; }
bool getTerminal(int *pos) { return (mDict[*pos] & FLAG_TERMINAL_MASK) > 0; }
int getCount(int *pos) { return mDict[(*pos)++] & 0xFF; }
unsigned short getChar(int *pos);
int wideStrLen(unsigned short *str);
bool sameAsTyped(unsigned short *word, int length);
bool checkFirstCharacter(unsigned short *word);
bool addWord(unsigned short *word, int length, int frequency);
bool addWordBigram(unsigned short *word, int length, int frequency);
unsigned short toLowerCase(unsigned short c);
void getWordsRec(int pos, int depth, int maxDepth, bool completion, int frequency,
int inputIndex, int diffs);
int isValidWordRec(int pos, unsigned short *word, int offset, int length);
void registerNextLetter(unsigned short c);
unsigned char *mDict;
void *mAsset;
int *mFrequencies;
int *mBigramFreq;
int mMaxWords;
int mMaxBigrams;
int mMaxWordLength;
unsigned short *mOutputChars;
unsigned short *mBigramChars;
int *mInputCodes;
int mInputLength;
int mMaxAlternatives;
unsigned short mWord[128];
int mSkipPos;
int mMaxEditDistance;
int mFullWordMultiplier;
int mTypedLetterMultiplier;
int mDictSize;
int *mNextLettersFrequencies;
int mNextLettersSize;
int mVersion;
int mBigram;
};
// ----------------------------------------------------------------------------
}; // namespace latinime
#endif // LATINIME_DICTIONARY_H
|
09bicsekanjam-clone
|
java/jni/src/dictionary.h
|
C++
|
asf20
| 3,832
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_CHAR_UTILS_H
#define LATINIME_CHAR_UTILS_H
namespace latinime {
unsigned short latin_tolower(unsigned short c);
}; // namespace latinime
#endif // LATINIME_CHAR_UTILS_H
|
09bicsekanjam-clone
|
java/jni/src/char_utils.h
|
C++
|
asf20
| 811
|
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
//#define LOG_TAG "dictionary.cpp"
//#include <cutils/log.h>
#define LOGI
#include "dictionary.h"
#include "basechars.h"
#include "char_utils.h"
#define DEBUG_DICT 0
#define DICTIONARY_VERSION_MIN 200
#define DICTIONARY_HEADER_SIZE 2
#define NOT_VALID_WORD -99
namespace latinime {
Dictionary::Dictionary(void *dict, int typedLetterMultiplier, int fullWordMultiplier, int size)
{
mDict = (unsigned char*) dict;
mTypedLetterMultiplier = typedLetterMultiplier;
mFullWordMultiplier = fullWordMultiplier;
mDictSize = size;
getVersionNumber();
}
Dictionary::~Dictionary()
{
}
int Dictionary::getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize)
{
int suggWords;
mFrequencies = frequencies;
mOutputChars = outWords;
mInputCodes = codes;
mInputLength = codesSize;
mMaxAlternatives = maxAlternatives;
mMaxWordLength = maxWordLength;
mMaxWords = maxWords;
mSkipPos = skipPos;
mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
mNextLettersFrequencies = nextLetters;
mNextLettersSize = nextLettersSize;
if (checkIfDictVersionIsLatest()) {
getWordsRec(DICTIONARY_HEADER_SIZE, 0, mInputLength * 3, false, 1, 0, 0);
} else {
getWordsRec(0, 0, mInputLength * 3, false, 1, 0, 0);
}
// Get the word count
suggWords = 0;
while (suggWords < mMaxWords && mFrequencies[suggWords] > 0) suggWords++;
if (DEBUG_DICT) LOGI("Returning %d words", suggWords);
if (DEBUG_DICT) {
LOGI("Next letters: ");
for (int k = 0; k < nextLettersSize; k++) {
if (mNextLettersFrequencies[k] > 0) {
LOGI("%c = %d,", k, mNextLettersFrequencies[k]);
}
}
LOGI("\n");
}
return suggWords;
}
void
Dictionary::registerNextLetter(unsigned short c)
{
if (c < mNextLettersSize) {
mNextLettersFrequencies[c]++;
}
}
void
Dictionary::getVersionNumber()
{
mVersion = (mDict[0] & 0xFF);
mBigram = (mDict[1] & 0xFF);
LOGI("IN NATIVE SUGGEST Version: %d Bigram : %d \n", mVersion, mBigram);
}
// Checks whether it has the latest dictionary or the old dictionary
bool
Dictionary::checkIfDictVersionIsLatest()
{
return (mVersion >= DICTIONARY_VERSION_MIN) && (mBigram == 1 || mBigram == 0);
}
unsigned short
Dictionary::getChar(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
unsigned short ch = (unsigned short) (mDict[(*pos)++] & 0xFF);
// If the code is 255, then actual 16 bit code follows (in big endian)
if (ch == 0xFF) {
ch = ((mDict[*pos] & 0xFF) << 8) | (mDict[*pos + 1] & 0xFF);
(*pos) += 2;
}
return ch;
}
int
Dictionary::getAddress(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
if ((mDict[*pos] & FLAG_ADDRESS_MASK) == 0) {
*pos += 1;
} else {
address += (mDict[*pos] & (ADDRESS_MASK >> 16)) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & 0xFF;
if (checkIfDictVersionIsLatest()) {
// skipping bigram
int bigramExist = (mDict[*pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
(*pos) += 3;
nextBigramExist = (mDict[(*pos)++] & FLAG_BIGRAM_CONTINUED);
}
} else {
(*pos)++;
}
}
return freq;
}
int
Dictionary::wideStrLen(unsigned short *str)
{
if (!str) return 0;
unsigned short *end = str;
while (*end)
end++;
return end - str;
}
bool
Dictionary::addWord(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxWords) {
if (frequency > mFrequencies[insertAt]
|| (mFrequencies[insertAt] == frequency
&& length < wideStrLen(mOutputChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
if (insertAt < mMaxWords) {
memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
(char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
(mMaxWords - insertAt - 1) * sizeof(mFrequencies[0]));
mFrequencies[insertAt] = frequency;
memmove((char*) mOutputChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mOutputChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxWords - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mOutputChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
return true;
}
return false;
}
bool
Dictionary::addWordBigram(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Bigram: Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxBigrams) {
if (frequency > mBigramFreq[insertAt]
|| (mBigramFreq[insertAt] == frequency
&& length < wideStrLen(mBigramChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
LOGI("Bigram: InsertAt -> %d maxBigrams: %d\n", insertAt, mMaxBigrams);
if (insertAt < mMaxBigrams) {
memmove((char*) mBigramFreq + (insertAt + 1) * sizeof(mBigramFreq[0]),
(char*) mBigramFreq + insertAt * sizeof(mBigramFreq[0]),
(mMaxBigrams - insertAt - 1) * sizeof(mBigramFreq[0]));
mBigramFreq[insertAt] = frequency;
memmove((char*) mBigramChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mBigramChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxBigrams - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mBigramChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Bigram: Added word at %d\n", insertAt);
return true;
}
return false;
}
unsigned short
Dictionary::toLowerCase(unsigned short c) {
if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
c = BASE_CHARS[c];
}
if (c >='A' && c <= 'Z') {
c |= 32;
} else if (c > 127) {
c = latin_tolower(c);
}
return c;
}
bool
Dictionary::sameAsTyped(unsigned short *word, int length)
{
if (length != mInputLength) {
return false;
}
int *inputCodes = mInputCodes;
while (length--) {
if ((unsigned int) *inputCodes != (unsigned int) *word) {
return false;
}
inputCodes += mMaxAlternatives;
word++;
}
return true;
}
static char QUOTE = '\'';
void
Dictionary::getWordsRec(int pos, int depth, int maxDepth, bool completion, int snr, int inputIndex,
int diffs)
{
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > maxDepth) {
return;
}
if (diffs > mMaxEditDistance) {
return;
}
int count = getCount(&pos);
int *currentChars = NULL;
if (mInputLength <= inputIndex) {
completion = true;
} else {
currentChars = mInputCodes + (inputIndex * mMaxAlternatives);
}
for (int i = 0; i < count; i++) {
// -- at char
unsigned short c = getChar(&pos);
// -- at flag/add
unsigned short lowerC = toLowerCase(c);
bool terminal = getTerminal(&pos);
int childrenAddress = getAddress(&pos);
// -- after address or flag
int freq = 1;
if (terminal) freq = getFreq(&pos);
// -- after add or freq
// If we are only doing completions, no need to look at the typed characters.
if (completion) {
mWord[depth] = c;
if (terminal) {
addWord(mWord, depth + 1, freq * snr);
if (depth >= mInputLength && mSkipPos < 0) {
registerNextLetter(mWord[mInputLength]);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
completion, snr, inputIndex, diffs);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || mSkipPos == depth) {
// Skip the ' or other letter and continue deeper
mWord[depth] = c;
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth, false, snr, inputIndex, diffs);
}
} else {
int j = 0;
while (currentChars[j] > 0) {
if (currentChars[j] == lowerC || currentChars[j] == c) {
int addedWeight = j == 0 ? mTypedLetterMultiplier : 1;
mWord[depth] = c;
if (mInputLength == inputIndex + 1) {
if (terminal) {
if (//INCLUDE_TYPED_WORD_IF_VALID ||
!sameAsTyped(mWord, depth + 1)) {
int finalFreq = freq * snr * addedWeight;
if (mSkipPos < 0) finalFreq *= mFullWordMultiplier;
addWord(mWord, depth + 1, finalFreq);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1,
maxDepth, true, snr * addedWeight, inputIndex + 1,
diffs + (j > 0));
}
} else if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
false, snr * addedWeight, inputIndex + 1, diffs + (j > 0));
}
}
j++;
if (mSkipPos >= 0) break;
}
}
}
}
int
Dictionary::getBigramAddress(int *pos, bool advance)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
address += (mDict[*pos] & 0x3F) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
if (advance) {
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getBigramFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & FLAG_BIGRAM_FREQ;
return freq;
}
int
Dictionary::getBigrams(unsigned short *prevWord, int prevWordLength, int *codes, int codesSize,
unsigned short *bigramChars, int *bigramFreq, int maxWordLength, int maxBigrams,
int maxAlternatives)
{
mBigramFreq = bigramFreq;
mBigramChars = bigramChars;
mInputCodes = codes;
mInputLength = codesSize;
mMaxWordLength = maxWordLength;
mMaxBigrams = maxBigrams;
mMaxAlternatives = maxAlternatives;
if (mBigram == 1 && checkIfDictVersionIsLatest()) {
int pos = isValidWordRec(DICTIONARY_HEADER_SIZE, prevWord, 0, prevWordLength);
LOGI("Pos -> %d\n", pos);
if (pos < 0) {
return 0;
}
int bigramCount = 0;
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0 && bigramCount < maxBigrams) {
int bigramAddress = getBigramAddress(&pos, true);
int frequency = (FLAG_BIGRAM_FREQ & mDict[pos]);
// search for all bigrams and store them
searchForTerminalNode(bigramAddress, frequency);
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
bigramCount++;
}
}
return bigramCount;
}
return 0;
}
void
Dictionary::searchForTerminalNode(int addressLookingFor, int frequency)
{
// track word with such address and store it in an array
unsigned short word[mMaxWordLength];
int pos;
int followDownBranchAddress = DICTIONARY_HEADER_SIZE;
bool found = false;
char followingChar = ' ';
int depth = -1;
while(!found) {
bool followDownAddressSearchStop = false;
bool firstAddress = true;
bool haveToSearchAll = true;
if (depth >= 0) {
word[depth] = (unsigned short) followingChar;
}
pos = followDownBranchAddress; // pos start at count
int count = mDict[pos] & 0xFF;
LOGI("count - %d\n",count);
pos++;
for (int i = 0; i < count; i++) {
// pos at data
pos++;
// pos now at flag
if (!getFirstBitOfByte(&pos)) { // non-terminal
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = false;
}
}
}
pos += 3;
} else if (getFirstBitOfByte(&pos)) { // terminal
if (addressLookingFor == (pos-1)) { // found !!
depth++;
word[depth] = (0xFF & mDict[pos-1]);
found = true;
break;
}
if (getSecondBitOfByte(&pos)) { // address + freq (4 byte)
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
}
}
}
pos += 4;
} else { // freq only (2 byte)
pos += 2;
}
// skipping bigram
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
pos += 3;
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
}
} else {
pos++;
}
}
}
depth++;
if (followDownBranchAddress == 0) {
LOGI("ERROR!!! Cannot find bigram!!");
break;
}
}
if (checkFirstCharacter(word)) {
addWordBigram(word, depth, frequency);
}
}
bool
Dictionary::checkFirstCharacter(unsigned short *word)
{
// Checks whether this word starts with same character or neighboring characters of
// what user typed.
int *inputCodes = mInputCodes;
int maxAlt = mMaxAlternatives;
while (maxAlt > 0) {
if ((unsigned int) *inputCodes == (unsigned int) *word) {
return true;
}
inputCodes++;
maxAlt--;
}
return false;
}
bool
Dictionary::isValidWord(unsigned short *word, int length)
{
if (checkIfDictVersionIsLatest()) {
return (isValidWordRec(DICTIONARY_HEADER_SIZE, word, 0, length) != NOT_VALID_WORD);
} else {
return (isValidWordRec(0, word, 0, length) != NOT_VALID_WORD);
}
}
int
Dictionary::isValidWordRec(int pos, unsigned short *word, int offset, int length) {
// returns address of bigram data of that word
// return -99 if not found
int count = getCount(&pos);
unsigned short currentChar = (unsigned short) word[offset];
for (int j = 0; j < count; j++) {
unsigned short c = getChar(&pos);
int terminal = getTerminal(&pos);
int childPos = getAddress(&pos);
if (c == currentChar) {
if (offset == length - 1) {
if (terminal) {
return (pos+1);
}
} else {
if (childPos != 0) {
int t = isValidWordRec(childPos, word, offset + 1, length);
if (t > 0) {
return t;
}
}
}
}
if (terminal) {
getFreq(&pos);
}
// There could be two instances of each alphabet - upper and lower case. So continue
// looking ...
}
return NOT_VALID_WORD;
}
} // namespace latinime
|
09bicsekanjam-clone
|
java/jni/src/dictionary.cpp
|
C++
|
asf20
| 19,272
|
APP_ABI := all
|
09bicsekanjam-clone
|
java/jni/Application.mk
|
Makefile
|
asf20
| 15
|
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <jni.h>
#include "dictionary.h"
// ----------------------------------------------------------------------------
using namespace latinime;
//
// helper function to throw an exception
//
static void throwException(JNIEnv *env, const char* ex, const char* fmt, int data)
{
if (jclass cls = env->FindClass(ex)) {
char msg[1000];
sprintf(msg, fmt, data);
env->ThrowNew(cls, msg);
env->DeleteLocalRef(cls);
}
}
static jint latinime_BinaryDictionary_open
(JNIEnv *env, jobject object, jobject dictDirectBuffer,
jint typedLetterMultiplier, jint fullWordMultiplier, jint size)
{
void *dict = env->GetDirectBufferAddress(dictDirectBuffer);
if (dict == NULL) {
fprintf(stderr, "DICT: Dictionary buffer is null\n");
return 0;
}
Dictionary *dictionary = new Dictionary(dict, typedLetterMultiplier, fullWordMultiplier, size);
return (jint) dictionary;
}
static int latinime_BinaryDictionary_getSuggestions(
JNIEnv *env, jobject object, jint dict, jintArray inputArray, jint arraySize,
jcharArray outputArray, jintArray frequencyArray, jint maxWordLength, jint maxWords,
jint maxAlternatives, jint skipPos, jintArray nextLettersArray, jint nextLettersSize)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *nextLetters = nextLettersArray != NULL ? env->GetIntArrayElements(nextLettersArray, NULL)
: NULL;
int count = dictionary->getSuggestions(inputCodes, arraySize, (unsigned short*) outputChars,
frequencies, maxWordLength, maxWords, maxAlternatives, skipPos, nextLetters,
nextLettersSize);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
if (nextLetters) {
env->ReleaseIntArrayElements(nextLettersArray, nextLetters, 0);
}
return count;
}
static int latinime_BinaryDictionary_getBigrams
(JNIEnv *env, jobject object, jint dict, jcharArray prevWordArray, jint prevWordLength,
jintArray inputArray, jint inputArraySize, jcharArray outputArray,
jintArray frequencyArray, jint maxWordLength, jint maxBigrams, jint maxAlternatives)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
jchar *prevWord = env->GetCharArrayElements(prevWordArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int count = dictionary->getBigrams((unsigned short*) prevWord, prevWordLength, inputCodes,
inputArraySize, (unsigned short*) outputChars, frequencies, maxWordLength, maxBigrams,
maxAlternatives);
env->ReleaseCharArrayElements(prevWordArray, prevWord, JNI_ABORT);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
return count;
}
static jboolean latinime_BinaryDictionary_isValidWord
(JNIEnv *env, jobject object, jint dict, jcharArray wordArray, jint wordLength)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return (jboolean) false;
jchar *word = env->GetCharArrayElements(wordArray, NULL);
jboolean result = dictionary->isValidWord((unsigned short*) word, wordLength);
env->ReleaseCharArrayElements(wordArray, word, JNI_ABORT);
return result;
}
static void latinime_BinaryDictionary_close
(JNIEnv *env, jobject object, jint dict)
{
Dictionary *dictionary = (Dictionary*) dict;
delete (Dictionary*) dict;
}
// ----------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
{"openNative", "(Ljava/nio/ByteBuffer;III)I",
(void*)latinime_BinaryDictionary_open},
{"closeNative", "(I)V", (void*)latinime_BinaryDictionary_close},
{"getSuggestionsNative", "(I[II[C[IIIII[II)I", (void*)latinime_BinaryDictionary_getSuggestions},
{"isValidWordNative", "(I[CI)Z", (void*)latinime_BinaryDictionary_isValidWord},
{"getBigramsNative", "(I[CI[II[C[IIII)I", (void*)latinime_BinaryDictionary_getBigrams}
};
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
fprintf(stderr,
"Native registration unable to find class '%s'\n", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
fprintf(stderr, "RegisterNatives failed for '%s'\n", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
static int registerNatives(JNIEnv *env)
{
const char* const kClassPathName = "org/pocketworkstation/pckeyboard/BinaryDictionary";
return registerNativeMethods(env,
kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
}
/*
* Returns the JNI version on success, -1 on failure.
*/
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
fprintf(stderr, "ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
fprintf(stderr, "ERROR: BinaryDictionary native registration failed\n");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
|
09bicsekanjam-clone
|
java/jni/jni/org_pocketworkstation_pckeyboard_BinaryDictionary.cpp
|
C++
|
asf20
| 6,786
|
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES += $(LOCAL_PATH)/src
LOCAL_SRC_FILES := \
jni/org_pocketworkstation_pckeyboard_BinaryDictionary.cpp \
src/dictionary.cpp \
src/char_utils.cpp
#ifneq ($(TARGET_ARCH),x86)
#LOCAL_NDK_VERSION := 4
#LOCAL_SDK_VERSION := 8
#endif
LOCAL_MODULE := libjni_pckeyboard
LOCAL_MODULE_TAGS := user
include $(BUILD_SHARED_LIBRARY)
|
09bicsekanjam-clone
|
java/jni/Android.mk
|
Makefile
|
asf20
| 394
|
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := PCKeyboard
LOCAL_CERTIFICATE := shared
LOCAL_JNI_SHARED_LIBRARIES := libjni_pckeyboard
LOCAL_STATIC_JAVA_LIBRARIES := android-common
#LOCAL_AAPT_FLAGS := -0 .dict
LOCAL_SDK_VERSION := current
LOCAL_PROGUARD_FLAG_FILES := proguard.flags
include $(BUILD_PACKAGE)
|
09bicsekanjam-clone
|
java/Android.mk
|
Makefile
|
asf20
| 426
|
#!/bin/bash
Res=res/
Alt=donottranslate-altchars.xml
Map=donottranslate-keymap.xml
Out=assets/kbd/
mkdir -p "$Out"
for Dir in res/values res/values-*
do
[ -f $Dir/$Map ] || continue # -o -f $Dir/$Alt ] || continue
Args="$Res/values/$Alt"
[ -f $Dir/$Alt ] && Args="$Args $Dir/$Alt"
Args="$Args $Res/values/$Map"
[ -f $Dir/$Map ] && Args="$Args $Dir/$Map"
if [ -n "$CONVERT_MAPS" ]; then
Loc=$(echo "$Dir" | sed 's/res.values-*//; s/\/$//; s/^$/en/')
perl CheckMap.pl -c $Args > "$Out/map-full-$Loc.txt"
else
echo >&2 -n "$Dir: "
perl CheckMap.pl $Args
fi
done
|
09bicsekanjam-clone
|
java/CheckMaps.sh
|
Shell
|
asf20
| 594
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
/**
*
*/
public class MediaButtonIntentReceiver extends BroadcastReceiver implements Constants {
private static final int MSG_PRESSED = 1, MSG_TIMEOUT = 2;
private static final long CLICK_DELAY = 300, LONG_PRESS_DELAY = 1000;
private static final int SINGLE_CLICK = 1, DOUBLE_CLICK = 2, TRIPLE_CLICK = 3;
private static boolean mPressedDown, mLongPressed = false;
private static long mFirstTime;
private static int mPressedCount = 0;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_PRESSED:
mHandler.removeMessages(MSG_TIMEOUT);
if (mPressedCount < Integer.MAX_VALUE) {
mPressedCount++;
}
break;
case MSG_TIMEOUT:
mHandler.removeCallbacksAndMessages(null);
switch (mPressedCount) {
case SINGLE_CLICK:
sendMediaCommand((Context) msg.obj, CMDTOGGLEPAUSE);
break;
case DOUBLE_CLICK:
sendMediaCommand((Context) msg.obj, CMDNEXT);
break;
case TRIPLE_CLICK:
sendMediaCommand((Context) msg.obj, CMDPREVIOUS);
break;
}
mPressedCount = 0;
break;
}
}
};
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction)) {
Intent i = new Intent(context, MusicPlaybackService.class);
i.setAction(SERVICECMD);
i.putExtra(CMDNAME, CMDPAUSE);
context.startService(i);
} else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) return;
int keycode = event.getKeyCode();
int action = event.getAction();
long eventtime = event.getEventTime();
switch (keycode) {
case KeyEvent.KEYCODE_MEDIA_STOP:
sendMediaCommand(context, CMDSTOP);
break;
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
sendMediaCommand(context, CMDTOGGLEPAUSE);
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
sendMediaCommand(context, CMDNEXT);
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
sendMediaCommand(context, CMDPREVIOUS);
break;
case KeyEvent.KEYCODE_HEADSETHOOK:
processHeadsetHookEvent(context, action, eventtime);
break;
}
}
}
private void processHeadsetHookEvent(Context context, int action, long eventtime) {
switch (action) {
case KeyEvent.ACTION_DOWN:
if (!mPressedDown) {
mPressedDown = true;
mFirstTime = eventtime;
mHandler.sendEmptyMessage(MSG_PRESSED);
} else if (!mLongPressed) {
if (eventtime - mFirstTime >= LONG_PRESS_DELAY) {
mPressedCount = 0;
mLongPressed = true;
sendMediaCommand(context, CMDTOGGLEFAVORITE);
mHandler.removeCallbacksAndMessages(null);
}
}
break;
case KeyEvent.ACTION_UP:
if (!mLongPressed) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TIMEOUT, context),
CLICK_DELAY);
}
mPressedDown = false;
mLongPressed = false;
break;
default:
break;
}
}
private void sendMediaCommand(Context context, String command) {
Intent i = new Intent(context, MusicPlaybackService.class);
i.setAction(SERVICECMD);
i.putExtra(CMDNAME, command);
context.startService(i);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/MediaButtonIntentReceiver.java
|
Java
|
gpl3
| 4,373
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.app;
import java.util.ArrayList;
import org.yammp.Constants;
import org.yammp.IMusicPlaybackService;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import org.yammp.util.ServiceToken;
import org.yammp.view.EqualizerView;
import org.yammp.view.EqualizerView.OnBandLevelChangeListener;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class Equalizer extends SherlockFragmentActivity implements Constants, ServiceConnection,
OnBandLevelChangeListener {
private IMusicPlaybackService mService = null;
private ServiceToken mToken;
private Spinner mSpinner;
private EqualizerView mEqualizerView;
private MediaUtils mUtils;
@Override
public void onBandLevelChange(short band, short level) {
if (mService != null) {
try {
mService.eqSetBandLevel(band, level);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(R.layout.equalizer);
mEqualizerView = (EqualizerView) findViewById(R.id.equalizer_view);
mEqualizerView.setOnBandLevelChangeListener(this);
mSpinner = (Spinner) findViewById(R.id.presets);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mInflater = getSupportMenuInflater();
mInflater.inflate(R.menu.equalizer, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case EQUALIZER_PRESETS:
break;
case EQUALIZER_RESET:
resetEqualizer();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onServiceConnected(ComponentName classname, IBinder obj) {
mService = IMusicPlaybackService.Stub.asInterface(obj);
setupEqualizerFxAndUI();
}
@Override
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
@Override
public void onStart() {
super.onStart();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mToken = mUtils.bindToService(this);
if (mToken == null) {
finish();
}
}
@Override
public void onStop() {
mUtils.unbindFromService(mToken);
mService = null;
super.onStop();
}
private void resetEqualizer() {
if (mService != null) {
try {
mService.eqReset();
} catch (RemoteException e) {
e.printStackTrace();
}
setupEqualizerFxAndUI();
}
}
private void setPreset(short preset_id) {
if (mService != null) {
try {
mService.eqUsePreset(preset_id);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private void setupEqualizerFxAndUI() {
if (mService == null) return;
try {
short bands = (short) mService.eqGetNumberOfBands();
mEqualizerView.setNumberOfBands(bands);
int[] value = mService.eqGetBandLevelRange();
if (value != null) {
short[] param = new short[value.length];
for (short i = 0; i < value.length; i++) {
param[i] = (short) value[i];
}
mEqualizerView.setBandLevelRange(param);
}
for (short i = 0; i < bands; i++) {
mEqualizerView.setCenterFreq(i, mService.eqGetCenterFreq(i));
mEqualizerView.setBandLevel(i, (short) mService.eqGetBandLevel(i));
}
ArrayList<String> list = new ArrayList<String>();
String mPresetName;
for (short preset_id = 0; preset_id < mService.eqGetNumberOfPresets(); preset_id++) {
mPresetName = mService.eqGetPresetName(preset_id);
list.add(mPresetName);
}
CharSequence[] items = list.toArray(new CharSequence[list.size()]);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/Equalizer.java
|
Java
|
gpl3
| 4,986
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.dialog.ScanningProgress;
import org.yammp.fragment.MusicBrowserFragment;
import org.yammp.fragment.MusicPlaybackFragment;
import org.yammp.fragment.VideoFragment;
import org.yammp.util.PreferencesEditor;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.widget.ArrayAdapter;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.Window;
public class MediaPlayerActivity extends BaseActivity implements Constants {
private ActionBar mActionBar;
private PagesAdapter mAdapter;
private PreferencesEditor mPrefs;
@Override
public void onCreate(Bundle icicle) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(icicle);
mPrefs = new PreferencesEditor(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.main);
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
mActionBar.setDisplayShowTitleEnabled(false);
String mount_state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(mount_state)
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(mount_state)) {
startActivity(new Intent(this, ScanningProgress.class));
finish();
}
mAdapter = new PagesAdapter(mActionBar);
mAdapter.addPage(MusicBrowserFragment.class, getString(R.string.label_music));
mAdapter.addPage(VideoFragment.class, getString(R.string.label_video));
mAdapter.addPage(MusicPlaybackFragment.class, getString(R.string.now_playing));
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getIntent().getExtras() != null ? getIntent().getExtras() : new Bundle());
super.onSaveInstanceState(outState);
}
private class PagesAdapter extends ArrayAdapter<String> implements OnNavigationListener {
private ArrayList<Class<? extends Fragment>> mFragments = new ArrayList<Class<? extends Fragment>>();
public PagesAdapter(ActionBar actionbar) {
super(actionbar.getThemedContext(), R.layout.sherlock_spinner_item,
new ArrayList<String>());
setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
actionbar.setListNavigationCallbacks(this, this);
}
public void addPage(Class<? extends Fragment> fragment, String name) {
add(name);
mFragments.add(fragment);
}
@Override
public boolean onNavigationItemSelected(int position, long id) {
Fragment instance;
try {
instance = mFragments.get(position).getConstructor(new Class[] {}).newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.content, instance)
.commit();
return true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return false;
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/MediaPlayerActivity.java
|
Java
|
gpl3
| 4,136
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import org.yammp.Constants;
import org.yammp.R;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
public class AppearanceSettingsActivity extends SherlockPreferenceActivity implements Constants {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
getPreferenceManager().setSharedPreferencesName(SHAREDPREFS_PREFERENCES);
addPreferencesFromResource(R.xml.appearance_settings);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case GOTO_HOME:
intent = new Intent(INTENT_PLAYBACK_VIEWER);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/AppearanceSettingsActivity.java
|
Java
|
gpl3
| 1,842
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import org.yammp.fragment.PluginFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import com.actionbarsherlock.app.SherlockFragmentActivity;
/**
* Demonstration of the implementation of a custom Loader.
*/
public class PluginsManagerActivity extends SherlockFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getSupportFragmentManager();
// Create the list fragment and add it as our sole content.
if (fm.findFragmentById(android.R.id.content) == null) {
PluginFragment list = new PluginFragment();
fm.beginTransaction().replace(android.R.id.content, list).commit();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/PluginsManagerActivity.java
|
Java
|
gpl3
| 1,548
|
package org.yammp.app;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class BaseActivity extends SherlockFragmentActivity implements ViewFactory {
private AsyncBackgroundEffect mBackgroundEffectTask;
private ImageSwitcher mBackground;
private MediaUtils mUtils;
@Override
public View makeView() {
ImageView view = new ImageView(this);
view.setScaleType(ImageView.ScaleType.FIT_XY);
view.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
}
public void setBackground(long song_id, long album_id) {
if (mBackgroundEffectTask != null) {
mBackgroundEffectTask.cancel(true);
}
mBackgroundEffectTask = new AsyncBackgroundEffect();
mBackgroundEffectTask.execute(song_id, album_id);
}
@Override
public void setContentView(int layoutResId) {
FrameLayout layout = new FrameLayout(this);
mBackground = new ImageSwitcher(this);
mBackground.setFactory(this);
mBackground.setInAnimation(this, android.R.anim.fade_in);
mBackground.setOutAnimation(this, android.R.anim.fade_out);
layout.addView(mBackground, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
layout.addView(getLayoutInflater().inflate(layoutResId, null),
new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
super.setContentView(layout);
}
private class AsyncBackgroundEffect extends AsyncTask<Long, Void, Drawable> {
@Override
public Drawable doInBackground(Long... params) {
Bitmap bitmap;
if (params == null || params.length != 2) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_music);
} else {
bitmap = mUtils.getArtwork(params[0], params[1]);
}
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_music);
}
float density = getResources().getDisplayMetrics().density;
Drawable drawable = mUtils.getBackgroundImage(bitmap, mBackground.getWidth(),
mBackground.getHeight(), 1.0f / 32 / density);
return drawable;
}
@Override
public void onPostExecute(Drawable result) {
if (result != null) {
mBackground.setImageDrawable(result);
} else {
mBackground.setImageResource(R.drawable.ic_launcher_music);
}
mBackgroundEffectTask = null;
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/BaseActivity.java
|
Java
|
gpl3
| 3,076
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import org.yammp.Constants;
import org.yammp.R;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
public class MusicSettingsActivity extends SherlockPreferenceActivity implements Constants,
OnPreferenceClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(SHAREDPREFS_PREFERENCES);
addPreferencesFromResource(R.xml.music_settings);
findPreference(KEY_RESCAN_MEDIA).setOnPreferenceClickListener(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case GOTO_HOME:
intent = new Intent(INTENT_MUSIC_BROWSER);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPreferenceClick(Preference preference) {
if (KEY_RESCAN_MEDIA.equals(preference.getKey())) {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
return false;
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/MusicSettingsActivity.java
|
Java
|
gpl3
| 2,277
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import org.yammp.Constants;
import org.yammp.IMusicPlaybackService;
import org.yammp.MusicPlaybackService;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.fragment.LyricsFragment;
import org.yammp.util.ColorAnalyser;
import org.yammp.util.EqualizerWrapper;
import org.yammp.util.MediaUtils;
import org.yammp.util.PreferencesEditor;
import org.yammp.util.ServiceToken;
import org.yammp.util.VisualizerCompat;
import org.yammp.util.VisualizerWrapper;
import org.yammp.util.VisualizerWrapper.OnDataChangedListener;
import org.yammp.view.SliderView;
import org.yammp.view.SliderView.OnValueChangeListener;
import org.yammp.view.TouchPaintView;
import org.yammp.view.TouchPaintView.EventListener;
import org.yammp.view.VisualizerViewFftSpectrum;
import org.yammp.view.VisualizerViewWaveForm;
import org.yammp.widget.RepeatingImageButton;
import org.yammp.widget.RepeatingImageButton.OnRepeatListener;
import android.app.SearchManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
public class MusicPlaybackActivity extends SherlockFragmentActivity implements Constants,
OnLongClickListener, ServiceConnection {
private boolean mSeeking = false;
private boolean mDeviceHasDpad;
private long mStartSeekPos = 0;
private long mLastSeekEventTime;
private IMusicPlaybackService mService = null;
private RepeatingImageButton mPrevButton;
private ImageButton mPauseButton;
private RepeatingImageButton mNextButton;
private AsyncColorAnalyser mColorAnalyser;
private ServiceToken mToken;
private boolean mIntentDeRegistered = false;
private PreferencesEditor mPrefs;
private int mUIColor = Color.WHITE;
private boolean mAutoColor = true;
private boolean mBlurBackground = false;
private VisualizerViewFftSpectrum mVisualizerViewFftSpectrum;
private VisualizerViewWaveForm mVisualizerViewWaveForm;
private boolean mDisplayVisualizer = false;
private FrameLayout mVisualizerView;
private VisualizerCompat mVisualizer;
private static final int RESULT_ALBUMART_DOWNLOADED = 1;
private boolean mShowFadeAnimation = false;
private boolean mLyricsWakelock = DEFAULT_LYRICS_WAKELOCK;
private TextView mTrackName, mTrackDetail;
private TouchPaintView mTouchPaintView;
private long mPosOverride = -1;
private boolean mFromTouch = false;
private long mDuration;
private boolean paused;
private static final int REFRESH = 1;
private static final int QUIT = 2;
private TextView mCurrentTime, mTotalTime;
private OnDataChangedListener mDataChangedListener = new OnDataChangedListener() {
@Override
public void onFftDataChanged(byte[] data, int len) {
if (mVisualizerViewFftSpectrum != null) {
mVisualizerViewFftSpectrum.updateVisualizer(data);
}
}
@Override
public void onWaveDataChanged(byte[] data, int len, boolean scoop) {
if (mVisualizerViewWaveForm != null) {
mVisualizerViewWaveForm.updateVisualizer(data, scoop);
}
}
};
int mInitialX = -1;
int mLastX = -1;
int mTextWidth = 0;
int mViewWidth = 0;
boolean mDraggingLabel = false;
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser || mService == null) return;
mPosOverride = mDuration * progress / 1000;
try {
mService.seek(mPosOverride);
} catch (RemoteException ex) {
}
refreshNow();
// trackball event, allow progress updates
if (!mFromTouch) {
refreshNow();
mPosOverride = -1;
}
}
@Override
public void onStartTrackingTouch(SeekBar bar) {
mLastSeekEventTime = 0;
mFromTouch = true;
mHandler.removeMessages(REFRESH);
}
@Override
public void onStopTrackingTouch(SeekBar bar) {
mPosOverride = -1;
mFromTouch = false;
// Ensure that progress is properly updated in the future,
mHandler.sendEmptyMessage(REFRESH);
}
};
private EventListener mTouchPaintEventListener = new EventListener() {
@Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
return true;
}
};
private View.OnClickListener mPauseListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doPauseResume();
}
};
private View.OnClickListener mPrevListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doPrev();
}
};
private View.OnClickListener mNextListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doNext();
}
};
private OnRepeatListener mRewListener = new OnRepeatListener() {
@Override
public void onRepeat(View v, long howlong, int repcnt) {
scanBackward(repcnt, howlong);
}
};
private OnRepeatListener mFfwdListener = new OnRepeatListener() {
@Override
public void onRepeat(View v, long howlong, int repcnt) {
scanForward(repcnt, howlong);
}
};
private final static int DISABLE_VISUALIZER = 0;
private final static int ENABLE_VISUALIZER = 1;
Handler mVisualizerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mVisualizerHandler.removeCallbacksAndMessages(null);
switch (msg.what) {
case DISABLE_VISUALIZER:
mVisualizer.setEnabled(false);
break;
case ENABLE_VISUALIZER:
mVisualizer.setEnabled(true);
break;
}
}
};
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
long next = refreshNow();
queueNextRefresh(next);
break;
case QUIT:
Toast.makeText(getApplicationContext(), R.string.service_start_error_msg,
Toast.LENGTH_SHORT);
finish();
break;
default:
break;
}
}
};
private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_META_CHANGED.equals(action)) {
// redraw the artist/title info and
// set new max for progress bar
updateTrackInfo(mShowFadeAnimation);
invalidateOptionsMenu();
setPauseButtonImage();
queueNextRefresh(1);
} else if (BROADCAST_PLAYSTATE_CHANGED.equals(action)) {
setPauseButtonImage();
setVisualizerView();
} else if (BROADCAST_FAVORITESTATE_CHANGED.equals(action)) {
invalidateOptionsMenu();
}
}
};
private BroadcastReceiver mScreenTimeoutListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
if (mIntentDeRegistered) {
IntentFilter f = new IntentFilter();
f.addAction(BROADCAST_PLAYSTATE_CHANGED);
f.addAction(BROADCAST_META_CHANGED);
f.addAction(BROADCAST_FAVORITESTATE_CHANGED);
registerReceiver(mStatusListener, new IntentFilter(f));
mIntentDeRegistered = false;
}
updateTrackInfo(false);
if (mDisplayVisualizer) {
enableVisualizer();
}
long next = refreshNow();
queueNextRefresh(next);
invalidateOptionsMenu();
} else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
paused = true;
disableVisualizer(true);
if (!mIntentDeRegistered) {
mHandler.removeMessages(REFRESH);
unregisterReceiver(mStatusListener);
mIntentDeRegistered = true;
}
}
}
};
private MediaUtils mUtils;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
requestWindowFeature(Window.FEATURE_PROGRESS);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mPrefs = new PreferencesEditor(this);
configureActivity();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.music_playback, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int repcnt = event.getRepeatCount();
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (!mPrevButton.hasFocus()) {
mPrevButton.requestFocus();
}
scanBackward(repcnt, event.getEventTime() - event.getDownTime());
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (!mNextButton.hasFocus()) {
mNextButton.requestFocus();
}
scanForward(repcnt, event.getEventTime() - event.getDownTime());
return true;
// case KeyEvent.KEYCODE_R:
// toggleRepeat();
// return true;
//
// case KeyEvent.KEYCODE_S:
// toggleShuffle();
// return true;
case KeyEvent.KEYCODE_N:
if (mService != null) {
try {
mService.next();
return true;
} catch (RemoteException e) {
e.printStackTrace();
}
} else
return false;
case KeyEvent.KEYCODE_P:
if (mService != null) {
try {
mService.prev();
return true;
} catch (RemoteException e) {
e.printStackTrace();
}
} else
return false;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_SPACE:
doPauseResume();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
try {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
if (mStartSeekPos < 1000) {
mService.prev();
} else {
mService.seek(0);
}
} else {
scanBackward(-1, event.getEventTime() - event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
mService.next();
} else {
scanForward(-1, event.getEventTime() - event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
}
} catch (RemoteException ex) {
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onLongClick(View v) {
// TODO search media info
String track = getTitle().toString();
String artist = "";// mArtistNameView.getText().toString();
String album = "";// mAlbumNameView.getText().toString();
CharSequence title = getString(R.string.mediasearch, track);
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, track);
String query = track;
if (!getString(R.string.unknown_artist).equals(artist)
&& !getString(R.string.unknown_album).equals(album)) {
query = artist + " " + track;
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
} else if (getString(R.string.unknown_artist).equals(artist)
&& !getString(R.string.unknown_album).equals(album)) {
query = album + " " + track;
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
} else if (!getString(R.string.unknown_artist).equals(artist)
&& getString(R.string.unknown_album).equals(album)) {
query = artist + " " + track;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
}
i.putExtra(SearchManager.QUERY, query);
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
startActivity(Intent.createChooser(i, title));
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case MENU_ADD_TO_PLAYLIST:
intent = new Intent(INTENT_ADD_TO_PLAYLIST);
long[] list_to_be_added = new long[1];
list_to_be_added[0] = mUtils.getCurrentAudioId();
intent.putExtra(INTENT_KEY_LIST, list_to_be_added);
startActivity(intent);
break;
case EQUALIZER:
intent = new Intent(INTENT_EQUALIZER);
startActivity(intent);
break;
case MENU_SLEEP_TIMER:
intent = new Intent(INTENT_SLEEP_TIMER);
startActivity(intent);
break;
case DELETE_ITEMS:
intent = new Intent(INTENT_DELETE_ITEMS);
Bundle bundle = new Bundle();
bundle.putString(
INTENT_KEY_PATH,
Uri.withAppendedPath(Audio.Media.EXTERNAL_CONTENT_URI,
Uri.encode(String.valueOf(mUtils.getCurrentAudioId()))).toString());
intent.putExtras(bundle);
startActivity(intent);
break;
case SETTINGS:
intent = new Intent(INTENT_APPEARANCE_SETTINGS);
startActivity(intent);
break;
case GOTO_HOME:
intent = new Intent(INTENT_MUSIC_BROWSER);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
break;
case MENU_ADD_TO_FAVORITES:
toggleFavorite();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(EQUALIZER);
if (item != null) {
item.setVisible(EqualizerWrapper.isSupported());
}
item = menu.findItem(MENU_ADD_TO_FAVORITES);
try {
if (item != null && mService != null) {
item.setIcon(mService.isFavorite(mService.getAudioId()) ? R.drawable.ic_menu_star
: R.drawable.ic_menu_star_off);
}
} catch (RemoteException e) {
e.printStackTrace();
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public void onResume() {
super.onResume();
if (mIntentDeRegistered) {
paused = false;
}
setPauseButtonImage();
}
@Override
public void onServiceConnected(ComponentName classname, IBinder obj) {
mService = IMusicPlaybackService.Stub.asInterface(obj);
try {
if (mService.getAudioId() >= 0 || mService.isPlaying() || mService.getPath() != null) {
updateTrackInfo(false);
long next = refreshNow();
queueNextRefresh(next);
setPauseButtonImage();
invalidateOptionsMenu();
mVisualizer = VisualizerWrapper.getInstance(mService.getAudioSessionId(), 50);
mDisplayVisualizer = mPrefs.getBooleanState(KEY_DISPLAY_VISUALIZER, false);
boolean mFftEnabled = String.valueOf(VISUALIZER_TYPE_FFT_SPECTRUM).equals(
mPrefs.getStringPref(KEY_VISUALIZER_TYPE, "1"));
boolean mWaveEnabled = String.valueOf(VISUALIZER_TYPE_WAVE_FORM).equals(
mPrefs.getStringPref(KEY_VISUALIZER_TYPE, "1"));
mVisualizerView.removeAllViews();
if (mFftEnabled) {
mVisualizerView.addView(mVisualizerViewFftSpectrum);
}
if (mWaveEnabled) {
mVisualizerView.addView(mVisualizerViewWaveForm);
}
mVisualizer.setFftEnabled(mFftEnabled);
mVisualizer.setWaveFormEnabled(mWaveEnabled);
mVisualizer.setOnDataChangedListener(mDataChangedListener);
setVisualizerView();
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(getApplicationContext(), MediaPlayerActivity.class);
startActivity(intent);
finish();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName classname) {
mVisualizer.release();
mService = null;
finish();
}
@Override
public void onStart() {
super.onStart();
paused = false;
mToken = mUtils.bindToService(this);
if (mToken == null) {
// something went wrong
mHandler.sendEmptyMessage(QUIT);
}
loadPreferences();
if (mBlurBackground) {
getWindow().addFlags(LayoutParams.FLAG_BLUR_BEHIND);
} else {
getWindow().clearFlags(LayoutParams.FLAG_BLUR_BEHIND);
}
if (mLyricsWakelock) {
getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
}
try {
float mTransitionAnimation = Settings.System.getFloat(getContentResolver(),
Settings.System.TRANSITION_ANIMATION_SCALE);
if (mTransitionAnimation > 0.0) {
mShowFadeAnimation = true;
} else {
mShowFadeAnimation = false;
}
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
IntentFilter f = new IntentFilter();
f.addAction(BROADCAST_PLAYSTATE_CHANGED);
f.addAction(BROADCAST_META_CHANGED);
f.addAction(BROADCAST_FAVORITESTATE_CHANGED);
registerReceiver(mStatusListener, new IntentFilter(f));
IntentFilter s = new IntentFilter();
s.addAction(Intent.ACTION_SCREEN_ON);
s.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenTimeoutListener, new IntentFilter(s));
long next = refreshNow();
queueNextRefresh(next);
}
@Override
public void onStop() {
paused = true;
if (!mIntentDeRegistered) {
mHandler.removeMessages(REFRESH);
unregisterReceiver(mStatusListener);
}
unregisterReceiver(mScreenTimeoutListener);
getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
mUtils.unbindFromService(mToken);
mService = null;
super.onStop();
}
private void configureActivity() {
setContentView(R.layout.music_playback);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setCustomView(R.layout.actionbar_music_playback);
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
View mCustomView = mActionBar.getCustomView();
mTouchPaintView = (TouchPaintView) mCustomView.findViewById(R.id.touch_paint);
mTouchPaintView.setEventListener(mTouchPaintEventListener);
mTrackName = (TextView) mCustomView.findViewById(R.id.track_name);
mTrackDetail = (TextView) mCustomView.findViewById(R.id.track_detail);
mCurrentTime = (TextView) mCustomView.findViewById(R.id.current_time);
mTotalTime = (TextView) mCustomView.findViewById(R.id.total_time);
/*
* mAlbum.setOnClickListener(mQueueListener);
* mAlbum.setOnLongClickListener(mSearchAlbumArtListener);
*/
mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setRepeatListener(mRewListener, 260);
mPauseButton = (ImageButton) findViewById(R.id.pause);
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
mNextButton = (RepeatingImageButton) findViewById(R.id.next);
mNextButton.setOnClickListener(mNextListener);
mNextButton.setRepeatListener(mFfwdListener, 260);
mDeviceHasDpad = getResources().getConfiguration().navigation == Configuration.NAVIGATION_DPAD;
mVisualizerViewFftSpectrum = new VisualizerViewFftSpectrum(this);
mVisualizerViewWaveForm = new VisualizerViewWaveForm(this);
mVisualizerView = (FrameLayout) findViewById(R.id.visualizer_view);
}
private void disableVisualizer(boolean animation) {
if (mVisualizer != null) {
if (mVisualizerView.getVisibility() == View.VISIBLE) {
mVisualizerView.setVisibility(View.INVISIBLE);
if (mShowFadeAnimation) {
mVisualizerView.startAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
}
if (animation) {
mVisualizerHandler.sendEmptyMessageDelayed(DISABLE_VISUALIZER, AnimationUtils
.loadAnimation(this, android.R.anim.fade_out).getDuration());
} else {
mVisualizerHandler.sendEmptyMessage(DISABLE_VISUALIZER);
}
}
}
}
private void doNext() {
if (mService == null) return;
try {
mService.next();
} catch (RemoteException ex) {
}
}
private void doPauseResume() {
try {
if (mService != null) {
if (mService.isPlaying()) {
mService.pause();
} else {
mService.play();
}
refreshNow();
setPauseButtonImage();
}
} catch (RemoteException ex) {
}
}
private void doPrev() {
if (mService == null) return;
try {
if (mService.position() < 2000) {
mService.prev();
} else {
mService.seek(0);
mService.play();
}
} catch (RemoteException ex) {
}
}
private void enableVisualizer() {
if (mVisualizer != null) {
if (mVisualizerView.getVisibility() != View.VISIBLE) {
mVisualizerView.setVisibility(View.VISIBLE);
mVisualizerHandler.sendEmptyMessage(ENABLE_VISUALIZER);
if (mShowFadeAnimation) {
mVisualizerView.startAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
}
}
}
}
private void loadPreferences() {
mLyricsWakelock = mPrefs.getBooleanPref(KEY_LYRICS_WAKELOCK, DEFAULT_LYRICS_WAKELOCK);
mAutoColor = mPrefs.getBooleanPref(KEY_AUTO_COLOR, true);
mBlurBackground = mPrefs.getBooleanPref(KEY_BLUR_BACKGROUND, false);
}
private void queueNextRefresh(long delay) {
if (!paused && !mFromTouch) {
Message msg = mHandler.obtainMessage(REFRESH);
mHandler.removeMessages(REFRESH);
mHandler.sendMessageDelayed(msg, delay);
}
}
private long refreshNow() {
if (mService == null) return 500;
try {
long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
long remaining = 1000 - pos % 1000;
if (pos >= 0 && mDuration > 0) {
mCurrentTime.setText(mUtils.makeTimeString(pos / 1000));
if (mService.isPlaying()) {
mCurrentTime.setVisibility(View.VISIBLE);
} else {
// blink the counter
// If the progress bar is still been dragged, then we do not
// want to blink the
// currentTime. It would cause flickering due to change in
// the visibility.
if (mFromTouch) {
mCurrentTime.setVisibility(View.VISIBLE);
} else {
int vis = mCurrentTime.getVisibility();
mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE
: View.INVISIBLE);
}
remaining = 500;
}
// Normalize our progress along the progress bar's scale
setSupportProgress((int) ((Window.PROGRESS_END - Window.PROGRESS_START) * pos / mDuration));
} else {
mCurrentTime.setText("--:--");
setSupportProgress(Window.PROGRESS_END - Window.PROGRESS_START);
}
// return the number of milliseconds until the next full second, so
// the counter can be updated at just the right time
return remaining;
} catch (RemoteException e) {
e.printStackTrace();
}
return 500;
}
private void scanBackward(int repcnt, long delta) {
if (mService == null) return;
try {
if (repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos - delta;
if (newpos < 0) {
// move to previous track
mService.prev();
long duration = mService.duration();
mStartSeekPos += duration;
newpos += duration;
}
if (delta - mLastSeekEventTime > 250 || repcnt < 0) {
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void scanForward(int repcnt, long delta) {
if (mService == null) return;
try {
if (repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos + delta;
long duration = mService.duration();
if (newpos >= duration) {
// move to next track
mService.next();
mStartSeekPos -= duration; // is OK to go negative
newpos -= duration;
}
if (delta - mLastSeekEventTime > 250 || repcnt < 0) {
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void setPauseButtonImage() {
try {
if (mService != null && mService.isPlaying()) {
mPauseButton.setImageResource(R.drawable.btn_playback_ic_pause);
} else {
mPauseButton.setImageResource(R.drawable.btn_playback_ic_play);
}
} catch (RemoteException ex) {
}
}
private void setUIColor(int color) {
mVisualizerViewFftSpectrum.setColor(color);
mVisualizerViewWaveForm.setColor(color);
mTouchPaintView.setColor(color);
}
private void setVisualizerView() {
try {
if (mService != null && mService.isPlaying() && mDisplayVisualizer) {
enableVisualizer();
} else {
disableVisualizer(false);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void toggleFavorite() {
if (mService == null) return;
try {
mService.toggleFavorite();
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void updateTrackInfo(boolean animation) {
if (mService == null) {
finish();
return;
}
try {
mTrackName.setText(mService.getTrackName());
if (mService.getArtistName() != null
&& !MediaStore.UNKNOWN_STRING.equals(mService.getArtistName())) {
mTrackDetail.setText(mService.getArtistName());
} else if (mService.getAlbumName() != null
&& !MediaStore.UNKNOWN_STRING.equals(mService.getAlbumName())) {
mTrackDetail.setText(mService.getAlbumName());
} else {
mTrackDetail.setText(R.string.unknown_artist);
}
if (mColorAnalyser != null) {
mColorAnalyser.cancel(true);
}
mColorAnalyser = new AsyncColorAnalyser();
mColorAnalyser.execute();
mDuration = mService.duration();
mTotalTime.setText(mUtils.makeTimeString(mDuration / 1000));
} catch (RemoteException e) {
e.printStackTrace();
finish();
}
}
private boolean useDpadMusicControl() {
if (mDeviceHasDpad
&& (mPrevButton.isFocused() || mNextButton.isFocused() || mPauseButton.isFocused()))
return true;
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode != RESULT_OK) return;
switch (requestCode) {
case DELETE_ITEMS:
if (resultCode == RESULT_DELETE_MUSIC) {
finish();
}
break;
}
}
public static class AlbumArtFragment extends SherlockFragment implements
ViewSwitcher.ViewFactory, OnClickListener, ServiceConnection {
private ImageSwitcher mAlbum;
private IMusicPlaybackService mService;
private ServiceToken mToken;
private AsyncAlbumArtLoader mAlbumArtLoader;
private ImageButton mRepeatButton, mShuffleButton;
private boolean mIntentDeRegistered = false;
private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_META_CHANGED.equals(action)) {
updateTrackInfo();
}
}
};
private BroadcastReceiver mScreenTimeoutListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
if (mIntentDeRegistered) {
IntentFilter f = new IntentFilter();
f.addAction(BROADCAST_META_CHANGED);
getActivity().registerReceiver(mStatusListener, new IntentFilter(f));
mIntentDeRegistered = false;
}
updateTrackInfo();
} else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
if (!mIntentDeRegistered) {
getActivity().unregisterReceiver(mStatusListener);
mIntentDeRegistered = true;
}
}
}
};
private View.OnLongClickListener mSearchAlbumArtListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
searchAlbumArt();
return true;
}
};
private MediaUtils mUtils;
@Override
public View makeView() {
ImageView view = new ImageView(getActivity());
view.setScaleType(ImageView.ScaleType.FIT_CENTER);
view.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
View view = getView();
mAlbum = (ImageSwitcher) view.findViewById(R.id.album_art);
mAlbum.setOnLongClickListener(mSearchAlbumArtListener);
mAlbum.setFactory(this);
mShuffleButton = (ImageButton) view.findViewById(R.id.toggle_shuffle);
mShuffleButton.setOnClickListener(this);
mRepeatButton = (ImageButton) view.findViewById(R.id.toggle_repeat);
mRepeatButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == mShuffleButton) {
toggleShuffle();
} else if (view == mRepeatButton) {
toggleRepeat();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.playback_albumart, container, false);
return view;
}
@Override
public void onServiceConnected(ComponentName name, IBinder obj) {
mService = IMusicPlaybackService.Stub.asInterface(obj);
updateTrackInfo();
setRepeatButtonImage();
setShuffleButtonImage();
}
@Override
public void onServiceDisconnected(ComponentName name) {
getActivity().finish();
}
@Override
public void onStart() {
super.onStart();
mToken = mUtils.bindToService(this);
IntentFilter f = new IntentFilter();
f.addAction(BROADCAST_META_CHANGED);
getActivity().registerReceiver(mStatusListener, new IntentFilter(f));
IntentFilter s = new IntentFilter();
s.addAction(Intent.ACTION_SCREEN_ON);
s.addAction(Intent.ACTION_SCREEN_OFF);
getActivity().registerReceiver(mScreenTimeoutListener, new IntentFilter(s));
}
@Override
public void onStop() {
if (mAlbumArtLoader != null) {
mAlbumArtLoader.cancel(true);
}
if (!mIntentDeRegistered) {
getActivity().unregisterReceiver(mStatusListener);
}
getActivity().unregisterReceiver(mScreenTimeoutListener);
mUtils.unbindFromService(mToken);
super.onStop();
}
private void searchAlbumArt() {
String artistName = "";
String albumName = "";
String mediaPath = "";
String albumArtPath = "";
try {
artistName = mService.getArtistName();
albumName = mService.getAlbumName();
mediaPath = mService.getMediaPath();
albumArtPath = mediaPath.substring(0, mediaPath.lastIndexOf("/")) + "/AlbumArt.jpg";
} catch (Exception e) {
e.printStackTrace();
}
try {
Intent intent = new Intent(INTENT_SEARCH_ALBUMART);
intent.putExtra(INTENT_KEY_ARTIST, artistName);
intent.putExtra(INTENT_KEY_ALBUM, albumName);
intent.putExtra(INTENT_KEY_PATH, albumArtPath);
startActivityForResult(intent, RESULT_ALBUMART_DOWNLOADED);
} catch (ActivityNotFoundException e) {
// e.printStackTrace();
}
}
private void setRepeatButtonImage() {
if (mService == null) return;
try {
switch (mService.getRepeatMode()) {
case REPEAT_ALL:
mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn);
break;
case REPEAT_CURRENT:
mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn);
break;
default:
mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn);
break;
}
} catch (RemoteException ex) {
ex.printStackTrace();
}
}
private void setShuffleButtonImage() {
if (mService == null) return;
try {
switch (mService.getShuffleMode()) {
case SHUFFLE_NONE:
mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn);
break;
default:
mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn);
break;
}
} catch (RemoteException ex) {
ex.printStackTrace();
}
}
private void toggleRepeat() {
if (mService == null) return;
try {
int mode = mService.getRepeatMode();
if (mode == MusicPlaybackService.REPEAT_NONE) {
mService.setRepeatMode(MusicPlaybackService.REPEAT_ALL);
Toast.makeText(getActivity(), R.string.repeat_all_notif, Toast.LENGTH_SHORT);
} else if (mode == MusicPlaybackService.REPEAT_ALL) {
mService.setRepeatMode(MusicPlaybackService.REPEAT_CURRENT);
if (mService.getShuffleMode() != MusicPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MusicPlaybackService.SHUFFLE_NONE);
setShuffleButtonImage();
}
Toast.makeText(getActivity(), R.string.repeat_current_notif, Toast.LENGTH_SHORT);
} else {
mService.setRepeatMode(MusicPlaybackService.REPEAT_NONE);
Toast.makeText(getActivity(), R.string.repeat_off_notif, Toast.LENGTH_SHORT);
}
setRepeatButtonImage();
} catch (RemoteException ex) {
}
}
private void toggleShuffle() {
if (mService == null) return;
try {
int shuffle = mService.getShuffleMode();
if (shuffle == SHUFFLE_NONE) {
mService.setShuffleMode(SHUFFLE_NORMAL);
if (mService.getRepeatMode() == REPEAT_CURRENT) {
mService.setRepeatMode(REPEAT_ALL);
setRepeatButtonImage();
}
Toast.makeText(getActivity(), R.string.shuffle_on_notif, Toast.LENGTH_SHORT);
} else if (shuffle == SHUFFLE_NORMAL) {
mService.setShuffleMode(SHUFFLE_NONE);
Toast.makeText(getActivity(), R.string.shuffle_off_notif, Toast.LENGTH_SHORT);
} else {
Log.e("MediaPlaybackActivity", "Invalid shuffle mode: " + shuffle);
}
setShuffleButtonImage();
} catch (RemoteException ex) {
}
}
private void updateTrackInfo() {
if (mAlbumArtLoader != null) {
mAlbumArtLoader.cancel(true);
}
mAlbumArtLoader = new AsyncAlbumArtLoader();
mAlbumArtLoader.execute();
}
private class AsyncAlbumArtLoader extends AsyncTask<Void, Void, Drawable> {
@Override
public Drawable doInBackground(Void... params) {
if (mService != null) {
try {
Bitmap bitmap = mUtils.getArtwork(mService.getAudioId(),
mService.getAlbumId());
if (bitmap == null) return null;
int value = 0;
if (bitmap.getHeight() <= bitmap.getWidth()) {
value = bitmap.getHeight();
} else {
value = bitmap.getWidth();
}
Bitmap result = Bitmap.createBitmap(bitmap,
(bitmap.getWidth() - value) / 2, (bitmap.getHeight() - value) / 2,
value, value);
return new BitmapDrawable(getResources(), result);
} catch (RemoteException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public void onPostExecute(Drawable result) {
if (mAlbum != null) {
if (result != null) {
mAlbum.setImageDrawable(result);
} else {
mAlbum.setImageResource(R.drawable.ic_mp_albumart_unknown);
}
}
}
}
}
public static class LyricsAndQueueFragment extends SherlockFragment implements
OnValueChangeListener {
private SliderView mVolumeSliderLeft, mVolumeSliderRight;
private AudioManager mAudioManager;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
View view = getView();
mVolumeSliderLeft = (SliderView) view.findViewById(R.id.volume_slider_left);
mVolumeSliderLeft.setOnValueChangeListener(this);
mVolumeSliderLeft.setMax(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
mVolumeSliderRight = (SliderView) view.findViewById(R.id.volume_slider_right);
mVolumeSliderRight.setOnValueChangeListener(this);
mVolumeSliderRight.setMax(mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
if (view.findViewById(R.id.albumart_frame) != null) {
getFragmentManager().beginTransaction()
.replace(R.id.albumart_frame, new AlbumArtFragment()).commit();
}
getFragmentManager().beginTransaction()
.replace(R.id.lyrics_frame, new LyricsFragment()).commit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.playback_info, container, false);
return view;
}
@Override
public void onValueChanged(int value) {
adjustVolume(value);
}
private void adjustVolume(int value) {
int max_volume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int current_volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (value + current_volume <= max_volume && value + current_volume >= 0) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value + current_volume,
AudioManager.FLAG_SHOW_UI);
} else if (value + current_volume > max_volume) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, max_volume,
AudioManager.FLAG_SHOW_UI);
} else if (value + current_volume < 0) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0,
AudioManager.FLAG_SHOW_UI);
}
}
private void setUIColor(int color) {
mVolumeSliderRight.setColor(color);
mVolumeSliderLeft.setColor(color);
}
}
private class AsyncColorAnalyser extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... params) {
if (mService != null) {
try {
if (mAutoColor) {
mUIColor = ColorAnalyser.analyse(mUtils.getArtwork(mService.getAudioId(),
mService.getAlbumId()));
} else {
mUIColor = mPrefs.getIntPref(KEY_CUSTOMIZED_COLOR, Color.WHITE);
}
return mUIColor;
} catch (RemoteException e) {
e.printStackTrace();
}
}
return Color.WHITE;
}
@Override
protected void onPostExecute(Integer result) {
setUIColor(mUIColor);
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/MusicPlaybackActivity.java
|
Java
|
gpl3
| 40,660
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.fragment.TrackFragment;
import org.yammp.util.MediaUtils;
import org.yammp.util.ServiceToken;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore.Audio;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
public class TrackBrowserActivity extends SherlockFragmentActivity implements Constants,
ServiceConnection {
private ServiceToken mToken;
private Intent intent;
private Bundle bundle;
private MediaUtils mUtils;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
intent = getIntent();
bundle = icicle != null ? icicle : intent.getExtras();
if (bundle == null) {
bundle = new Bundle();
}
if (bundle.getString(INTENT_KEY_ACTION) == null) {
bundle.putString(INTENT_KEY_ACTION, intent.getAction());
}
if (bundle.getString(INTENT_KEY_TYPE) == null) {
bundle.putString(INTENT_KEY_TYPE, intent.getType());
}
TrackFragment fragment = new TrackFragment(bundle);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, fragment)
.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
outcicle.putAll(bundle);
super.onSaveInstanceState(outcicle);
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
finish();
}
@Override
public void onStart() {
super.onStart();
mToken = mUtils.bindToService(this);
setTitle();
}
@Override
public void onStop() {
mUtils.unbindFromService(mToken);
super.onStop();
}
private void setTitle() {
String mimeType = bundle.getString(INTENT_KEY_TYPE);
String name;
long id;
if (Audio.Playlists.CONTENT_TYPE.equals(mimeType)) {
id = bundle.getLong(Audio.Playlists._ID);
switch ((int) id) {
case (int) PLAYLIST_QUEUE:
setTitle(R.string.now_playing);
return;
case (int) PLAYLIST_FAVORITES:
setTitle(R.string.favorites);
return;
case (int) PLAYLIST_RECENTLY_ADDED:
setTitle(R.string.recently_added);
return;
case (int) PLAYLIST_PODCASTS:
setTitle(R.string.podcasts);
return;
default:
if (id < 0) {
setTitle(R.string.music_library);
return;
}
}
name = mUtils.getPlaylistName(id);
} else if (Audio.Artists.CONTENT_TYPE.equals(mimeType)) {
id = bundle.getLong(Audio.Artists._ID);
name = mUtils.getArtistName(id, true);
} else if (Audio.Albums.CONTENT_TYPE.equals(mimeType)) {
id = bundle.getLong(Audio.Albums._ID);
name = mUtils.getAlbumName(id, true);
} else if (Audio.Genres.CONTENT_TYPE.equals(mimeType)) {
id = bundle.getLong(Audio.Genres._ID);
name = mUtils.parseGenreName(mUtils.getGenreName(id, true));
} else {
setTitle(R.string.music_library);
return;
}
setTitle(name);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/TrackBrowserActivity.java
|
Java
|
gpl3
| 4,274
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.app;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.fragment.QueryFragment;
import org.yammp.util.MediaUtils;
import org.yammp.util.ServiceToken;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
public class QueryBrowserActivity extends SherlockFragmentActivity implements Constants,
ServiceConnection, TextWatcher {
private ServiceToken mToken;
private Intent intent;
private Bundle bundle;
private QueryFragment fragment;
private MediaUtils mUtils;
@Override
public void afterTextChanged(Editable s) {
// don't care about this one
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// don't care about this one
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
configureActivity();
intent = getIntent();
bundle = icicle != null ? icicle : intent.getExtras();
if (bundle == null) {
bundle = new Bundle();
}
if (bundle.getString(INTENT_KEY_ACTION) == null) {
bundle.putString(INTENT_KEY_ACTION, intent.getAction());
}
if (bundle.getString(INTENT_KEY_DATA) == null) {
bundle.putString(INTENT_KEY_DATA, intent.getDataString());
}
if (bundle.getString(SearchManager.QUERY) == null) {
bundle.putString(SearchManager.QUERY, intent.getStringExtra(SearchManager.QUERY));
}
if (bundle.getString(MediaStore.EXTRA_MEDIA_FOCUS) == null) {
bundle.putString(MediaStore.EXTRA_MEDIA_FOCUS,
intent.getStringExtra(MediaStore.EXTRA_MEDIA_FOCUS));
}
if (bundle.getString(MediaStore.EXTRA_MEDIA_ARTIST) == null) {
bundle.putString(MediaStore.EXTRA_MEDIA_ARTIST,
intent.getStringExtra(MediaStore.EXTRA_MEDIA_ARTIST));
}
if (bundle.getString(MediaStore.EXTRA_MEDIA_ALBUM) == null) {
bundle.putString(MediaStore.EXTRA_MEDIA_ALBUM,
intent.getStringExtra(MediaStore.EXTRA_MEDIA_ALBUM));
}
if (bundle.getString(MediaStore.EXTRA_MEDIA_TITLE) == null) {
bundle.putString(MediaStore.EXTRA_MEDIA_TITLE,
intent.getStringExtra(MediaStore.EXTRA_MEDIA_TITLE));
}
fragment = new QueryFragment(bundle);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, fragment)
.commit();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case GOTO_HOME:
intent = new Intent(INTENT_MUSIC_BROWSER);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
outcicle.putAll(bundle);
super.onSaveInstanceState(outcicle);
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onStart() {
super.onStart();
mToken = mUtils.bindToService(this);
}
@Override
public void onStop() {
mUtils.unbindFromService(mToken);
super.onStop();
};
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Bundle args = fragment.getArguments();
if (args == null) {
args = new Bundle();
}
args.putString(INTENT_KEY_FILTER, s.toString());
fragment.getLoaderManager().restartLoader(0, args, fragment);
}
private void configureActivity() {
View mCustomView;
setContentView(new FrameLayout(this));
getSupportActionBar().setCustomView(R.layout.actionbar_query_browser);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
mCustomView = getSupportActionBar().getCustomView();
if (mCustomView != null) {
((EditText) mCustomView.findViewById(R.id.query_editor)).addTextChangedListener(this);
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/app/QueryBrowserActivity.java
|
Java
|
gpl3
| 5,271
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.view;
import org.yammp.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
public class VerticalTextSpinner extends View {
private static final int SELECTOR_ARROW_HEIGHT = 15;
private static int TEXT_SPACING;
private static int TEXT_MARGIN_RIGHT;
private static int TEXT_SIZE;
private static int TEXT1_Y;
private static int TEXT2_Y;
private static int TEXT3_Y;
private static int TEXT4_Y;
private static int TEXT5_Y;
private static int SCROLL_DISTANCE;
private static final int SCROLL_MODE_NONE = 0;
private static final int SCROLL_MODE_UP = 1;
private static final int SCROLL_MODE_DOWN = 2;
private static final long DEFAULT_SCROLL_INTERVAL_MS = 400;
private static final int MIN_ANIMATIONS = 4;
private final Drawable mBackgroundFocused;
private final int mSelectorDefaultY;
private final int mSelectorMinY;
private final int mSelectorMaxY;
private final int mSelectorHeight;
private final TextPaint mTextPaintDark;
private final TextPaint mTextPaintLight;
private int mSelectorY;
private Drawable mSelector;
private int mDownY;
private boolean isDraggingSelector;
private int mScrollMode;
private long mScrollInterval;
private boolean mIsAnimationRunning;
private boolean mStopAnimation;
private boolean mWrapAround = true;
private int mTotalAnimatedDistance;
private int mNumberOfAnimations;
private long mDelayBetweenAnimations;
private int mDistanceOfEachAnimation;
private String[] mTextList;
private int mCurrentSelectedPos;
private OnChangedListener mListener;
private String mText1;
private String mText2;
private String mText3;
private String mText4;
private String mText5;
public VerticalTextSpinner(Context context) {
this(context, null);
}
public VerticalTextSpinner(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VerticalTextSpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
float scale = getResources().getDisplayMetrics().density;
TEXT_SPACING = (int) (18 * scale);
TEXT_MARGIN_RIGHT = (int) (25 * scale);
TEXT_SIZE = (int) (22 * scale);
SCROLL_DISTANCE = TEXT_SIZE + TEXT_SPACING;
TEXT1_Y = TEXT_SIZE * (-2 + 2) + TEXT_SPACING * (-2 + 1);
TEXT2_Y = TEXT_SIZE * (-1 + 2) + TEXT_SPACING * (-1 + 1);
TEXT3_Y = TEXT_SIZE * (0 + 2) + TEXT_SPACING * (0 + 1);
TEXT4_Y = TEXT_SIZE * (1 + 2) + TEXT_SPACING * (1 + 1);
TEXT5_Y = TEXT_SIZE * (2 + 2) + TEXT_SPACING * (2 + 1);
mBackgroundFocused = context.getResources().getDrawable(R.drawable.pickerbox_background);
mSelector = context.getResources().getDrawable(R.drawable.pickerbox);
mSelectorHeight = mSelector.getIntrinsicHeight();
mSelectorDefaultY = (mBackgroundFocused.getIntrinsicHeight() - mSelectorHeight) / 2;
mSelectorMinY = 0;
mSelectorMaxY = mBackgroundFocused.getIntrinsicHeight() - mSelectorHeight;
mSelectorY = mSelectorDefaultY;
mTextPaintDark = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaintDark.setTextSize(TEXT_SIZE);
mTextPaintDark
.setColor(context.getResources().getColor(android.R.color.primary_text_light));
mTextPaintLight = new TextPaint(Paint.ANTI_ALIAS_FLAG);
mTextPaintLight.setTextSize(TEXT_SIZE);
mTextPaintLight.setColor(context.getResources().getColor(
android.R.color.secondary_text_dark));
mScrollMode = SCROLL_MODE_NONE;
mScrollInterval = DEFAULT_SCROLL_INTERVAL_MS;
calculateAnimationValues();
}
public int getCurrentSelectedPos() {
return mCurrentSelectedPos;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
/*
* This is a bit confusing, when we get the key event DPAD_DOWN we
* actually roll the spinner up. When the key event is DPAD_UP we roll
* the spinner down.
*/
if (keyCode == KeyEvent.KEYCODE_DPAD_UP && canScrollDown()) {
mScrollMode = SCROLL_MODE_DOWN;
scroll();
mStopAnimation = true;
return true;
} else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && canScrollUp()) {
mScrollMode = SCROLL_MODE_UP;
scroll();
mStopAnimation = true;
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
final int y = (int) event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
requestFocus();
mDownY = y;
isDraggingSelector = y >= mSelectorY
&& y <= mSelectorY + mSelector.getIntrinsicHeight();
break;
case MotionEvent.ACTION_MOVE:
if (isDraggingSelector) {
int top = mSelectorDefaultY + y - mDownY;
if (top <= mSelectorMinY && canScrollDown()) {
mSelectorY = mSelectorMinY;
mStopAnimation = false;
if (mScrollMode != SCROLL_MODE_DOWN) {
mScrollMode = SCROLL_MODE_DOWN;
scroll();
}
} else if (top >= mSelectorMaxY && canScrollUp()) {
mSelectorY = mSelectorMaxY;
mStopAnimation = false;
if (mScrollMode != SCROLL_MODE_UP) {
mScrollMode = SCROLL_MODE_UP;
scroll();
}
} else {
mSelectorY = top;
mStopAnimation = true;
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
default:
mSelectorY = mSelectorDefaultY;
mStopAnimation = true;
invalidate();
break;
}
return true;
}
public void setItems(String[] textList) {
mTextList = textList;
calculateTextPositions();
}
public void setOnChangeListener(OnChangedListener listener) {
mListener = listener;
}
public void setScrollInterval(long interval) {
mScrollInterval = interval;
calculateAnimationValues();
}
public void setSelectedPos(int selectedPos) {
mCurrentSelectedPos = selectedPos;
calculateTextPositions();
postInvalidate();
}
public void setWrapAround(boolean wrap) {
mWrapAround = wrap;
}
private void calculateAnimationValues() {
mNumberOfAnimations = (int) mScrollInterval / SCROLL_DISTANCE;
if (mNumberOfAnimations < MIN_ANIMATIONS) {
mNumberOfAnimations = MIN_ANIMATIONS;
mDistanceOfEachAnimation = SCROLL_DISTANCE / mNumberOfAnimations;
mDelayBetweenAnimations = 0;
} else {
mDistanceOfEachAnimation = SCROLL_DISTANCE / mNumberOfAnimations;
mDelayBetweenAnimations = mScrollInterval / mNumberOfAnimations;
}
}
/**
* Called every time the text items or current position changes. We
* calculate store we don't have to calculate onDraw.
*/
private void calculateTextPositions() {
mText1 = getTextToDraw(-2);
mText2 = getTextToDraw(-1);
mText3 = getTextToDraw(0);
mText4 = getTextToDraw(1);
mText5 = getTextToDraw(2);
}
private boolean canScrollDown() {
return mCurrentSelectedPos > 0 || mWrapAround;
}
private boolean canScrollUp() {
return mCurrentSelectedPos < mTextList.length - 1 || mWrapAround;
}
private void drawText(Canvas canvas, String text, int y, TextPaint paint) {
int width = (int) paint.measureText(text);
int x = getMeasuredWidth() - width - TEXT_MARGIN_RIGHT;
canvas.drawText(text, x, y, paint);
}
private int getNewIndex(int offset) {
int index = mCurrentSelectedPos + offset;
if (index < 0) {
if (mWrapAround) {
index += mTextList.length;
} else
return -1;
} else if (index >= mTextList.length) {
if (mWrapAround) {
index -= mTextList.length;
} else
return -1;
}
return index;
}
private String getTextToDraw(int offset) {
int index = getNewIndex(offset);
if (index < 0) return "";
return mTextList[index];
}
private void scroll() {
if (mIsAnimationRunning) return;
mTotalAnimatedDistance = 0;
mIsAnimationRunning = true;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
/* The bounds of the selector */
final int selectorLeft = 0;
final int selectorTop = mSelectorY;
final int selectorRight = getWidth();
final int selectorBottom = mSelectorY + mSelectorHeight;
/* Draw the selector */
mSelector.setBounds(selectorLeft, selectorTop, selectorRight, selectorBottom);
mSelector.draw(canvas);
if (mTextList == null) /*
* We're not setup with values so don't draw
* anything else
*/
return;
final TextPaint textPaintDark = mTextPaintDark;
if (hasFocus()) {
/* The bounds of the top area where the text should be light */
final int topLeft = 0;
final int topTop = 0;
final int topRight = selectorRight;
final int topBottom = selectorTop + SELECTOR_ARROW_HEIGHT;
/* Assign a bunch of local finals for performance */
final String text1 = mText1;
final String text2 = mText2;
final String text3 = mText3;
final String text4 = mText4;
final String text5 = mText5;
final TextPaint textPaintLight = mTextPaintLight;
/*
* Draw the 1st, 2nd and 3rd item in light only, clip it so it only
* draws in the area above the selector
*/
canvas.save();
canvas.clipRect(topLeft, topTop, topRight, topBottom);
drawText(canvas, text1, TEXT1_Y + mTotalAnimatedDistance, textPaintLight);
drawText(canvas, text2, TEXT2_Y + mTotalAnimatedDistance, textPaintLight);
drawText(canvas, text3, TEXT3_Y + mTotalAnimatedDistance, textPaintLight);
canvas.restore();
/*
* Draw the 2nd, 3rd and 4th clipped to the selector bounds in dark
* paint
*/
canvas.save();
canvas.clipRect(selectorLeft, selectorTop + SELECTOR_ARROW_HEIGHT, selectorRight,
selectorBottom - SELECTOR_ARROW_HEIGHT);
drawText(canvas, text2, TEXT2_Y + mTotalAnimatedDistance, textPaintDark);
drawText(canvas, text3, TEXT3_Y + mTotalAnimatedDistance, textPaintDark);
drawText(canvas, text4, TEXT4_Y + mTotalAnimatedDistance, textPaintDark);
canvas.restore();
/* The bounds of the bottom area where the text should be light */
final int bottomLeft = 0;
final int bottomTop = selectorBottom - SELECTOR_ARROW_HEIGHT;
final int bottomRight = selectorRight;
final int bottomBottom = getMeasuredHeight();
/*
* Draw the 3rd, 4th and 5th in white text, clip it so it only draws
* in the area below the selector.
*/
canvas.save();
canvas.clipRect(bottomLeft, bottomTop, bottomRight, bottomBottom);
drawText(canvas, text3, TEXT3_Y + mTotalAnimatedDistance, textPaintLight);
drawText(canvas, text4, TEXT4_Y + mTotalAnimatedDistance, textPaintLight);
drawText(canvas, text5, TEXT5_Y + mTotalAnimatedDistance, textPaintLight);
canvas.restore();
} else {
drawText(canvas, mText3, TEXT3_Y, textPaintDark);
}
if (mIsAnimationRunning) {
if (Math.abs(mTotalAnimatedDistance) + mDistanceOfEachAnimation > SCROLL_DISTANCE) {
mTotalAnimatedDistance = 0;
if (mScrollMode == SCROLL_MODE_UP) {
int oldPos = mCurrentSelectedPos;
int newPos = getNewIndex(1);
if (newPos >= 0) {
mCurrentSelectedPos = newPos;
if (mListener != null) {
mListener.onChanged(this, oldPos, mCurrentSelectedPos, mTextList);
}
}
if (newPos < 0 || newPos >= mTextList.length - 1 && !mWrapAround) {
mStopAnimation = true;
}
calculateTextPositions();
} else if (mScrollMode == SCROLL_MODE_DOWN) {
int oldPos = mCurrentSelectedPos;
int newPos = getNewIndex(-1);
if (newPos >= 0) {
mCurrentSelectedPos = newPos;
if (mListener != null) {
mListener.onChanged(this, oldPos, mCurrentSelectedPos, mTextList);
}
}
if (newPos < 0 || newPos == 0 && !mWrapAround) {
mStopAnimation = true;
}
calculateTextPositions();
}
if (mStopAnimation) {
final int previousScrollMode = mScrollMode;
/*
* No longer scrolling, we wait till the current animation
* completes then we stop.
*/
mIsAnimationRunning = false;
mStopAnimation = false;
mScrollMode = SCROLL_MODE_NONE;
/*
* If the current selected item is an empty string scroll
* past it.
*/
if ("".equals(mTextList[mCurrentSelectedPos])) {
mScrollMode = previousScrollMode;
scroll();
mStopAnimation = true;
}
}
} else {
if (mScrollMode == SCROLL_MODE_UP) {
mTotalAnimatedDistance -= mDistanceOfEachAnimation;
} else if (mScrollMode == SCROLL_MODE_DOWN) {
mTotalAnimatedDistance += mDistanceOfEachAnimation;
}
}
if (mDelayBetweenAnimations > 0) {
postInvalidateDelayed(mDelayBetweenAnimations);
} else {
invalidate();
}
}
}
public interface OnChangedListener {
void onChanged(VerticalTextSpinner spinner, int oldPos, int newPos, String[] items);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/view/VerticalTextSpinner.java
|
Java
|
gpl3
| 13,342
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class VisualizerViewWaveForm extends View {
// Namespaces to read attributes
private static final String VISUALIZER_NS = "http://schemas.android.com/apk/res/org.yammp";
// Attribute names
private static final String ATTR_ANTIALIAS = "antialias";
private static final String ATTR_COLOR = "color";
// Default values for defaults
private static final boolean DEFAULT_ANTIALIAS = true;
private static final int DEFAULT_COLOR = Color.WHITE;
// Real defaults
private final boolean mAntiAlias;
private final int mColor;
private byte[] mData = null;
private float[] mPoints;
private Rect mRect = new Rect();
private Paint mForePaint = new Paint();
private boolean mScoop = false;
public VisualizerViewWaveForm(Context context) {
super(context);
mAntiAlias = DEFAULT_ANTIALIAS;
mColor = DEFAULT_COLOR;
mForePaint.setStrokeWidth(1.0f);
setAntiAlias(mAntiAlias);
setColor(mColor);
}
public VisualizerViewWaveForm(Context context, AttributeSet attrs) {
super(context, attrs);
// Read parameters from attributes
mAntiAlias = attrs.getAttributeBooleanValue(VISUALIZER_NS, ATTR_ANTIALIAS,
DEFAULT_ANTIALIAS);
mColor = attrs.getAttributeIntValue(VISUALIZER_NS, ATTR_COLOR, DEFAULT_COLOR);
mForePaint.setStrokeWidth(1.0f);
setAntiAlias(mAntiAlias);
setColor(mColor);
}
public void setAntiAlias(boolean antialias) {
mForePaint.setAntiAlias(antialias);
}
public void setColor(int color) {
mForePaint.setColor(Color.argb(0xFF, Color.red(color), Color.green(color),
Color.blue(color)));
}
public void updateVisualizer(byte[] data, boolean scoop) {
mData = data;
mScoop = scoop;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mData == null) return;
mRect.setEmpty();
if (mPoints == null || mPoints.length < mData.length * 4) {
mPoints = new float[mData.length * 4];
}
mRect.set(0, 0, getWidth(), getHeight());
for (int i = 0; i < mData.length - 1; i++) {
mPoints[i * 4] = mRect.width() * i / (mData.length - 1);
mPoints[i * 4 + 1] = (mScoop ? mData[i] + 128 : (byte) (mData[i] + 128))
* (mRect.height() / 2) / 128 + (mScoop ? 0 : mRect.height() / 2);
mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mData.length - 1);
mPoints[i * 4 + 3] = (mScoop ? mData[i + 1] + 128 : (byte) (mData[i + 1] + 128))
* (mRect.height() / 2) / 128 + (mScoop ? 0 : mRect.height() / 2);
}
canvas.drawLines(mPoints, mForePaint);
}
@Override
protected void onSizeChanged(int width, int height, int old_width, int old_height) {
mForePaint.setStrokeWidth(1.0f);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/view/VisualizerViewWaveForm.java
|
Java
|
gpl3
| 3,482
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
public class VisualizerViewFftSpectrum extends View {
// Namespaces to read attributes
private static final String VISUALIZER_NS = "http://schemas.android.com/apk/res/org.yammp";
// Attribute names
private static final String ATTR_ANTIALIAS = "antialias";
private static final String ATTR_COLOR = "color";
// Default values for defaults
private static final boolean DEFAULT_ANTIALIAS = true;
private static final int DEFAULT_COLOR = Color.WHITE;
// Real defaults
private final boolean mAntiAlias;
private final int mColor;
private int mFftSamples = 48;
private byte[] mData = null;
private float[] mPoints;
private Rect mRect = new Rect();
private Paint mForePaint = new Paint();
public VisualizerViewFftSpectrum(Context context) {
super(context);
mAntiAlias = DEFAULT_ANTIALIAS;
mColor = DEFAULT_COLOR;
mForePaint.setStrokeWidth((float) getWidth() / (float) mFftSamples / 2.0f);
setAntiAlias(mAntiAlias);
setColor(mColor);
}
public VisualizerViewFftSpectrum(Context context, AttributeSet attrs) {
super(context, attrs);
mAntiAlias = attrs.getAttributeBooleanValue(VISUALIZER_NS, ATTR_ANTIALIAS,
DEFAULT_ANTIALIAS);
mColor = attrs.getAttributeIntValue(VISUALIZER_NS, ATTR_COLOR, DEFAULT_COLOR);
mForePaint.setStrokeWidth((float) getWidth() / (float) mFftSamples / 2.0f);
setAntiAlias(mAntiAlias);
setColor(mColor);
}
public void setAntiAlias(boolean antialias) {
mForePaint.setAntiAlias(antialias);
}
public void setColor(int color) {
mForePaint.setColor(Color.argb(0xA0, Color.red(color), Color.green(color),
Color.blue(color)));
}
public void setFftSamples(int samples) {
mFftSamples = samples;
mForePaint.setStrokeWidth((float) getWidth() / (float) samples / 2.0f);
mPoints = null;
}
public void updateVisualizer(byte[] data) {
byte[] model = new byte[data.length / 2 + 1];
int j = 0;
for (int i = 0; i <= mFftSamples * 2; i += 2) {
model[j] = (byte) Math.hypot(data[i], data[i + 1]);
j++;
}
mData = model;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mData == null) return;
if (mPoints == null || mPoints.length < mData.length * 4) {
mPoints = new float[mData.length * 4];
}
mRect.set(0, 0, getWidth(), getHeight() * 2);
for (int i = 0; i <= mFftSamples; i++) {
if (mData[i] < 0) {
mData[i] = 127;
}
mPoints[i * 4] = mRect.width() * i / mFftSamples + getWidth() / mFftSamples / 2.0f;
mPoints[i * 4 + 1] = mRect.height() / 2;
mPoints[i * 4 + 2] = mRect.width() * i / mFftSamples + getWidth() / mFftSamples / 2.0f;
mPoints[i * 4 + 3] = mRect.height() / 2 - 2 - mData[i] * 2;
}
canvas.drawLines(mPoints, mForePaint);
}
@Override
protected void onSizeChanged(int width, int height, int old_width, int old_height) {
mForePaint.setStrokeWidth((float) width / (float) mFftSamples / 2.0f);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/view/VisualizerViewFftSpectrum.java
|
Java
|
gpl3
| 3,763
|
package org.yammp.view;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class SliderView extends View implements OnGestureListener, OnTouchListener {
private int mHeight = 0;
private int mMaxValue = 16;
private float mDelta = 0;
private int mColor = Color.WHITE;
private GestureDetector mGestureDetector;
private OnValueChangeListener mListener;
public SliderView(Context context) {
super(context);
init(context);
}
public SliderView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SliderView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
@Override
public boolean onDown(MotionEvent e) {
mDelta = 0;
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
mDelta = 0;
}
@Override
public boolean onScroll(MotionEvent event1, MotionEvent event2, float distanceX, float distanceY) {
if (mDelta >= 1 || mDelta <= -1) {
if (mListener != null) {
mListener.onValueChanged((int) mDelta);
}
mDelta = 0;
} else {
mDelta += mMaxValue * distanceY / mHeight * 2;
}
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mHeight = getHeight();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
v.setBackgroundColor(Color.argb(0x33, Color.red(mColor), Color.green(mColor),
Color.blue(mColor)));
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
v.setBackgroundColor(Color.TRANSPARENT);
}
mGestureDetector.onTouchEvent(event);
return true;
}
public void setColor(int color) {
mColor = color;
}
public void setMax(int max) {
mMaxValue = max;
}
public void setOnValueChangeListener(OnValueChangeListener listener) {
mListener = listener;
}
private void init(Context context) {
setOnTouchListener(this);
mGestureDetector = new GestureDetector(context, this);
mHeight = getHeight();
}
public interface OnValueChangeListener {
void onValueChanged(int value);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/view/SliderView.java
|
Java
|
gpl3
| 2,651
|
package org.yammp.view;
import java.util.Arrays;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Shader;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class EqualizerView extends View implements OnTouchListener {
private short[] mBands = new short[] {};
private float firstMultiplier = 0.33f;
private float secondMultiplier = 1 - firstMultiplier;
private Point p1 = new Point(), p3 = new Point();
private int GRID_WH = 64;
private short MIN_LEVEL = 0, MAX_LEVEL = 0;
private HashMap<Short, Integer> mCenterFreqs = new HashMap<Short, Integer>();
private OnBandLevelChangeListener mListener;
public EqualizerView(Context context) {
super(context);
setOnTouchListener(this);
}
public EqualizerView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnTouchListener(this);
}
@Override
public void onDraw(Canvas canvas) {
Point[] points = new Point[mBands.length];
for (int i = 0; i < mBands.length; i++) {
if (MIN_LEVEL != 0 && MAX_LEVEL != 0) {
points[i] = new Point((int) ((float) i / (mBands.length - 1)
* (getWidth() - GRID_WH) + GRID_WH / 2),
(int) (getHeight() / 2 - (float) mBands[i]
/ (Math.abs(MIN_LEVEL) + Math.abs(MAX_LEVEL)) * getHeight()));
} else {
points[i] = new Point((int) ((float) i / (mBands.length - 1)
* (getWidth() - GRID_WH) + GRID_WH / 2), getHeight() / 2);
}
}
drawBackground(canvas, points);
drawPaths(canvas, points);
drawBars(canvas, points);
drawPoints(canvas, points);
drawLabels(canvas, points);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
short band = findClosest(event.getX(), event.getY());
if (mBands == null || mBands.length < 1) return false;
if (band != -1 && band < mBands.length) {
short level = (short) ((getHeight() / 2 - event.getY()) / getHeight() * (Math
.abs(MIN_LEVEL) + Math.abs(MAX_LEVEL)));
if (level < MIN_LEVEL) {
level = MIN_LEVEL;
}
if (level > MAX_LEVEL) {
level = MAX_LEVEL;
}
if (mListener != null) {
mListener.onBandLevelChange(band, level);
}
setBandLevel(band, level);
}
return true;
}
public void setBandLevel(short band, short level) {
if (mBands == null || band < 0 || band >= mBands.length) return;
mBands[band] = level;
invalidate();
}
public void setBandLevelRange(short[] range) {
if (range == null || range.length != 2) return;
MIN_LEVEL = range[0];
MAX_LEVEL = range[1];
invalidate();
}
public void setCenterFreq(short band, int freq) {
mCenterFreqs.put(band, freq);
invalidate();
}
public void setNumberOfBands(short bands) {
mBands = new short[bands];
Arrays.fill(mBands, (short) 0);
invalidate();
}
public void setOnBandLevelChangeListener(OnBandLevelChangeListener listener) {
mListener = listener;
}
private void calc(Point[] points, Point result, int index1, int index2, final float multiplier) {
float diffX = points[index2].x - points[index1].x; // p2.x - p1.x;
float diffY = points[index2].y - points[index1].y; // p2.y - p1.y;
result.x = (int) (points[index1].x + diffX * multiplier);
result.y = (int) (points[index1].y + diffY * multiplier);
}
private void drawBackground(Canvas canvas, Point[] points) {
Paint paint = new Paint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.DKGRAY);
}
};
int linesX = getWidth() / GRID_WH;
int linesY = getHeight() / GRID_WH;
for (int i = 0; i < linesX; i++) {
canvas.drawLine(getWidth() * i / linesX, 0, getWidth() * i / linesX, getHeight(), paint);
}
for (int i = 0; i < linesY; i++) {
canvas.drawLine(0, getHeight() * i / linesY, getWidth(), getHeight() * i / linesY,
paint);
}
paint = new Paint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.CYAN);
setStrokeWidth(1.5f);
}
};
canvas.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2, paint);
if (mBands != null && mBands.length > 0) {
paint = new TextPaint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.WHITE);
setTextSize(15.0f);
}
};
for (short i = 0; i < mBands.length; i++) {
String label = "";
Integer value = mCenterFreqs.get(i);
if (value != null) {
int freq = value;
if (freq / 1000 < 1000) {
label = String.format("%1.1f", (float) freq / 1000) + " Hz";
} else {
label = String.format("%1.1f", (float) freq / 1000 / 1000) + " KHz";
}
canvas.drawText(label, points[i].x, getHeight(), paint);
}
}
}
}
private void drawBars(Canvas canvas, Point[] points) {
if (points == null || points.length < 1) return;
Paint paint = new Paint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.GREEN);
if (mBands == null || mBands.length < 1) {
setStrokeWidth(12.0f);
} else {
setStrokeWidth(getWidth() / mBands.length / 8);
}
setShader(new LinearGradient(0, 0, 0, getHeight(), 0xffbfff00, 0xff003300,
Shader.TileMode.CLAMP));
}
};
for (Point point : points) {
canvas.drawLine(point.x, getHeight() / 2, point.x, point.y, paint);
}
}
private void drawLabels(Canvas canvas, Point[] points) {
if (points == null || points.length < 1) return;
Paint paint = new Paint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.WHITE);
}
};
for (Point point : points) {
String label = String.format("%1.1f", (float) (getHeight() / 2 - point.y) / getHeight()
* (Math.abs(MIN_LEVEL) + Math.abs(MAX_LEVEL)) / 100)
+ " dB";
canvas.drawText(label, point.x, getHeight() / 2, paint);
}
}
private void drawPaths(Canvas canvas, Point[] points) {
if (points == null || points.length < 1) return;
Paint paint = new Paint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.MAGENTA);
}
};
Path p = new Path();
float x = points[0].x;
float y = points[0].y;
p.moveTo(x, y);
int length = points.length;
for (int i = 0; i < length; i++) {
int nextIndex = i + 1 < length ? i + 1 : i;
int nextNextIndex = i + 2 < length ? i + 2 : nextIndex;
calc(points, p1, i, nextIndex, secondMultiplier);
calc(points, p3, nextIndex, nextNextIndex, firstMultiplier);
p.cubicTo(p1.x, p1.y, points[nextIndex].x, points[nextIndex].y, p3.x, p3.y);
}
canvas.drawPath(p, paint);
}
private void drawPoints(Canvas canvas, Point[] points) {
if (points == null || points.length < 1) return;
Paint paint = new Paint() {
{
setStyle(Paint.Style.STROKE);
setAntiAlias(true);
setColor(Color.WHITE);
if (mBands == null || mBands.length < 1) {
setStrokeWidth(12.0f);
} else {
setStrokeWidth(getWidth() / mBands.length / 8);
}
}
};
for (Point point : points) {
canvas.drawPoint(point.x, point.y, paint);
}
}
private short findClosest(float x, float y) {
if (mBands == null || mBands.length < 1) return -1;
int count = mBands.length;
for (int i = 0; i < count; i++) {
int n = (int) (getWidth() * ((float) i / count));
if (n < x && n + (getWidth() - GRID_WH) / mBands.length > x) return (short) i;
}
return -1;
}
public interface OnBandLevelChangeListener {
void onBandLevelChange(short band, short level);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/view/EqualizerView.java
|
Java
|
gpl3
| 7,685
|
package org.yammp.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class TouchPaintView extends View {
private static final int FADE_DELAY = 2;
private static final int FADE_ALPHA = 0x10;
private static final int MAX_FADE_STEPS = 256 / FADE_ALPHA * 2 + 8;
private Bitmap mBitmap;
private Canvas mCanvas;
private Rect mRect = new Rect();
private Paint mPaint;
private boolean mCurDown;
private int mCurX;
private int mCurY;
private float mCurSize;
private int mCurWidth;
private int mFadeSteps = 0;
private int mColor = Color.WHITE;
private EventListener mListener;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mHandler.removeCallbacksAndMessages(null);
if (mFadeSteps < MAX_FADE_STEPS) {
fade();
mHandler.sendEmptyMessageDelayed(0, FADE_DELAY);
} else {
mFadeSteps = 0;
}
}
};
public TouchPaintView(Context c) {
super(c);
init();
}
public TouchPaintView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mListener != null) {
mListener.onTouchEvent(event);
}
int action = event.getAction();
mCurDown = action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE;
drawPoint(event.getX(), event.getY(), event.getPressure(), event.getSize());
mFadeSteps = 0;
mHandler.sendEmptyMessageDelayed(0, FADE_DELAY);
return true;
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if (mListener != null) {
mListener.onTrackballEvent(event);
}
boolean oldDown = mCurDown;
mCurDown = true;
int baseX = mCurX;
int baseY = mCurY;
final float scaleX = event.getXPrecision();
final float scaleY = event.getYPrecision();
drawPoint(baseX + event.getX() * scaleX, baseY + event.getY() * scaleY,
event.getPressure(), event.getSize());
mCurDown = oldDown;
mFadeSteps = 0;
mHandler.sendEmptyMessageDelayed(0, FADE_DELAY);
return true;
}
public void setColor(int color) {
mColor = color;
}
public void setEventListener(EventListener listener) {
mListener = listener;
}
private void drawPoint(float x, float y, float pressure, float size) {
mCurX = (int) x;
mCurY = (int) y;
mCurSize = size;
mCurWidth = (int) (mCurSize * 128);
if (mCurWidth < 1) {
mCurWidth = 1;
}
if (mCurDown && mBitmap != null) {
int pressureLevel = (int) (Math.sqrt(pressure) * 128);
mPaint.setARGB(pressureLevel, Color.red(mColor), Color.green(mColor),
Color.blue(mColor));
mPaint.setMaskFilter(new BlurMaskFilter(mCurWidth / 2, BlurMaskFilter.Blur.NORMAL));
mCanvas.drawCircle(mCurX, mCurY, mCurWidth, mPaint);
mRect.set(mCurX - mCurWidth - 2, mCurY - mCurWidth - 2, mCurX + mCurWidth + 2, mCurY
+ mCurWidth + 2);
invalidate(mRect);
}
mFadeSteps = 0;
}
private void fade() {
if (mCanvas != null && mFadeSteps < MAX_FADE_STEPS) {
mCanvas.drawColor(Color.argb(FADE_ALPHA, 0xFF, 0xFF, 0xFF), Mode.DST_OUT);
invalidate();
mFadeSteps++;
} else if (mFadeSteps >= MAX_FADE_STEPS) {
mFadeSteps = 0;
mHandler.removeCallbacksAndMessages(null);
}
}
private void init() {
setFocusable(true);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.TRANSPARENT);
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
canvas.drawBitmap(mBitmap, 0, 0, null);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
int curW = mBitmap != null ? mBitmap.getWidth() : 0;
int curH = mBitmap != null ? mBitmap.getHeight() : 0;
if (curW >= w && curH >= h) return;
if (curW < w) {
curW = w;
}
if (curH < h) {
curH = h;
}
Bitmap newBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
Canvas newCanvas = new Canvas();
newCanvas.setBitmap(newBitmap);
if (mBitmap != null) {
newCanvas.drawBitmap(mBitmap, 0, 0, null);
}
mBitmap = newBitmap;
mCanvas = newCanvas;
mFadeSteps = MAX_FADE_STEPS;
}
public interface EventListener {
boolean onTouchEvent(MotionEvent event);
boolean onTrackballEvent(MotionEvent event);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/view/TouchPaintView.java
|
Java
|
gpl3
| 4,538
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp;
import android.net.Uri;
interface IMusicPlaybackService {
void reloadLyrics();
void refreshLyrics();
void openFile(String path);
void open(in long [] list, int position);
int getQueuePosition();
boolean isPlaying();
void stop();
void pause();
void play();
void prev();
void next();
void toggleRepeat();
void toggleShuffle();
long duration();
long position();
long seek(long pos);
String getTrackName();
String getMediaPath();
String getAlbumName();
long getAlbumId();
String getArtistName();
long getArtistId();
void enqueue(in long [] list, int action);
long [] getQueue();
void moveQueueItem(int from, int to);
void setQueuePosition(int index);
void setQueueId(long id);
String getPath();
long getAudioId();
Uri getArtworkUri();
String [] getLyrics();
int getLyricsStatus();
int getCurrentLyricsId();
long getPositionByLyricsId(int id);
void setShuffleMode(int shufflemode);
int getShuffleMode();
int removeTracks(int first, int last);
int removeTrack(long id);
void setRepeatMode(int repeatmode);
int getRepeatMode();
int getMediaMountedCount();
int getAudioSessionId();
void startSleepTimer(long millisecond, boolean gentle);
void stopSleepTimer();
long getSleepTimerRemained();
void reloadSettings();
void reloadEqualizer();
void toggleFavorite();
void addToFavorites(long id);
void removeFromFavorites(long id);
boolean isFavorite(long id);
boolean togglePause();
int eqGetNumberOfBands();
int[] eqGetBandLevelRange();
void eqSetBandLevel(int band, int level);
int eqGetBandLevel(int band);
int eqGetCenterFreq(int band);
int[] eqGetBandFreqRange(int band);
int eqGetBand(int frequency);
int eqGetCurrentPreset();
void eqUsePreset(int preset);
int eqGetNumberOfPresets();
String eqGetPresetName(int preset);
int eqSetEnabled(boolean enabled);
void eqRelease();
void eqReset();
}
|
061304011116lyj-yammp
|
src/org/yammp/IMusicPlaybackService.aidl
|
AIDL
|
gpl3
| 2,681
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import org.yammp.util.EqualizerWrapper;
import org.yammp.util.LyricsParser;
import org.yammp.util.MediaUtils;
import org.yammp.util.PreferencesEditor;
import org.yammp.util.ShakeListener;
import org.yammp.util.ShakeListener.OnShakeListener;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.Toast;
/**
* Provides "background" audio playback capabilities, allowing the user to
* switch between activities without stopping playback.
*/
public class MusicPlaybackService extends Service implements Constants, OnShakeListener {
/**
* used to specify whether enqueue() should start playing the new list of
* files right away, next or once all the currently queued files have been
* played
*/
private static final int TRACK_ENDED = 1;
private static final int RELEASE_WAKELOCK = 2;
private static final int SERVER_DIED = 3;
private static final int FOCUSCHANGE = 4;
private static final int FADEDOWN = 5;
private static final int FADEUP = 6;
private static final int NEW_LYRICS_LOADED = 1;
private static final int POSITION_CHANGED = 2;
private static final int LYRICS_REFRESHED = 3;
private static final int LYRICS_PAUSED = 4;
private static final int LYRICS_RESUMED = 5;
private static final int START_SLEEP_TIMER = 1;
private static final int STOP_SLEEP_TIMER = 2;
private MultiPlayer mPlayer;
private String mFileToPlay;
private NotificationManager mNotificationManager;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private int mMediaMountedCount = 0;
private long[] mPlayList = null;
private int mPlayListLen = 0;
private Vector<Integer> mHistory = new Vector<Integer>();
private Cursor mCursor;
private int mPlayPos = -1;
private Shuffler mShuffler = null;
private int mOpenFailedCounter = 0;
private String[] mCursorCols = new String[] { "audio._id AS _id",
MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.IS_PODCAST,
MediaStore.Audio.Media.BOOKMARK };
private final static int IDCOLIDX = 0;
private final static int PODCASTCOLIDX = 8;
private final static int BOOKMARKCOLIDX = 9;
private BroadcastReceiver mUnmountReceiver = null;
private BroadcastReceiver mA2dpReceiver = null;
private WakeLock mWakeLock;
private int mServiceStartId = -1;
private boolean mServiceInUse = false;
private boolean mIsSupposedToBePlaying = false;
private boolean mQuietMode = false;
private AudioManager mAudioManager;
private boolean mQueueIsSaveable = true;
// used to track what type of audio focus loss caused the playback to pause
private boolean mPausedByTransientLossOfFocus = false;
// used to track current volume
private float mCurrentVolume = 1.0f;
private PreferencesEditor mPrefs;
// We use this to distinguish between different cards when saving/restoring
// playlists.
// This will have to change if we want to support multiple simultaneous
// cards.
private int mCardId;
// interval after which we stop the service when idle
private static final int IDLE_DELAY = 60000;
private boolean mGentleSleepTimer, mSleepTimerTimedUp;
private long mCurrentTimestamp, mStopTimestamp;
private EqualizerWrapper mEqualizer = null;
private boolean mEqualizerSupported = EqualizerWrapper.isSupported();
private LyricsParser mLyricsParser = new LyricsParser();
private int mLyricsStatus = 0;
private int mLyricsId = -1;
private String[] mLyrics = new String[] {};
private ShakeListener mShakeDetector;
private boolean mShakeEnabled;
private String mShakingBehavior;
private float mShakingThreshold = DEFAULT_SHAKING_THRESHOLD;
private boolean mScrobbleEnabled = false;
private boolean mExternalAudioDeviceConnected = false;
private MediaUtils mUtils;
private YAMMPApplication mApplication;
private Intent mPlaybackIntent;
private Handler mMediaplayerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mUtils.debugLog("mMediaplayerHandler.handleMessage " + msg.what);
switch (msg.what) {
case FADEDOWN:
mCurrentVolume -= 0.05f;
if (mCurrentVolume > 0.2f) {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEDOWN, 10);
} else {
mCurrentVolume = 0.2f;
}
mPlayer.setVolume(mCurrentVolume);
break;
case FADEUP:
mCurrentVolume += 0.01f;
if (mCurrentVolume < 1.0f) {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEUP, 10);
} else {
mCurrentVolume = 1.0f;
}
mPlayer.setVolume(mCurrentVolume);
break;
case SERVER_DIED:
if (mIsSupposedToBePlaying) {
next(true);
} else {
// the server died when we were idle, so just
// reopen the same song (it will start again
// from the beginning though when the user
// restarts)
openCurrent();
}
break;
case TRACK_ENDED:
if (mRepeatMode == REPEAT_CURRENT) {
seek(0);
play();
} else {
next(false);
}
break;
case RELEASE_WAKELOCK:
mWakeLock.release();
break;
case FOCUSCHANGE:
// This code is here so we can better synchronize it with
// the code that handles fade-in
switch (msg.arg1) {
case AudioManager.AUDIOFOCUS_LOSS:
Log.v(LOGTAG_SERVICE, "AudioFocus: received AUDIOFOCUS_LOSS");
if (isPlaying()) {
mPausedByTransientLossOfFocus = false;
}
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
mMediaplayerHandler.removeMessages(FADEUP);
mMediaplayerHandler.sendEmptyMessage(FADEDOWN);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.v(LOGTAG_SERVICE, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
if (isPlaying()) {
mPlayer.setVolume((float) Math.pow(10.0, -8 / 20.0));
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
Log.v(LOGTAG_SERVICE, "AudioFocus: received AUDIOFOCUS_GAIN");
if (isPlaying() || mPausedByTransientLossOfFocus) {
mPausedByTransientLossOfFocus = false;
mCurrentVolume = 0f;
mPlayer.setVolume(mCurrentVolume);
play(); // also queues a fade-in
} else {
mMediaplayerHandler.removeMessages(FADEDOWN);
mMediaplayerHandler.sendEmptyMessage(FADEUP);
}
break;
default:
Log.e(LOGTAG_SERVICE, "Unknown audio focus change code");
}
break;
default:
break;
}
}
};
/**
* Lyrics Handler
*
* load lyrics automatically, most accurate and fastest ever.<br>
* Usage: send a empty message {@link #NEW_LYRICS_LOADED} when new song
* played.
*
* @author mariotaku
*/
private Handler mLyricsHandler = new Handler() {
private List<String> mLyricsList = new ArrayList<String>();
private int lyrics_id = 0;
@Override
public void handleMessage(Message msg) {
mLyricsHandler.removeMessages(LYRICS_REFRESHED);
switch (msg.what) {
case NEW_LYRICS_LOADED:
mLyricsId = -1;
lyrics_id = 0;
if (getMediaPath() == null) return;
String media_path = getMediaPath();
String lyrics_path = media_path.substring(0, media_path.lastIndexOf("."))
+ ".lrc";
mLyricsStatus = mLyricsParser.parseLyrics(lyrics_path);
mLyricsList = mLyricsParser.getAllLyrics();
mLyrics = mLyricsList.toArray(new String[mLyricsList.size()]);
notifyLyricsChange(BROADCAST_NEW_LYRICS_LOADED);
if (mLyricsStatus == LYRICS_STATUS_OK && isPlaying()) {
if (mLyricsParser.getTimestamp(lyrics_id) <= position()) {
mLyricsHandler.sendEmptyMessage(LYRICS_REFRESHED);
} else {
mLyricsHandler.sendEmptyMessageDelayed(LYRICS_REFRESHED,
mLyricsParser.getTimestamp(lyrics_id) - position());
}
}
break;
case LYRICS_REFRESHED:
if (mLyricsParser == null || mLyricsStatus != LYRICS_STATUS_OK) return;
if (lyrics_id < mLyricsParser.getAllLyrics().size()) {
mLyricsId = lyrics_id;
lyrics_id++;
notifyLyricsChange(BROADCAST_LYRICS_REFRESHED);
if (isPlaying()) {
mLyricsHandler.sendEmptyMessageDelayed(LYRICS_REFRESHED,
mLyricsParser.getTimestamp(lyrics_id) - position());
}
}
break;
case POSITION_CHANGED:
if (mLyricsParser == null || mLyricsStatus != LYRICS_STATUS_OK) return;
lyrics_id = mLyricsParser.getId(msg.arg1);
mLyricsHandler.sendEmptyMessageDelayed(LYRICS_REFRESHED,
mLyricsParser.getTimestamp(lyrics_id) - position());
break;
case LYRICS_PAUSED:
if (mLyricsParser == null || mLyricsStatus != LYRICS_STATUS_OK) return;
break;
case LYRICS_RESUMED:
if (mLyricsParser == null || mLyricsStatus != LYRICS_STATUS_OK) return;
if (lyrics_id < mLyricsParser.getAllLyrics().size()) {
lyrics_id = mLyricsParser.getId(position());
mLyricsHandler.sendEmptyMessageDelayed(LYRICS_REFRESHED,
mLyricsParser.getTimestamp(lyrics_id) - position());
}
break;
}
}
};
private BroadcastReceiver mExternalAudioDeviceStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
int state = intent.getIntExtra("state", 0);
mExternalAudioDeviceConnected = state == 1;
}
}
};
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra(CMDNAME);
mUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDSTOP.equals(cmd)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
} else if (CMDCYCLEREPEAT.equals(cmd) || CYCLEREPEAT_ACTION.equals(action)) {
toggleRepeat();
} else if (CMDTOGGLESHUFFLE.equals(cmd) || TOGGLESHUFFLE_ACTION.equals(action)) {
toggleShuffle();
} else if (CMDTOGGLEFAVORITE.equals(cmd)) {
if (!isFavorite()) {
addToFavorites();
} else {
removeFromFavorites();
}
}
}
};
private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
mMediaplayerHandler.obtainMessage(FOCUSCHANGE, focusChange, 0).sendToTarget();
}
};
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.v(LOGTAG_SERVICE, "PhoneState: received CALL_STATE_RINGING");
if (isPlaying()) {
mPausedByTransientLossOfFocus = true;
pause();
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.v(LOGTAG_SERVICE, "PhoneState: received CALL_STATE_OFFHOOK");
mPausedByTransientLossOfFocus = false;
if (isPlaying()) {
pause();
}
break;
}
}
};
private final char hexdigits[] = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) return;
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
private Handler mSleepTimerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case START_SLEEP_TIMER:
mSleepTimerHandler.removeMessages(START_SLEEP_TIMER, null);
if (mGentleSleepTimer) {
if (isPlaying()) {
mSleepTimerTimedUp = true;
} else {
pause();
mNotificationManager.cancel(ID_NOTIFICATION_SLEEPTIMER);
}
} else {
pause();
mNotificationManager.cancel(ID_NOTIFICATION_SLEEPTIMER);
}
mStopTimestamp = 0;
break;
case STOP_SLEEP_TIMER:
mStopTimestamp = 0;
mSleepTimerHandler.removeMessages(START_SLEEP_TIMER, null);
mNotificationManager.cancel(ID_NOTIFICATION_SLEEPTIMER);
break;
}
}
};
private final IBinder mBinder = new ServiceStub(this);
public MusicPlaybackService() {
}
public void addToFavorites() {
if (getAudioId() >= 0) {
addToFavorites(getAudioId());
}
}
public void addToFavorites(long id) {
mUtils.addToFavorites(id);
notifyChange(BROADCAST_FAVORITESTATE_CHANGED);
}
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath
* path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
stop(true);
notifyChange(BROADCAST_QUEUE_CHANGED);
notifyChange(BROADCAST_META_CHANGED);
}
/**
* Returns the duration of the file in milliseconds. Currently this method
* returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) return mPlayer.duration();
return -1;
}
/**
* Appends a list of tracks to the current playlist. If nothing is playing
* currently, playback will be started at the first track. If the action is
* NOW, playback will switch to the first of the new tracks immediately.
*
* @param list
* The list of tracks to append.
* @param action
* NOW, NEXT or LAST
*/
public void enqueue(long[] list, int action) {
synchronized (this) {
if (action == ACTION_NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(BROADCAST_QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 ==
// mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(BROADCAST_QUEUE_CHANGED);
if (action == ACTION_NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(BROADCAST_META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(BROADCAST_META_CHANGED);
}
}
}
public int eqGetBand(int frequency) {
if (!mEqualizerSupported || mEqualizer == null) return 0;
return mEqualizer.getBand(frequency);
}
public int[] eqGetBandFreqRange(short band) {
if (!mEqualizerSupported || mEqualizer == null) return null;
return mEqualizer.getBandFreqRange(band);
}
public short eqGetBandLevel(short band) {
if (mEqualizerSupported && mEqualizer != null) return mEqualizer.getBandLevel(band);
return (short) 0;
}
public short[] eqGetBandLevelRange() {
if (!mEqualizerSupported || mEqualizer == null) return null;
return mEqualizer.getBandLevelRange();
}
public int eqGetCenterFreq(short band) {
if (!mEqualizerSupported || mEqualizer == null) return 0;
return mEqualizer.getCenterFreq(band);
}
public short eqGetCurrentPreset() {
if (!mEqualizerSupported || mEqualizer == null) return 0;
return mEqualizer.getCurrentPreset();
}
public short eqGetNumberOfBands() {
if (!mEqualizerSupported || mEqualizer == null) return 0;
return mEqualizer.getNumberOfBands();
}
public short eqGetNumberOfPresets() {
if (!mEqualizerSupported || mEqualizer == null) return 0;
return mEqualizer.getNumberOfPresets();
}
public String eqGetPresetName(short preset) {
if (!mEqualizerSupported || mEqualizer == null) return null;
return mEqualizer.getPresetName(preset);
}
public void eqRelease() {
if (!mEqualizerSupported || mEqualizer == null) return;
mEqualizer.release();
}
public void eqReset() {
if (!mEqualizerSupported || mEqualizer == null) return;
for (short i = 0; i < eqGetNumberOfBands(); i++) {
eqSetBandLevel(i, (short) 0);
}
}
public void eqSetBandLevel(short band, short level) {
if (!mEqualizerSupported || mEqualizer == null) return;
mEqualizer.setBandLevel(band, level);
mPrefs.setEqualizerSetting(band, level);
}
public int eqSetEnabled(boolean enabled) {
if (!mEqualizerSupported || mEqualizer == null) return 0;
return mEqualizer.setEnabled(enabled);
}
public void eqUsePreset(short preset) {
if (!mEqualizerSupported || mEqualizer == null) return;
mEqualizer.usePreset(preset);
for (short i = 0; i < eqGetNumberOfBands(); i++) {
mPrefs.setEqualizerSetting(i, eqGetBandLevel(i));
}
}
public Bitmap getAlbumArt() {
synchronized (this) {
return mUtils.getArtwork(getAudioId(), getAlbumId());
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) return -1;
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) return null;
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) return -1;
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getArtistName() {
synchronized (this) {
if (mCursor == null) return null;
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public Uri getArtworkUri() {
synchronized (this) {
return mUtils.getArtworkUri(getAudioId(), getAlbumId());
}
}
/**
* Returns the rowid of the currently playing file, or -1 if no file is
* currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) return mPlayList[mPlayPos];
}
return -1;
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
public int getCurrentLyricsId() {
return mLyricsId;
}
public String[] getLyrics() {
return mLyrics;
}
public int getLyricsStatus() {
return mLyricsStatus;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the absolute path of the currently playing file, or null if no
* file is currently playing.
*/
public String getMediaPath() {
synchronized (this) {
if (mCursor == null) return null;
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
}
}
/**
* Returns the path of the currently playing file, or null if no file is
* currently playing.
*/
public String getPath() {
return mFileToPlay;
}
public long getPositionByLyricsId(int id) {
synchronized (this) {
if (mLyricsParser != null && id < mLyricsParser.getAllTimestamp().size())
return mLyricsParser.getTimestamp(id);
}
return position();
}
/**
* Returns the current play list
*
* @return An array of integers containing the IDs of the tracks in the play
* list
*/
public long[] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long[] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
/**
* Returns the position in the queue
*
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized (this) {
return mPlayPos;
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getShuffleMode() {
return mShuffleMode;
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) return null;
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
public boolean isFavorite() {
if (getAudioId() >= 0) return isFavorite(getAudioId());
return false;
}
public boolean isFavorite(long id) {
return mUtils.isFavorite(id);
}
/**
* Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/**
* Moves the item at index1 to index2.
*
* @param from
* @param to
*/
public void moveQueueItem(int from, int to) {
synchronized (this) {
if (from >= mPlayListLen) {
from = mPlayListLen - 1;
}
if (to >= mPlayListLen) {
to = mPlayListLen - 1;
}
if (from < to) {
long tmp = mPlayList[from];
for (int i = from; i < to; i++) {
mPlayList[i] = mPlayList[i + 1];
}
mPlayList[to] = tmp;
if (mPlayPos == from) {
mPlayPos = to;
} else if (mPlayPos >= from && mPlayPos <= to) {
mPlayPos--;
}
} else if (to < from) {
long tmp = mPlayList[from];
for (int i = from; i > to; i--) {
mPlayList[i] = mPlayList[i - 1];
}
mPlayList[to] = tmp;
if (mPlayPos == from) {
mPlayPos = to;
} else if (mPlayPos >= to && mPlayPos <= from) {
mPlayPos++;
}
}
notifyChange(BROADCAST_QUEUE_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mSleepTimerTimedUp) {
pause();
mNotificationManager.cancel(ID_NOTIFICATION_SLEEPTIMER);
mSleepTimerTimedUp = false;
return;
}
if (mPlayListLen <= 0) {
Log.d(LOGTAG_SERVICE, "No play queue");
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
if (mPlayPos >= 0) {
if (!mHistory.contains(mPlayPos)) {
mHistory.add(mPlayPos);
}
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i = 0; i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i = 0; i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <= 0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
// pick from full set
numUnplayed = numTracks;
for (int i = 0; i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(BROADCAST_PLAYSTATE_CHANGED);
}
return;
}
}
int skip = mShuffler.shuffle(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0) {
;
}
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(BROADCAST_PLAYSTATE_CHANGED);
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(BROADCAST_META_CHANGED);
}
}
public void notifyLyricsChange(String action) {
Intent i = new Intent(action);
if (BROADCAST_LYRICS_REFRESHED.equals(action)) {
i.putExtra(BROADCAST_KEY_LYRICS_ID, mLyricsId);
} else if (BROADCAST_NEW_LYRICS_LOADED.equals(action)) {
i.putExtra(BROADCAST_KEY_LYRICS_STATUS, mLyricsStatus);
i.putExtra(BROADCAST_KEY_LYRICS, mLyrics);
} else
return;
sendBroadcast(i);
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
mApplication = (YAMMPApplication) getApplication();
mUtils = mApplication.getMediaUtils();
mPlaybackIntent = new Intent();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName()));
mPrefs = new PreferencesEditor(getApplicationContext());
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mShakeDetector = new ShakeListener(this);
mCardId = mUtils.getCardId();
registerExternalStorageListener();
registerA2dpServiceListener();
// Needs to be done in this thread, since otherwise
// ApplicationContext.getPowerManager() crashes.
mPlayer = new MultiPlayer();
mPlayer.setHandler(mMediaplayerHandler);
if (mEqualizerSupported) {
mEqualizer = new EqualizerWrapper(0, getAudioSessionId());
if (mEqualizer != null) {
mEqualizer.setEnabled(true);
reloadEqualizer();
}
}
reloadQueue();
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(SERVICECMD);
commandFilter.addAction(TOGGLEPAUSE_ACTION);
commandFilter.addAction(PAUSE_ACTION);
commandFilter.addAction(NEXT_ACTION);
commandFilter.addAction(PREVIOUS_ACTION);
commandFilter.addAction(CYCLEREPEAT_ACTION);
commandFilter.addAction(TOGGLESHUFFLE_ACTION);
commandFilter.addAction(BROADCAST_PLAYSTATUS_REQUEST);
registerReceiver(mIntentReceiver, commandFilter);
registerReceiver(mExternalAudioDeviceStatusReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
mWakeLock.setReferenceCounted(false);
// If the service was idle, but got killed before it stopped itself, the
// system will relaunch it. Make sure it gets stopped again in that
// case.
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public void onDestroy() {
// Check that we're not being destroyed while something is still
// playing.
if (isPlaying()) {
Log.e(LOGTAG_SERVICE, "Service being destroyed while still playing.");
}
if (mEqualizer != null) {
mEqualizer.setEnabled(false);
mEqualizer.release();
}
mPlayer.release();
mPlayer = null;
mAudioManager.abandonAudioFocus(mAudioFocusListener);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
// make sure there aren't any other messages coming
mDelayedStopHandler.removeCallbacksAndMessages(null);
mMediaplayerHandler.removeCallbacksAndMessages(null);
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
unregisterReceiver(mIntentReceiver);
unregisterReceiver(mA2dpReceiver);
unregisterReceiver(mExternalAudioDeviceStatusReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
mWakeLock.release();
mNotificationManager.cancelAll();
removeStickyBroadcast(mPlaybackIntent);
super.onDestroy();
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onShake() {
mShakingBehavior = mPrefs.getStringPref(KEY_SHAKING_BEHAVIOR, DEFAULT_SHAKING_BEHAVIOR);
if (!BEHAVIOR_PLAY_PAUSE.equals(mShakingBehavior)
|| !BEHAVIOR_NEXT_SONG.equals(mShakingBehavior)) return;
if (mPlayer.isInitialized()) {
if (BEHAVIOR_PLAY_PAUSE.equals(mShakingBehavior)) {
if (isPlaying()) {
pause();
Toast.makeText(this, R.string.pause, Toast.LENGTH_SHORT).show();
} else {
play();
Toast.makeText(this, R.string.play, Toast.LENGTH_SHORT).show();
}
} else if (BEHAVIOR_NEXT_SONG.equals(mShakingBehavior)) {
if (isPlaying()) {
next(true);
Toast.makeText(this, R.string.next, Toast.LENGTH_SHORT).show();
} else {
play();
Toast.makeText(this, R.string.play, Toast.LENGTH_SHORT).show();
}
}
} else {
mUtils.shuffleAll();
Toast.makeText(this, R.string.shuffle_all, Toast.LENGTH_SHORT).show();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
mUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDTOGGLEFAVORITE.equals(cmd)) {
if (!isFavorite()) {
addToFavorites();
} else {
removeFromFavorites();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDSTOP.equals(cmd)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
} else if (CMDCYCLEREPEAT.equals(cmd) || CYCLEREPEAT_ACTION.equals(action)) {
toggleRepeat();
} else if (CMDTOGGLESHUFFLE.equals(cmd) || TOGGLESHUFFLE_ACTION.equals(action)) {
toggleShuffle();
} else if (BROADCAST_PLAYSTATUS_REQUEST.equals(action)) {
notifyChange(BROADCAST_PLAYSTATUS_RESPONSE);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
/*
* Desired behavior for prev/next/shuffle:
*
* - NEXT will move to the next track in the list when not shuffling, and to
* a track randomly picked from the not-yet-played tracks when shuffling. If
* all tracks have already been played, pick from the full set, but avoid
* picking the previously played track if possible. - when shuffling, PREV
* will go to the previously played track. Hitting PREV again will go to the
* track played before that, etc. When the start of the history has been
* reached, PREV is a no-op. When not shuffling, PREV will go to the
* sequentially previous track (the difference with the shuffle-case is
* mainly that when not shuffling, the user can back up to tracks that are
* not in the history).
*
* Example: When playing an album with 10 tracks from the start, and
* enabling shuffle while playing track 5, the remaining tracks (6-10) will
* be shuffled, e.g. the final play order might be 1-2-3-4-5-8-10-6-9-7.
* When hitting 'prev' 8 times while playing track 7 in this example, the
* user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next', a
* random track will be picked again. If at any time user disables shuffling
* the next/previous track will be picked in sequential order again.
*/
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) // something is
// currently
// playing, or will
// be playing once
// an in-progress action requesting audio focus ends, so don't stop
// the service now.
return true;
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between
// tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
/**
* Replaces the current playlist with a new list, and prepares for starting
* playback at the specified position in the list, or a random position if
* the specified position is 0.
*
* @param list
* The new list of tracks.
*/
public void open(long[] list, int position) {
synchronized (this) {
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(BROADCAST_QUEUE_CHANGED);
}
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mShuffler.shuffle(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(BROADCAST_META_CHANGED);
}
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path
* The full path of the file to be opened.
*/
public void open(String path) {
synchronized (this) {
if (path == null) return;
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (!mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls
// open() again.
next(false);
}
if (!mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG_SERVICE, "Failed to open file for playback");
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized (this) {
mMediaplayerHandler.removeMessages(FADEUP);
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(BROADCAST_PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
CharSequence contentTitle, contentText = null;
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) return;
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName()));
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000
&& mPlayer.position() >= duration - 2000) {
next(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped
// because
// of another focus loss
mMediaplayerHandler.removeMessages(FADEDOWN);
mMediaplayerHandler.sendEmptyMessage(FADEUP);
contentTitle = getTrackName();
String artist = getArtistName();
boolean isUnknownArtist = artist == null || MediaStore.UNKNOWN_STRING.equals(artist);
String album = getAlbumName();
boolean isUnknownAlbum = album == null || MediaStore.UNKNOWN_STRING.equals(album);
if (!isUnknownArtist && !isUnknownAlbum) {
contentText = getString(R.string.notification_artist_album, artist, album);
} else if (isUnknownArtist && !isUnknownAlbum) {
contentText = album;
} else if (!isUnknownArtist && isUnknownAlbum) {
contentText = artist;
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(
INTENT_PLAYBACK_VIEWER), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setOngoing(true);
builder.setSmallIcon(R.drawable.ic_stat_playback);
builder.setContentIntent(contentIntent);
builder.setContentTitle(contentTitle);
builder.setContentText(contentText);
mNotificationManager.notify(ID_NOTIFICATION_PLAYBACK, builder.getNotification());
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(BROADCAST_PLAYSTATE_CHANGED);
}
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_NORMAL);
}
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) return mPlayer.position();
return -1;
}
public void prev() {
synchronized (this) {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) // prev is a no-op
return;
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(BROADCAST_META_CHANGED);
}
};
public void registerA2dpServiceListener() {
mA2dpReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_PLAYSTATUS_REQUEST.equals(action)) {
notifyChange(BROADCAST_PLAYSTATUS_RESPONSE);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(BROADCAST_PLAYSTATUS_REQUEST);
registerReceiver(mA2dpReceiver, iFilter);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The
* intent will call closeExternalStorageFiles() if the external media is
* going to be ejected, so applications can clean up any files they have
* open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = mUtils.getCardId();
reloadQueue();
mQueueIsSaveable = true;
notifyChange(BROADCAST_QUEUE_CHANGED);
notifyChange(BROADCAST_META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
public void reloadEqualizer() {
if (mEqualizerSupported && mEqualizer != null) {
short bands = mEqualizer.getNumberOfBands();
final short minEQLevel = mEqualizer.getBandLevelRange()[0];
final short maxEQLevel = mEqualizer.getBandLevelRange()[1];
for (short i = 0; i < bands; i++) {
final short band = i;
mEqualizer.setBandLevel(band,
mPrefs.getEqualizerSetting(band, (short) ((maxEQLevel + minEQLevel) / 2)));
}
}
}
public void reloadLyrics() {
mLyricsHandler.removeCallbacksAndMessages(null);
mLyricsHandler.sendEmptyMessage(NEW_LYRICS_LOADED);
}
// TODO reload server settings
public void reloadSettings() {
mShakeEnabled = mPrefs.getBooleanPref(KEY_SHAKE_ENABLED, false);
mShakingThreshold = mPrefs.getFloatPref(KEY_SHAKING_THRESHOLD, DEFAULT_SHAKING_THRESHOLD);
if (mShakeDetector != null) {
mShakeDetector.stop();
if (mShakeEnabled) {
mShakeDetector.start();
}
mShakeDetector.setShakeThreshold(mShakingThreshold);
}
}
public void removeFromFavorites() {
if (getAudioId() >= 0) {
removeFromFavorites(getAudioId());
}
}
public void removeFromFavorites(long id) {
mUtils.removeFromFavorites(id);
notifyChange(BROADCAST_FAVORITESTATE_CHANGED);
}
/**
* Removes all instances of the track with the given id from the playlist.
*
* @param id
* The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(BROADCAST_QUEUE_CHANGED);
}
return numremoved;
}
/**
* Removes the range of tracks specified from the play list. If a file
* within the range is the file currently being played, playback will move
* to the next file after the range.
*
* @param first
* The first file to be removed
* @param last
* The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(BROADCAST_QUEUE_CHANGED);
}
return numremoved;
}
/**
* Seeks to the position specified.
*
* @param pos
* The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) {
pos = 0;
}
if (pos > mPlayer.duration()) {
pos = mPlayer.duration();
}
long result = mPlayer.seek(pos);
mLyricsHandler.obtainMessage(POSITION_CHANGED, (int) result, 0).sendToTarget();
return result;
}
return 0;
}
/**
* Starts playing the track at the given id in the queue.
*
* @param id
* The id in the queue of the track that will be played.
*/
public void setQueueId(long id) {
int pos = -1;
for (int i = 0; i < mPlayList.length; i++) {
if (id == mPlayList[i]) {
pos = i;
}
}
if (pos < 0) return;
setQueuePosition(pos);
}
/**
* Starts playing the track at the given position in the queue.
*
* @param pos
* The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized (this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(BROADCAST_META_CHANGED);
}
}
public void setRepeatMode(int repeatmode) {
synchronized (this) {
if (mRepeatMode == repeatmode) return;
if (mShuffleMode == SHUFFLE_NORMAL && repeatmode == REPEAT_CURRENT) {
setShuffleMode(SHUFFLE_NONE);
}
mRepeatMode = repeatmode;
notifyChange(BROADCAST_REPEATMODE_CHANGED);
saveQueue(false);
}
}
public void setShuffleMode(int shufflemode) {
synchronized (this) {
if (mShuffleMode == shufflemode && mPlayListLen < 1) return;
if (mRepeatMode == REPEAT_CURRENT) {
mRepeatMode = REPEAT_NONE;
}
mShuffleMode = shufflemode;
notifyChange(BROADCAST_SHUFFLEMODE_CHANGED);
saveQueue(false);
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
public void toggleFavorite() {
if (!isFavorite()) {
addToFavorites();
} else {
removeFromFavorites();
}
}
public boolean togglePause() {
if (isPlaying()) {
pause();
} else {
play();
}
return isPlaying();
}
public void toggleRepeat() {
if (mRepeatMode == REPEAT_NONE) {
setRepeatMode(REPEAT_ALL);
} else if (mRepeatMode == REPEAT_ALL) {
setRepeatMode(REPEAT_CURRENT);
if (mShuffleMode != SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NONE);
}
} else {
setRepeatMode(REPEAT_NONE);
}
}
public void toggleShuffle() {
if (mShuffleMode == SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NORMAL);
if (mRepeatMode == REPEAT_CURRENT) {
setRepeatMode(REPEAT_ALL);
}
} else if (mShuffleMode == SHUFFLE_NORMAL) {
setShuffleMode(SHUFFLE_NONE);
} else {
setShuffleMode(SHUFFLE_NONE);
Log.e("MediaPlaybackService", "Invalid shuffle mode: " + mShuffleMode);
}
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long[] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize; i > 0; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(BROADCAST_META_CHANGED);
}
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long[] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) return 0;
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
private long getSleepTimerRemained() {
Calendar now = Calendar.getInstance();
long mCurrentTimestamp = now.getTimeInMillis();
if (mStopTimestamp != 0)
return mStopTimestamp - mCurrentTimestamp;
else
return 0;
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
mNotificationManager.cancel(ID_NOTIFICATION_PLAYBACK);
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) return false;
return mCursor.getInt(PODCASTCOLIDX) > 0;
}
}
/**
* Notify the change-receivers that something has changed. The intent that
* is sent contains the following data for the currently playing track: "id"
* - Integer: the database row ID "artist" - String: the name of the artist
* "album_artist" - String: the name of the album artist "album" - String:
* the name of the album "track" - String: the name of the track The intent
* has an action that is one of "org.yammp.metachanged"
* "org.yammp.queuechanged", "org.yammp.playbackcomplete"
* "org.yammp.playstatechanged" respectively indicating that a new track has
* started playing, that the playback queue has changed, that playback has
* stopped because the last file in the list has been played, or that the
* play-state changed (paused/resumed).
*/
private void notifyChange(String action) {
mPlaybackIntent.setAction(action);
mPlaybackIntent.putExtra(BROADCAST_KEY_ID, getAudioId());
mPlaybackIntent.putExtra(BROADCAST_KEY_ARTIST, getArtistName());
mPlaybackIntent.putExtra(BROADCAST_KEY_ALBUM, getAlbumName());
mPlaybackIntent.putExtra(BROADCAST_KEY_TRACK, getTrackName());
mPlaybackIntent.putExtra(BROADCAST_KEY_PLAYING, isPlaying());
mPlaybackIntent.putExtra(BROADCAST_KEY_ISFAVORITE, isFavorite());
mPlaybackIntent.putExtra(BROADCAST_KEY_SONGID, getAudioId());
mPlaybackIntent.putExtra(BROADCAST_KEY_ALBUMID, getAlbumId());
mPlaybackIntent.putExtra(BROADCAST_KEY_DURATION, duration());
mPlaybackIntent.putExtra(BROADCAST_KEY_POSITION, position());
mPlaybackIntent.putExtra(BROADCAST_KEY_SHUFFLEMODE, getShuffleMode());
mPlaybackIntent.putExtra(BROADCAST_KEY_REPEATMODE, getRepeatMode());
if (mPlayList != null) {
mPlaybackIntent.putExtra(BROADCAST_KEY_LISTSIZE, Long.valueOf(mPlayList.length));
} else {
mPlaybackIntent.putExtra(BROADCAST_KEY_LISTSIZE, Long.valueOf(mPlayListLen));
}
sendStickyBroadcast(mPlaybackIntent);
if (BROADCAST_META_CHANGED.equals(action)) {
mLyricsHandler.sendEmptyMessage(NEW_LYRICS_LOADED);
if (isPlaying()) {
sendScrobbleBroadcast(SCROBBLE_PLAYSTATE_START);
} else {
sendScrobbleBroadcast(SCROBBLE_PLAYSTATE_COMPLETE);
}
}
if (BROADCAST_PLAYSTATE_CHANGED.equals(action)) {
notifyLyricsChange(BROADCAST_LYRICS_REFRESHED);
if (isPlaying()) {
mLyricsHandler.sendEmptyMessage(LYRICS_RESUMED);
sendScrobbleBroadcast(SCROBBLE_PLAYSTATE_RESUME);
} else {
mLyricsHandler.sendEmptyMessage(LYRICS_PAUSED);
sendScrobbleBroadcast(SCROBBLE_PLAYSTATE_PAUSE);
}
}
if (BROADCAST_QUEUE_CHANGED.equals(action)) {
saveQueue(true);
} else {
saveQueue(false);
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) return;
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
private void reloadQueue() {
String q = null;
int id = mCardId;
if (getSharedPreferences(SHAREDPREFS_STATES, Context.MODE_PRIVATE).contains(
STATE_KEY_CARDID)) {
id = mPrefs.getIntState(STATE_KEY_CARDID, mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPrefs.getStringState(STATE_KEY_QUEUE, "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
// Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += c - '0' << shift;
} else if (c >= 'a' && c <= 'f') {
n += 10 + c - 'a' << shift;
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
//TODO shuffler.
mShuffler = new Shuffler(mPlayList);
mPlayListLen = plen;
int pos = mPrefs.getIntState(STATE_KEY_CURRPOS, 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor cur = mUtils.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { "_id" }, "_id=" + mPlayList[mPlayPos], null, null);
if (cur == null || cur.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
cur = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos], null, null);
}
if (cur != null) {
cur.close();
}
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
mLyricsHandler.sendEmptyMessage(NEW_LYRICS_LOADED);
long seekpos = mPrefs.getLongState(STATE_KEY_SEEKPOS, 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG_SERVICE, "restored queue, currently at position " + position() + "/"
+ duration() + " (requested " + seekpos + ")");
int repmode = mPrefs.getIntState(STATE_KEY_REPEATMODE, REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPrefs.getIntState(STATE_KEY_SHUFFLEMODE, SHUFFLE_NONE);
if (shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPrefs.getStringState(STATE_KEY_HISTORY, "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
if (!mHistory.contains(mPlayPos)) {
mHistory.add(mPlayPos);
}
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += c - '0' << shift;
} else if (c >= 'a' && c <= 'f') {
n += 10 + c - 'a' << shift;
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
mShuffleMode = shufmode;
}
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) {
first = 0;
}
if (last >= mPlayListLen) {
last = mPlayListLen - 1;
}
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= last - first + 1;
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
notifyChange(BROADCAST_META_CHANGED);
}
return last - first + 1;
}
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if (pos < bookmark && pos + 10000 > bookmark || pos > bookmark
&& pos - 10000 < bookmark) // The existing bookmark is
// close to the current
// position, so don't update it.
return;
if (pos < 15000 || pos + 10000 > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
private void saveQueue(boolean full) {
if (!mQueueIsSaveable) return;
// long start = System.currentTimeMillis();
if (full) {
StringBuilder q = new StringBuilder();
// The current playlist is saved as a list of "reverse hexadecimal"
// numbers, which we can generate faster than normal decimal or
// hexadecimal numbers, which in turn allows us to save the playlist
// more often without worrying too much about performance.
// (saving the full state takes about 40 ms under no-load conditions
// on the phone)
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
long n = mPlayList[i];
if (n < 0) {
continue;
} else if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = (int) (n & 0xf);
n >>>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
// Log.i("@@@@ service", "created queue string in " +
// (System.currentTimeMillis() - start) + " ms");
mPrefs.setStringState(STATE_KEY_QUEUE, q.toString());
mPrefs.setIntState(STATE_KEY_CARDID, mCardId);
if (mShuffleMode != SHUFFLE_NONE) {
// In shuffle mode we need to save the history too
len = mHistory.size();
q.setLength(0);
for (int i = 0; i < len; i++) {
int n = mHistory.get(i);
if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = n & 0xf;
n >>>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
mPrefs.setStringState(STATE_KEY_HISTORY, q.toString());
}
}
mPrefs.setIntState(STATE_KEY_CURRPOS, mPlayPos);
if (mPlayer.isInitialized()) {
mPrefs.setLongState(STATE_KEY_SEEKPOS, mPlayer.position());
}
mPrefs.setIntState(STATE_KEY_REPEATMODE, mRepeatMode);
mPrefs.setIntState(STATE_KEY_SHUFFLEMODE, mShuffleMode);
// Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis()
// - start) + " ms");
}
private void sendScrobbleBroadcast(int state) {
mScrobbleEnabled = mPrefs.getBooleanPref(KEY_ENABLE_SCROBBLING, false);
// check that state is a valid state
if (state != SCROBBLE_PLAYSTATE_START && state != SCROBBLE_PLAYSTATE_RESUME
&& state != SCROBBLE_PLAYSTATE_PAUSE && state != SCROBBLE_PLAYSTATE_COMPLETE)
return;
if (mScrobbleEnabled) {
Intent i = new Intent(SCROBBLE_SLS_API);
i.putExtra(BROADCAST_KEY_APP_NAME, getString(R.string.app_name));
i.putExtra(BROADCAST_KEY_APP_PACKAGE, getPackageName());
i.putExtra(BROADCAST_KEY_STATE, state);
i.putExtra(BROADCAST_KEY_ARTIST, getArtistName());
i.putExtra(BROADCAST_KEY_ALBUM, getAlbumName());
i.putExtra(BROADCAST_KEY_TRACK, getTrackName());
i.putExtra(BROADCAST_KEY_DURATION, (int) (duration() / 1000));
sendBroadcast(i);
}
}
private void startSleepTimer(long milliseconds, boolean gentle) {
Calendar now = Calendar.getInstance();
mCurrentTimestamp = now.getTimeInMillis();
mStopTimestamp = mCurrentTimestamp + milliseconds;
int format_flags = DateUtils.FORMAT_NO_NOON_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL
| DateUtils.FORMAT_CAP_AMPM;
format_flags |= DateUtils.FORMAT_SHOW_TIME;
String time = DateUtils.formatDateTime(this, mStopTimestamp, format_flags);
CharSequence contentTitle = getString(R.string.sleep_timer_enabled);
CharSequence contentText = getString(R.string.notification_sleep_timer, time);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setOngoing(true);
builder.setSmallIcon(R.drawable.ic_stat_sleeptimer);
builder.setContentIntent(contentIntent);
builder.setContentTitle(contentTitle);
builder.setContentText(contentText);
mGentleSleepTimer = gentle;
mNotificationManager.notify(ID_NOTIFICATION_SLEEPTIMER, builder.getNotification());
mSleepTimerHandler.sendEmptyMessageDelayed(START_SLEEP_TIMER, milliseconds);
Toast.makeText(
this,
getResources().getQuantityString(R.plurals.NNNminutes_notif,
Integer.valueOf((int) milliseconds / 60 / 1000),
Integer.valueOf((int) milliseconds / 60 / 1000)), Toast.LENGTH_SHORT)
.show();
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
mNotificationManager.cancel(ID_NOTIFICATION_PLAYBACK);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
private void stopSleepTimer() {
mSleepTimerHandler.sendEmptyMessage(STOP_SLEEP_TIMER);
Toast.makeText(this, R.string.sleep_timer_disabled, Toast.LENGTH_SHORT).show();
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
mUtils.debugDump(writer);
}
/**
* Provides a unified interface for dealing with midi files and other media
* files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
private MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
private MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode
// does
// not
// require the media service, so it's OK to do this now,
// while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MusicPlaybackService.this,
PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public MultiPlayer() {
mMediaPlayer.setWakeMode(MusicPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public long duration() {
return mMediaPlayer.getDuration();
}
public int getAudioSessionId() {
try {
return (Integer) mMediaPlayer.getClass()
.getMethod("getAudioSessionId", new Class[] {})
.invoke(mMediaPlayer, new Object[] {});
} catch (Exception e) {
return 0;
}
}
public boolean isInitialized() {
return mIsInitialized;
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public void pause() {
mMediaPlayer.pause();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MusicPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setHandler(Handler handler) {
mHandler = handler;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
mCurrentVolume = vol;
}
public void start() {
mUtils.debugLog(new Exception("MultiPlayer.start called"));
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
private List<Long> mHistory = new ArrayList<Long>();
private long[] mQueue = new long[] {};
private List<Long> mUnplayed = new ArrayList<Long>();
private Long mPreviousRandom = null, mCurrentRandom = null, mNextRandom = null;
private int mPosition = 0;
private boolean mTracebackMode = false;
public Shuffler(long[] queue) {
if (queue == null || queue.length <= 0) {
throw new IllegalArgumentException("queue cannot be null or zero-sized!");
}
mQueue = queue;
mPreviousRandom = null;
mCurrentRandom = (long) mRandom.nextInt(mQueue.length);
mHistory.add(mCurrentRandom);
long tmp_random = mRandom.nextInt(mQueue.length);
while (mCurrentRandom == tmp_random) {
tmp_random = mRandom.nextInt(mQueue.length);
}
mNextRandom = tmp_random;
}
public void reloadQueue(long[] queue){
if (queue == null || queue.length <= 0) {
throw new IllegalArgumentException("queue cannot be null or zero-sized!");
}
mQueue = queue;
List<Long> tmp_list = new ArrayList<Long>();
for (long item : queue) {
tmp_list.add(item);
}
for (Long item : mHistory) {
if (!tmp_list.contains(item)) mHistory.remove(item);
}
}
public Long getPrevious() {
return mPreviousRandom;
}
public Long getNext() {
return mNextRandom;
}
public Long getCurrent() {
return mCurrentRandom;
}
public Long doNextShuffle() {
if (mHistory.size() > 0) {
if (!mTracebackMode) {
mPreviousRandom = mCurrentRandom;
mCurrentRandom = mNextRandom;
mHistory.add(mCurrentRandom);
if (mHistory.size() >= 1) {
mPosition = mHistory.size() - 1;
} else {
mPosition = 0;
}
long tmp_random = mRandom.nextInt(mQueue.length);
while (mCurrentRandom == tmp_random) {
tmp_random = mRandom.nextInt(mQueue.length);
}
mNextRandom = tmp_random;
} else {
mPreviousRandom = mPosition < 0 ? mHistory.get(mPosition) : null;
mCurrentRandom = mHistory.get(mPosition);
mNextRandom = mPosition < mHistory.size() - 1 ? mHistory.get(mPosition + 1)
: null;
mPosition++;
}
} else {
mPreviousRandom = null;
mCurrentRandom = (long) mRandom.nextInt(mQueue.length);
mHistory.add(mCurrentRandom);
long tmp_random = mRandom.nextInt(mQueue.length);
while (mCurrentRandom == tmp_random) {
tmp_random = mRandom.nextInt(mQueue.length);
}
mNextRandom = tmp_random;
}
return mCurrentRandom;
}
public void goToPosition(int position) {
if (position >= mHistory.size() - 1) {
mTracebackMode = false;
return;
} else if (position < 0) {
mPosition = 0;
} else {
mPosition = position;
}
mTracebackMode = true;
mPreviousRandom = mPosition < 0 ? mHistory.get(mPosition) : null;
mCurrentRandom = mHistory.get(mPosition);
mNextRandom = mPosition < mHistory.size() - 1 ? mHistory.get(mPosition + 1) : null;
}
public void goByPosition(int offset) {
goToPosition(mPosition + offset);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still has
* a remote reference to the stub.
*/
static class ServiceStub extends IMusicPlaybackService.Stub {
WeakReference<MusicPlaybackService> mService;
ServiceStub(MusicPlaybackService service) {
mService = new WeakReference<MusicPlaybackService>(service);
}
@Override
public void addToFavorites(long id) {
mService.get().addToFavorites(id);
}
@Override
public long duration() {
return mService.get().duration();
}
@Override
public void enqueue(long[] list, int action) {
mService.get().enqueue(list, action);
}
@Override
public int eqGetBand(int frequency) {
return mService.get().eqGetBand(frequency);
}
@Override
public int[] eqGetBandFreqRange(int band) {
return mService.get().eqGetBandFreqRange((short) band);
}
@Override
public int eqGetBandLevel(int band) {
return mService.get().eqGetBandLevel((short) band);
}
@Override
public int[] eqGetBandLevelRange() {
short[] value = mService.get().eqGetBandLevelRange();
if (value == null) return null;
int[] result = new int[value.length];
for (short i = 0; i < value.length; i++) {
result[i] = value[i];
}
return result;
}
@Override
public int eqGetCenterFreq(int band) {
return mService.get().eqGetCenterFreq((short) band);
}
@Override
public int eqGetCurrentPreset() {
return mService.get().eqGetCurrentPreset();
}
@Override
public int eqGetNumberOfBands() {
return mService.get().eqGetNumberOfBands();
}
@Override
public int eqGetNumberOfPresets() {
return mService.get().eqGetNumberOfPresets();
}
@Override
public String eqGetPresetName(int preset) {
return mService.get().eqGetPresetName((short) preset);
}
@Override
public void eqRelease() {
mService.get().eqRelease();
}
@Override
public void eqReset() {
mService.get().eqReset();
}
@Override
public void eqSetBandLevel(int band, int level) {
mService.get().eqSetBandLevel((short) band, (short) level);
}
@Override
public int eqSetEnabled(boolean enabled) {
return mService.get().eqSetEnabled(enabled);
}
@Override
public void eqUsePreset(int preset) {
mService.get().eqUsePreset((short) preset);
}
@Override
public long getAlbumId() {
return mService.get().getAlbumId();
}
@Override
public String getAlbumName() {
return mService.get().getAlbumName();
}
@Override
public long getArtistId() {
return mService.get().getArtistId();
}
@Override
public String getArtistName() {
return mService.get().getArtistName();
}
@Override
public Uri getArtworkUri() {
return mService.get().getArtworkUri();
}
@Override
public long getAudioId() {
return mService.get().getAudioId();
}
@Override
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
@Override
public int getCurrentLyricsId() {
return mService.get().getCurrentLyricsId();
}
@Override
public String[] getLyrics() {
return mService.get().getLyrics();
}
@Override
public int getLyricsStatus() {
return mService.get().getLyricsStatus();
}
@Override
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
@Override
public String getMediaPath() {
return mService.get().getMediaPath();
}
@Override
public String getPath() {
return mService.get().getPath();
}
@Override
public long getPositionByLyricsId(int id) {
return mService.get().getPositionByLyricsId(id);
}
@Override
public long[] getQueue() {
return mService.get().getQueue();
}
@Override
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
@Override
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
@Override
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
@Override
public long getSleepTimerRemained() {
return mService.get().getSleepTimerRemained();
}
@Override
public String getTrackName() {
return mService.get().getTrackName();
}
@Override
public boolean isFavorite(long id) {
return mService.get().isFavorite(id);
}
@Override
public boolean isPlaying() {
return mService.get().isPlaying();
}
@Override
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
@Override
public void next() {
mService.get().next(true);
}
@Override
public void open(long[] list, int position) {
mService.get().open(list, position);
}
@Override
public void openFile(String path) {
mService.get().open(path);
}
@Override
public void pause() {
mService.get().pause();
}
@Override
public void play() {
mService.get().play();
}
@Override
public long position() {
return mService.get().position();
}
@Override
public void prev() {
mService.get().prev();
}
@Override
public void refreshLyrics() {
mService.get().notifyLyricsChange(BROADCAST_LYRICS_REFRESHED);
}
@Override
public void reloadEqualizer() {
mService.get().reloadEqualizer();
}
@Override
public void reloadLyrics() {
mService.get().reloadLyrics();
}
@Override
public void reloadSettings() {
mService.get().reloadSettings();
}
@Override
public void removeFromFavorites(long id) {
mService.get().removeFromFavorites(id);
}
@Override
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
@Override
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
@Override
public long seek(long pos) {
return mService.get().seek(pos);
}
@Override
public void setQueueId(long id) {
mService.get().setQueueId(id);
}
@Override
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
@Override
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
@Override
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
@Override
public void startSleepTimer(long milliseconds, boolean gentle) {
mService.get().startSleepTimer(milliseconds, gentle);
}
@Override
public void stop() {
mService.get().stop();
}
@Override
public void stopSleepTimer() {
mService.get().stopSleepTimer();
}
@Override
public void toggleFavorite() {
mService.get().toggleFavorite();
}
@Override
public boolean togglePause() {
return mService.get().togglePause();
}
@Override
public void toggleRepeat() {
mService.get().toggleRepeat();
}
@Override
public void toggleShuffle() {
mService.get().toggleShuffle();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/MusicPlaybackService.java
|
Java
|
gpl3
| 78,582
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp;
import org.yammp.app.MediaPlayerActivity;
import org.yammp.app.MusicPlaybackActivity;
import org.yammp.util.MediaUtils;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.RemoteViews;
/**
* Simple widget to show currently playing album art along with play/pause and
* next track buttons.
*/
public class MediaAppWidgetProvider4x1 extends AppWidgetProvider implements Constants {
private static String mTrackName, mTrackDetail;
private static long mAlbumId, mAudioId;
private static boolean mIsPlaying;
private static String[] mLyrics = new String[] {};
private static int mLyricsStat;
@Override
public void onReceive(Context context, Intent intent) {
performUpdate(context, intent);
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
init(context, appWidgetIds);
}
/**
* Initialize given widgets to default state, where we launch Music on
* default click and hide actions if service not running.
*/
private void init(Context context, int[] appWidgetIds) {
final Resources res = context.getResources();
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.album_appwidget4x1);
views.setViewVisibility(R.id.track_name, View.GONE);
views.setTextViewText(R.id.track_detail, res.getText(R.string.widget_initial_text));
views.setViewVisibility(R.id.album_art, View.GONE);
views.setViewVisibility(R.id.lyrics_line, View.GONE);
linkButtons(context, views, false);
pushUpdate(context, appWidgetIds, views);
}
/**
* Link up various button actions using {@link PendingIntents}.
*
* @param isPlaying
* True if player is active in background, which means widget
* click will launch {@link MusicPlaybackActivity}, otherwise we
* launch {@link MediaPlayerActivity}.
*/
private void linkButtons(Context context, RemoteViews views, boolean isPlaying) {
// Connect up various buttons and touch events
PendingIntent pendingIntent;
if (isPlaying) {
pendingIntent = PendingIntent.getActivity(context, 0,
new Intent(INTENT_PLAYBACK_VIEWER), 0);
views.setOnClickPendingIntent(R.id.album_appwidget, pendingIntent);
} else {
pendingIntent = PendingIntent.getActivity(context, 0, new Intent(INTENT_MUSIC_BROWSER),
0);
views.setOnClickPendingIntent(R.id.album_appwidget, pendingIntent);
}
final ComponentName serviceName = new ComponentName(context, MusicPlaybackService.class);
pendingIntent = PendingIntent.getService(context, 0,
new Intent(TOGGLEPAUSE_ACTION).setComponent(serviceName), 0);
views.setOnClickPendingIntent(R.id.control_play, pendingIntent);
pendingIntent = PendingIntent.getService(context, 0,
new Intent(NEXT_ACTION).setComponent(serviceName), 0);
views.setOnClickPendingIntent(R.id.control_next, pendingIntent);
}
/**
* Update all active widget instances by pushing changes
*/
private void performUpdate(Context context, Intent intent) {
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, this
.getClass()));
final Resources res = context.getResources();
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.album_appwidget4x1);
if (BROADCAST_META_CHANGED.equals(intent.getAction())
|| BROADCAST_PLAYSTATE_CHANGED.equals(intent.getAction())) {
mTrackName = intent.getStringExtra(BROADCAST_KEY_TRACK);
String artist = intent.getStringExtra(BROADCAST_KEY_ARTIST);
String album = intent.getStringExtra(BROADCAST_KEY_ALBUM);
if (artist != null && !MediaStore.UNKNOWN_STRING.equals(artist)) {
mTrackDetail = artist;
} else if (album != null && !MediaStore.UNKNOWN_STRING.equals(album)) {
mTrackDetail = album;
} else {
mTrackDetail = null;
}
mAlbumId = intent.getLongExtra(BROADCAST_KEY_ALBUMID, -1);
mAudioId = intent.getLongExtra(BROADCAST_KEY_SONGID, -1);
mIsPlaying = intent.getBooleanExtra(BROADCAST_KEY_PLAYING, false);
views.setTextViewText(R.id.lyrics_line, "");
} else if (BROADCAST_NEW_LYRICS_LOADED.equals(intent.getAction())) {
mLyrics = intent.getStringArrayExtra(BROADCAST_KEY_LYRICS);
mLyricsStat = intent.getIntExtra(BROADCAST_KEY_LYRICS_STATUS, LYRICS_STATUS_INVALID);
}
CharSequence errorState = null;
// Format title string with track number, or show SD card message
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_SHARED) || status.equals(Environment.MEDIA_UNMOUNTED)) {
errorState = res.getText(R.string.sdcard_busy_title);
} else if (status.equals(Environment.MEDIA_REMOVED)) {
errorState = res.getText(R.string.sdcard_missing_title);
} else if (mTrackName == null) {
errorState = res.getText(R.string.emptyplaylist);
}
if (errorState != null) {
// Show error state to user
views.setViewVisibility(R.id.track_name, View.GONE);
views.setTextViewText(R.id.track_detail, errorState);
views.setViewVisibility(R.id.album_art, View.GONE);
views.setViewVisibility(R.id.lyrics_line, View.GONE);
} else {
// No error, so show normal titles and artwork
views.setViewVisibility(R.id.track_name, View.VISIBLE);
views.setViewVisibility(R.id.lyrics_line, View.VISIBLE);
views.setTextViewText(R.id.track_name, mTrackName);
views.setViewVisibility(R.id.album_art, mTrackDetail != null ? View.VISIBLE : View.GONE);
if (mTrackDetail != null) {
views.setTextViewText(R.id.track_detail, mTrackDetail);
}
// Set album art
Uri uri = null;
if (mAudioId >= 0 && mAlbumId >= 0) {
uri = new MediaUtils(context).getArtworkUri(mAudioId, mAlbumId);
}
if (uri != null) {
views.setImageViewUri(R.id.album_art, uri);
} else {
views.setImageViewResource(R.id.album_art, R.drawable.ic_mp_albumart_unknown);
}
if (BROADCAST_LYRICS_REFRESHED.equals(intent.getAction())) {
int lyrics_id = intent.getIntExtra(BROADCAST_KEY_LYRICS_ID, -1);
if (mLyrics != null && mLyrics.length > lyrics_id && lyrics_id >= 0) {
if (mLyricsStat == LYRICS_STATUS_OK) {
views.setViewVisibility(R.id.track_name, View.VISIBLE);
views.setTextViewText(R.id.lyrics_line, mLyrics[lyrics_id]);
} else {
views.setViewVisibility(R.id.lyrics_line, View.GONE);
views.setTextViewText(R.id.lyrics_line, "");
}
} else {
views.setViewVisibility(R.id.lyrics_line, View.GONE);
}
}
}
if (mIsPlaying) {
views.setImageViewResource(R.id.control_play, R.drawable.btn_playback_ic_pause);
} else {
views.setImageViewResource(R.id.control_play, R.drawable.btn_playback_ic_play);
}
linkButtons(context, views, mIsPlaying);
pushUpdate(context, appWidgetIds, views);
}
private void pushUpdate(Context context, int[] appWidgetIds, RemoteViews views) {
// Update specific list of appWidgetIds if given, otherwise default to
// all
final AppWidgetManager gm = AppWidgetManager.getInstance(context);
if (appWidgetIds != null) {
gm.updateAppWidget(appWidgetIds, views);
} else {
gm.updateAppWidget(new ComponentName(context, this.getClass()), views);
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/MediaAppWidgetProvider4x1.java
|
Java
|
gpl3
| 8,414
|
package org.yammp.dialog;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlaylistPicker extends FragmentActivity implements DialogInterface.OnClickListener,
DialogInterface.OnCancelListener, Constants {
private AlertDialog mPlayListPickerDialog;
List<Map<String, String>> mAllPlayLists = new ArrayList<Map<String, String>>();
List<String> mPlayListNames = new ArrayList<String>();
long[] mList = new long[] {};
private MediaUtils mUtils;
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
@Override
public void onClick(DialogInterface dialog, int which) {
long listId = Long.valueOf(mAllPlayLists.get(which).get(MAP_KEY_ID));
String listName = mAllPlayLists.get(which).get(MAP_KEY_NAME);
Intent intent;
boolean mCreateShortcut = getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT);
if (mCreateShortcut) {
final Intent shortcut = new Intent();
shortcut.setAction(INTENT_PLAY_SHORTCUT);
shortcut.putExtra(MAP_KEY_ID, listId);
intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, listName);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
.fromContext(this, R.drawable.ic_launcher_shortcut_playlist));
setResult(RESULT_OK, intent);
} else {
if (listId >= 0) {
mUtils.addToPlaylist(mList, listId);
} else if (listId == PLAYLIST_QUEUE) {
mUtils.addToCurrentPlaylist(mList);
} else if (listId == PLAYLIST_NEW) {
intent = new Intent(INTENT_CREATE_PLAYLIST);
intent.putExtra(INTENT_KEY_LIST, mList);
startActivity(intent);
}
}
finish();
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(new LinearLayout(this));
if (getIntent().getAction() != null) {
if (INTENT_ADD_TO_PLAYLIST.equals(getIntent().getAction())
&& getIntent().getLongArrayExtra(INTENT_KEY_LIST) != null) {
mUtils.makePlaylistList(false, mAllPlayLists);
mList = getIntent().getLongArrayExtra(INTENT_KEY_LIST);
for (int i = 0; i < mAllPlayLists.size(); i++) {
mPlayListNames.add(mAllPlayLists.get(i).get(MAP_KEY_NAME));
}
mPlayListPickerDialog = new AlertDialog.Builder(this)
.setTitle(R.string.add_to_playlist)
.setItems(mPlayListNames.toArray(new CharSequence[mPlayListNames.size()]),
this).setOnCancelListener(this).show();
} else if (getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)) {
mUtils.makePlaylistList(true, mAllPlayLists);
for (int i = 0; i < mAllPlayLists.size(); i++) {
mPlayListNames.add(mAllPlayLists.get(i).get(MAP_KEY_NAME));
}
mPlayListPickerDialog = new AlertDialog.Builder(this)
.setTitle(R.string.playlists)
.setItems(mPlayListNames.toArray(new CharSequence[mPlayListNames.size()]),
this).setOnCancelListener(this).show();
}
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onPause() {
if (mPlayListPickerDialog != null && mPlayListPickerDialog.isShowing()) {
mPlayListPickerDialog.dismiss();
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (mPlayListPickerDialog != null && !mPlayListPickerDialog.isShowing()) {
mPlayListPickerDialog.show();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/PlaylistPicker.java
|
Java
|
gpl3
| 3,841
|
package org.yammp.dialog;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import org.yammp.util.ServiceToken;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayShortcut extends FragmentActivity implements Constants, ServiceConnection {
private long mPlaylistId;
private ServiceToken mToken = null;
private MediaUtils mUtils;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(new LinearLayout(this));
mPlaylistId = getIntent().getLongExtra(MAP_KEY_ID, PLAYLIST_UNKNOWN);
mToken = mUtils.bindToService(this);
}
@Override
public void onServiceConnected(ComponentName classname, IBinder obj) {
if (getIntent().getAction() != null && getIntent().getAction().equals(INTENT_PLAY_SHORTCUT)
&& mPlaylistId != PLAYLIST_UNKNOWN) {
switch ((int) mPlaylistId) {
case (int) PLAYLIST_ALL_SONGS:
mUtils.playAll();
break;
case (int) PLAYLIST_RECENTLY_ADDED:
mUtils.playRecentlyAdded();
break;
default:
if (mPlaylistId >= 0) {
mUtils.playPlaylist(mPlaylistId);
}
break;
}
} else {
Toast.makeText(PlayShortcut.this, R.string.error_bad_parameters, Toast.LENGTH_SHORT)
.show();
}
finish();
}
@Override
public void onServiceDisconnected(ComponentName classname) {
finish();
}
@Override
public void onStop() {
if (mToken != null) {
mUtils.unbindFromService(mToken);
}
finish();
super.onStop();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/PlayShortcut.java
|
Java
|
gpl3
| 1,788
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.dialog;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import org.yammp.util.PreferencesEditor;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class SleepTimerDialog extends FragmentActivity implements OnSeekBarChangeListener,
Constants {
private SeekBar mSetTime;
private TextView mTimeView;
private String mPrompt;
private int mProgress, mTimerTime, mRemained;
private AlertDialog mSleepTimerDialog;
private String action;
private MediaUtils mUtils;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(new LinearLayout(this));
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
action = getIntent().getAction();
mSleepTimerDialog = new AlertDialog.Builder(this).create();
mSleepTimerDialog.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mRemained = (int) mUtils.getSleepTimerRemained() / 1000 / 60;
LinearLayout mContainer = new LinearLayout(this);
mContainer.setOrientation(LinearLayout.VERTICAL);
mContainer.setPadding((int) dm.density * 8, 0, (int) dm.density * 8, 0);
mTimeView = new TextView(this);
mContainer.addView(mTimeView);
mSetTime = new SeekBar(this);
mSetTime.setMax(120);
mContainer.addView(mSetTime);
if (mRemained > 0) {
mSetTime.setProgress(mRemained);
} else {
mSetTime.setProgress(30);
}
mSetTime.setOnSeekBarChangeListener(this);
mProgress = mSetTime.getProgress();
mTimerTime = mProgress;
if (mTimerTime >= 1) {
mPrompt = SleepTimerDialog.this.getResources().getQuantityString(R.plurals.NNNminutes,
mTimerTime, mTimerTime);
} else {
mPrompt = SleepTimerDialog.this.getResources().getString(R.string.disabled);
}
mTimeView.setText(mPrompt);
if (INTENT_SLEEP_TIMER.equals(action)) {
mSleepTimerDialog.setIcon(android.R.drawable.ic_dialog_info);
mSleepTimerDialog.setTitle(R.string.set_time);
mSleepTimerDialog.setView(mContainer);
mSleepTimerDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.ok),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mTimerTime >= 1) {
long milliseconds = mTimerTime * 60 * 1000;
boolean gentle = new PreferencesEditor(getApplicationContext())
.getBooleanPref(KEY_GENTLE_SLEEPTIMER, true);
mUtils.startSleepTimer(milliseconds, gentle);
} else {
mUtils.stopSleepTimer();
}
finish();
}
});
mSleepTimerDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
mSleepTimerDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onPause() {
if (mSleepTimerDialog != null && mSleepTimerDialog.isShowing()) {
mSleepTimerDialog.dismiss();
}
super.onPause();
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mTimerTime = progress;
if (progress >= 1) {
mPrompt = SleepTimerDialog.this.getResources().getQuantityString(R.plurals.NNNminutes,
mTimerTime, mTimerTime);
} else {
mPrompt = SleepTimerDialog.this.getResources().getString(R.string.disabled);
}
mTimeView.setText(mPrompt);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
protected void onResume() {
super.onResume();
if (mSleepTimerDialog != null && !mSleepTimerDialog.isShowing()) {
mSleepTimerDialog.show();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/SleepTimerDialog.java
|
Java
|
gpl3
| 5,140
|
package org.yammp.dialog;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockDialogFragment;
public class DeleteDialogFragment extends SherlockDialogFragment implements OnClickListener {
private long[] mItems = new long[] {};
private MediaUtils mUtils;
private static boolean mIsDeleteLyrics = false;
private static long mId;
private static int mType;
private static String mName;
private static String mMessage;
public final static int ARTIST = 1;
public final static int ALBUM = 2;
public final static int TRACK = 3;
@Override
public void onActivityCreated(Bundle saveInstanceState) {
super.onActivityCreated(saveInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
if (mIsDeleteLyrics) {
mUtils.deleteLyrics(mItems);
} else {
mUtils.deleteTracks(mItems);
}
break;
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
switch (mType) {
case ARTIST:
mItems = new long[] { mId };
mName = mUtils.getTrackName(mId);
mMessage = getString(mIsDeleteLyrics ? R.string.delete_song_lyrics
: R.string.delete_song_track, mName);
break;
case ALBUM:
mItems = mUtils.getSongListForAlbum(mId);
mName = mUtils.getAlbumName(mId, true);
mMessage = getString(mIsDeleteLyrics ? R.string.delete_album_lyrics
: R.string.delete_album_tracks, mName);
break;
case TRACK:
mItems = mUtils.getSongListForArtist(mId);
mName = mUtils.getArtistName(mId, true);
mMessage = getString(mIsDeleteLyrics ? R.string.delete_artist_lyrics
: R.string.delete_artist_tracks, mName);
break;
}
return new AlertDialog.Builder(getSherlockActivity()) {
{
setIcon(android.R.drawable.ic_dialog_alert);
setTitle(R.string.delete);
setMessage(mMessage);
setNegativeButton(android.R.string.cancel, DeleteDialogFragment.this);
setPositiveButton(android.R.string.ok, DeleteDialogFragment.this);
}
}.create();
}
public static DeleteDialogFragment getInstance(boolean is_delete_lyrics, long id, int type) {
mId = id;
mIsDeleteLyrics = is_delete_lyrics;
mType = type;
return new DeleteDialogFragment();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/DeleteDialogFragment.java
|
Java
|
gpl3
| 2,591
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.dialog;
import org.yammp.R;
import org.yammp.app.MediaPlayerActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
public class ScanningProgress extends FragmentActivity {
private DialogFragment mFragment;
private BroadcastReceiver mMountStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) {
startActivity(new Intent(getApplicationContext(), MediaPlayerActivity.class));
finish();
}
}
};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mFragment = new ScanningDialogFragment();
mFragment.show(getSupportFragmentManager(), "scanning_dialog");
}
@Override
public void onStart() {
super.onStart();
registerReceiver(mMountStateReceiver, new IntentFilter(Intent.ACTION_MEDIA_MOUNTED));
}
@Override
public void onStop() {
unregisterReceiver(mMountStateReceiver);
super.onStop();
}
public static class ScanningDialogFragment extends DialogFragment implements OnClickListener,
OnCancelListener {
@Override
public void onCancel(DialogInterface dialog) {
getActivity().finish();
}
@Override
public void onClick(DialogInterface dialog, int which) {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String mount_state = Environment.getExternalStorageState();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.media_storage_error_title);
if (Environment.MEDIA_MOUNTED.equals(mount_state)
|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(mount_state)) {
getActivity().finish();
} else if (Environment.MEDIA_CHECKING.equals(mount_state)) {
builder.setMessage(R.string.media_storage_error_checking);
} else if (Environment.MEDIA_BAD_REMOVAL.equals(mount_state)
|| Environment.MEDIA_REMOVED.equals(mount_state)) {
builder.setMessage(R.string.media_storage_error_removed);
} else if (Environment.MEDIA_NOFS.equals(mount_state)
|| Environment.MEDIA_UNMOUNTABLE.equals(mount_state)) {
builder.setMessage(R.string.media_storage_error_corrupted);
} else if (Environment.MEDIA_SHARED.equals(mount_state)) {
builder.setMessage(R.string.media_storage_error_shared);
} else if (Environment.MEDIA_UNMOUNTED.equals(mount_state)) {
builder.setMessage(R.string.media_storage_error_unmounted);
} else {
builder.setMessage(R.string.media_storage_error_unknown);
}
return builder.create();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/ScanningProgress.java
|
Java
|
gpl3
| 3,784
|
package org.yammp.dialog;
import org.yammp.view.VerticalTextSpinner;
import android.app.AlertDialog;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.widget.LinearLayout;
public class VerticalTextSpinnerDialog extends AlertDialog {
private VerticalTextSpinner mVerticalTextSpinner;
public VerticalTextSpinnerDialog(Context context, String[] items, int position) {
super(context);
init(context, items, position);
}
public int getCurrentSelectedPos() {
if (mVerticalTextSpinner != null) return mVerticalTextSpinner.getCurrentSelectedPos();
return 0;
}
private void init(Context context, String[] items, int position) {
DisplayMetrics dm = new DisplayMetrics();
dm = context.getResources().getDisplayMetrics();
LinearLayout mContainer = new LinearLayout(context);
mContainer.setGravity(Gravity.CENTER);
mVerticalTextSpinner = new VerticalTextSpinner(context);
mVerticalTextSpinner.setItems(items);
mVerticalTextSpinner.setWrapAround(true);
mVerticalTextSpinner.setScrollInterval(200);
mVerticalTextSpinner.setSelectedPos(position);
mContainer
.addView(mVerticalTextSpinner, (int) (120 * dm.density), (int) (100 * dm.density));
setView(mContainer);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/VerticalTextSpinnerDialog.java
|
Java
|
gpl3
| 1,264
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.dialog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.ImageDownloader;
import org.yammp.util.LyricsDownloader;
import org.yammp.util.MediaUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class SearchDialog extends Activity implements Constants, TextWatcher, OnCancelListener {
private ProgressDialog mProgress = null;
private LinearLayout mLinearLayout;
private AlertDialog mSearchDialog, mLyricsChooser, mLyricsConfirm, mAlbumArtConfirm;
private ProgressDialog mSearchProgress, mDownloadProgress;
private boolean restore_lyrics_chooser, restore_lyrics_confirm,
restore_albumart_confirm = false;
LyricsDownloader mDownloader;
LyricsSearchTask mLyricsSearchTask;
LyricsDownloadTask mLyricsDownloadTask;
AlbumArtSearchTask mAlbumArtSearchTask;
AlbumArtDownloadTask mAlbumArtDownloadTask;
private String action;
private LinearLayout mContainer;
private TextView mKeywordSummary1, mKeywordSummary2;
private EditText mSearchKeyword1, mSearchKeyword2;
private String mKeyword1, mKeyword2 = "";
private String mPath = null;
private View.OnClickListener mSearchLyricsOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
String mTypedKeyword1 = mSearchKeyword1.getText().toString();
String mTypedKeyword2 = mSearchKeyword2.getText().toString();
mLyricsSearchTask = new LyricsSearchTask();
mLyricsSearchTask.execute(mTypedKeyword1, mTypedKeyword2, mPath);
}
};
private View.OnClickListener mSearchAlbumArtOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
String mTypedKeyword1 = mSearchKeyword1.getText().toString();
String mTypedKeyword2 = mSearchKeyword2.getText().toString();
mAlbumArtSearchTask = new AlbumArtSearchTask();
mAlbumArtSearchTask.execute(mTypedKeyword1, mTypedKeyword2, mPath);
}
};
private MediaUtils mUtils;
@Override
public void afterTextChanged(Editable s) {
// don't care about this one
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// don't care about this one
}
@Override
public void onCancel(DialogInterface dialog) {
if (dialog == mSearchDialog) {
finish();
}
if (dialog == mSearchProgress) {
if (mLyricsSearchTask != null) {
mLyricsSearchTask.cancel(true);
}
if (mAlbumArtSearchTask != null) {
mAlbumArtSearchTask.cancel(true);
}
}
if (dialog == mDownloadProgress) {
if (mLyricsDownloadTask != null) {
mLyricsDownloadTask.cancel(true);
}
if (mAlbumArtDownloadTask != null) {
mAlbumArtDownloadTask.cancel(true);
}
}
return;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
mLinearLayout = new LinearLayout(this);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(mLinearLayout);
action = getIntent().getAction();
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
mSearchDialog = new AlertDialog.Builder(this).create();
mSearchDialog.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (INTENT_SEARCH_ALBUMART.equals(action) || INTENT_SEARCH_LYRICS.equals(action)) {
mPath = icicle != null ? icicle.getString(INTENT_KEY_PATH) : getIntent()
.getStringExtra(INTENT_KEY_PATH);
mContainer = new LinearLayout(this);
mContainer.setOrientation(LinearLayout.VERTICAL);
mKeywordSummary1 = new TextView(this);
mKeywordSummary1.setTextAppearance(this, android.R.attr.textAppearanceSmall);
mKeywordSummary1.setText(R.string.artist);
mContainer.addView(mKeywordSummary1);
mKeyword1 = icicle != null ? icicle.getString(INTENT_KEY_ARTIST) : getIntent()
.getStringExtra(INTENT_KEY_ARTIST);
mSearchKeyword1 = new EditText(this);
mSearchKeyword1.setSingleLine(true);
mSearchKeyword1.addTextChangedListener(this);
mContainer.addView(mSearchKeyword1);
mKeywordSummary2 = new TextView(this);
mKeywordSummary2.setTextAppearance(this, android.R.attr.textAppearanceSmall);
if (INTENT_SEARCH_ALBUMART.equals(action)) {
mKeyword2 = icicle != null ? icicle.getString(INTENT_KEY_ALBUM) : getIntent()
.getStringExtra(INTENT_KEY_ALBUM);
mKeywordSummary2.setText(R.string.album);
} else if (INTENT_SEARCH_LYRICS.equals(action)) {
mKeyword2 = icicle != null ? icicle.getString(INTENT_KEY_TRACK) : getIntent()
.getStringExtra(INTENT_KEY_TRACK);
mKeywordSummary2.setText(R.string.track);
}
mContainer.addView(mKeywordSummary2);
mSearchKeyword2 = new EditText(this);
mSearchKeyword2.setSingleLine(true);
mSearchKeyword2.addTextChangedListener(this);
mContainer.addView(mSearchKeyword2);
mSearchDialog.setIcon(android.R.drawable.ic_dialog_info);
if (INTENT_SEARCH_ALBUMART.equals(action)) {
mSearchDialog.setTitle(R.string.search_albumart);
} else if (INTENT_SEARCH_LYRICS.equals(action)) {
mSearchDialog.setTitle(R.string.search_lyrics);
}
mSearchDialog.setView(mContainer, (int) (8 * dm.density), (int) (4 * dm.density),
(int) (8 * dm.density), (int) (4 * dm.density));
mSearchDialog.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.search_go),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing here. We override the onClick
}
});
mSearchDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
mSearchDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button mButton = mSearchDialog.getButton(AlertDialog.BUTTON_POSITIVE);
if (INTENT_SEARCH_ALBUMART.equals(action)) {
mButton.setOnClickListener(mSearchAlbumArtOnClickListener);
} else if (INTENT_SEARCH_LYRICS.equals(action)) {
mButton.setOnClickListener(mSearchLyricsOnClickListener);
}
}
});
mSearchDialog.setOnCancelListener(this);
mProgress = new ProgressDialog(this);
mProgress.setCancelable(true);
mProgress.setOnCancelListener(this);
mSearchDialog.show();
mSearchKeyword1.setText(mKeyword1);
mSearchKeyword2.setText(mKeyword2);
setSaveButton();
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onPause() {
if (mSearchDialog != null && mSearchDialog.isShowing()) {
mSearchDialog.dismiss();
}
if (mLyricsChooser != null && mLyricsChooser.isShowing()) {
restore_lyrics_chooser = true;
mLyricsChooser.dismiss();
}
if (mLyricsConfirm != null && mLyricsConfirm.isShowing()) {
restore_lyrics_confirm = true;
mLyricsConfirm.dismiss();
}
if (mAlbumArtConfirm != null && mAlbumArtConfirm.isShowing()) {
restore_albumart_confirm = true;
mAlbumArtConfirm.dismiss();
}
if ((mLyricsSearchTask != null || mAlbumArtSearchTask != null
|| mLyricsDownloadTask != null || mAlbumArtDownloadTask != null)
&& mProgress.isShowing()) {
mProgress.dismiss();
}
super.onPause();
};
@Override
public void onSaveInstanceState(Bundle outcicle) {
if (INTENT_SEARCH_ALBUMART.equals(action)) {
outcicle.putString(INTENT_KEY_ALBUM, mSearchKeyword2.getText().toString());
} else if (INTENT_SEARCH_LYRICS.equals(action)) {
outcicle.putString(INTENT_KEY_TRACK, mSearchKeyword2.getText().toString());
}
outcicle.putString(INTENT_KEY_PATH, mPath);
outcicle.putString(INTENT_KEY_ARTIST, mSearchKeyword1.getText().toString());
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setSaveButton();
}
private void setSaveButton() {
String mTypedKeyword1 = mSearchKeyword1.getText().toString();
String mTypedKeyword2 = mSearchKeyword2.getText().toString();
Button button = mSearchDialog.getButton(Dialog.BUTTON_POSITIVE);
if (mTypedKeyword1.trim().length() == 0 || mTypedKeyword2.trim().length() == 0) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
button.invalidate();
}
@Override
protected void onResume() {
super.onResume();
if (mSearchDialog != null && !mSearchDialog.isShowing()) {
mSearchDialog.show();
}
if (mLyricsChooser != null && restore_lyrics_chooser) {
mLyricsChooser.show();
}
if (mLyricsConfirm != null && restore_lyrics_confirm) {
mLyricsConfirm.show();
}
if (mAlbumArtConfirm != null && restore_albumart_confirm) {
mAlbumArtConfirm.show();
}
if (mLyricsSearchTask != null && mLyricsSearchTask.getStatus().equals(Status.RUNNING)
|| mAlbumArtSearchTask != null
&& !mAlbumArtSearchTask.getStatus().equals(Status.RUNNING)) {
mProgress.setMessage(getString(R.string.searching_please_wait));
mProgress.show();
}
if (mLyricsDownloadTask != null && mLyricsDownloadTask.getStatus().equals(Status.RUNNING)
|| mAlbumArtDownloadTask != null
&& !mAlbumArtDownloadTask.getStatus().equals(Status.RUNNING)) {
mProgress.setMessage(getString(R.string.downloading_please_wait));
mProgress.show();
}
}
private class AlbumArtDownloadTask extends AsyncTask<String, Void, Bitmap> {
String albumArtPath;
private void writeAlbumArt(Bitmap bitmap, String path) {
try {
FileOutputStream fos = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected Bitmap doInBackground(String... params) {
albumArtPath = params[1];
return ImageDownloader.getCoverBitmap(params[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
File art = new File(albumArtPath);
art.delete();
writeAlbumArt(result, albumArtPath);
if (mProgress != null) {
mProgress.dismiss();
}
if (mSearchDialog != null && mSearchDialog.isShowing()) {
mSearchDialog.dismiss();
}
finish();
}
@Override
protected void onPreExecute() {
mProgress.setMessage(getString(R.string.downloading_please_wait));
mProgress.show();
}
}
private class AlbumArtSearchTask extends AsyncTask<String, Void, String> implements
OnClickListener {
String mUrl, mPath;
@Override
public void onClick(DialogInterface dialog, int which) {
restore_albumart_confirm = false;
if (dialog == mAlbumArtConfirm) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
mAlbumArtDownloadTask = new AlbumArtDownloadTask();
mAlbumArtDownloadTask.execute(mUrl, mPath);
}
}
}
private void confirmOverwrite(final String url, final String path) {
mUrl = url;
mPath = path;
if (new File(path).exists()) {
mAlbumArtConfirm = new AlertDialog.Builder(SearchDialog.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.confirm_overwrite)
.setMessage(getString(R.string.albumart_already_exist))
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, this).show();
} else {
mAlbumArtDownloadTask = new AlbumArtDownloadTask();
mAlbumArtDownloadTask.execute(url, path);
}
}
@Override
protected String doInBackground(String... params) {
mPath = params[2];
try {
return ImageDownloader.getCoverUrl(params[0], params[1]);
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(String result) {
if (mProgress != null) {
mProgress.dismiss();
}
if (result != null) {
confirmOverwrite(result, mPath);
} else {
Toast.makeText(SearchDialog.this, R.string.search_noresult, Toast.LENGTH_SHORT)
.show();
}
}
@Override
protected void onPreExecute() {
mProgress.setMessage(getString(R.string.searching_please_wait));
mProgress.show();
}
}
private class LyricsDownloadTask extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String... params) {
// try {
// mDownloader.download(Integer.valueOf(params[0]), params[1]);
// } catch (NumberFormatException e) {
// e.printStackTrace();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
return null;
}
@Override
protected void onPostExecute(Void result) {
if (mProgress != null) {
mProgress.dismiss();
}
if (mSearchDialog != null && mSearchDialog.isShowing()) {
mSearchDialog.dismiss();
}
mUtils.reloadLyrics();
finish();
}
@Override
protected void onPreExecute() {
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setMessage(getString(R.string.downloading_please_wait));
mProgress.show();
}
}
private class LyricsSearchTask extends AsyncTask<String, Void, String[]> implements
OnCancelListener, OnClickListener {
private int mItem = 0;
@Override
public void onCancel(DialogInterface dialog) {
if (dialog == mLyricsChooser) {
restore_lyrics_chooser = false;
}
if (dialog == mLyricsConfirm) {
restore_lyrics_confirm = false;
}
}
@Override
public void onClick(DialogInterface dialog, int item) {
if (dialog == mLyricsChooser) {
restore_lyrics_chooser = false;
confirmOverwrite(item, mPath);
}
if (dialog == mLyricsConfirm) {
restore_lyrics_confirm = false;
switch (item) {
case DialogInterface.BUTTON_POSITIVE:
mLyricsDownloadTask = new LyricsDownloadTask();
mLyricsDownloadTask.execute(String.valueOf(mItem), mPath);
break;
}
}
}
private void chooseLyrics(final String[] result) {
mLyricsChooser = new AlertDialog.Builder(SearchDialog.this)
.setTitle(R.string.search_lyrics).setItems(result, this)
.setOnCancelListener(this).show();
}
private void confirmOverwrite(int item, String path) {
mItem = item;
if (new File(mPath).exists()) {
mLyricsConfirm = new AlertDialog.Builder(SearchDialog.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.confirm_overwrite)
.setMessage(getString(R.string.lyrics_already_exist))
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, this).setOnCancelListener(this)
.show();
} else {
mLyricsDownloadTask = new LyricsDownloadTask();
mLyricsDownloadTask.execute(String.valueOf(item), mPath);
}
}
@Override
protected String[] doInBackground(String... params) {
mPath = params[2];
// try {
// return mDownloader.search(params[0], params[1]);
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// } catch (XmlPullParserException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
return null;
}
@Override
protected void onPostExecute(String[] result) {
if (mProgress != null) {
mProgress.dismiss();
}
if (result.length > 0) {
chooseLyrics(result);
} else {
Toast.makeText(SearchDialog.this, R.string.search_noresult, Toast.LENGTH_SHORT)
.show();
}
}
@Override
protected void onPreExecute() {
mDownloader = new LyricsDownloader();
mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgress.setMessage(getString(R.string.searching_please_wait));
mProgress.show();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/SearchDialog.java
|
Java
|
gpl3
| 17,104
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.dialog;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.util.PreferencesEditor;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.widget.LinearLayout;
import android.widget.Toast;
public class WeekSelector extends FragmentActivity implements Constants {
private String action;
private static VerticalTextSpinnerDialog mAlert;
private static PreferencesEditor mPrefs;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new LinearLayout(this));
mPrefs = new PreferencesEditor(this);
int def = mPrefs.getIntPref(PREF_KEY_NUMWEEKS, 2);
int pos = savedInstanceState != null ? savedInstanceState.getInt(PREF_KEY_NUMWEEKS, def)
: def;
mAlert = new VerticalTextSpinnerDialog(this, getResources()
.getStringArray(R.array.weeklist), pos - 1);
action = getIntent().getAction();
if (INTENT_WEEK_SELECTOR.equals(action)) {
new WeekSelectorDialogFragment().show(getSupportFragmentManager(), "dialog");
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt(PREF_KEY_NUMWEEKS, mAlert.getCurrentSelectedPos() + 1);
super.onSaveInstanceState(savedInstanceState);
}
public static class WeekSelectorDialogFragment extends DialogFragment implements
OnClickListener, OnCancelListener {
@Override
public void onCancel(DialogInterface dialog) {
getActivity().finish();
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
int numweeks = mAlert.getCurrentSelectedPos() + 1;
mPrefs.setIntPref(PREF_KEY_NUMWEEKS, numweeks);
getActivity().setResult(RESULT_OK);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
getActivity().finish();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mAlert.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mAlert.setIcon(android.R.drawable.ic_dialog_info);
mAlert.setTitle(R.string.set_time);
mAlert.setButton(Dialog.BUTTON_POSITIVE, getString(android.R.string.ok), this);
mAlert.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
mAlert.setOnCancelListener(this);
return mAlert;
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/WeekSelector.java
|
Java
|
gpl3
| 3,347
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.dialog;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlaylistDialog extends FragmentActivity implements Constants, TextWatcher,
OnCancelListener, OnShowListener {
private AlertDialog mPlaylistDialog;
private String action;
private EditText mPlaylist;
private String mDefaultName, mOriginalName;
private long mRenameId;
private long[] mList = new long[] {};
private OnClickListener mRenamePlaylistListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mPlaylist.getText().toString();
mUtils.renamePlaylist(mRenameId, name);
finish();
}
};
private OnClickListener mCreatePlaylistListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = mPlaylist.getText().toString();
if (name != null && name.length() > 0) {
int id = idForplaylist(name);
if (id >= 0) {
mUtils.clearPlaylist(id);
mUtils.addToPlaylist(mList, id);
} else {
long new_id = mUtils.createPlaylist(name);
if (new_id >= 0) {
mUtils.addToPlaylist(mList, new_id);
}
}
finish();
}
}
};
private MediaUtils mUtils;
@Override
public void afterTextChanged(Editable s) {
// don't care about this one
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// don't care about this one
}
@Override
public void onCancel(DialogInterface dialog) {
if (dialog == mPlaylistDialog) {
finish();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mUtils = ((YAMMPApplication) getApplication()).getMediaUtils();
setContentView(new LinearLayout(this));
action = getIntent().getAction();
mRenameId = icicle != null ? icicle.getLong(INTENT_KEY_RENAME) : getIntent().getLongExtra(
INTENT_KEY_RENAME, -1);
mList = icicle != null ? icicle.getLongArray(INTENT_KEY_LIST) : getIntent()
.getLongArrayExtra(INTENT_KEY_LIST);
if (INTENT_RENAME_PLAYLIST.equals(action)) {
mOriginalName = nameForId(mRenameId);
mDefaultName = icicle != null ? icicle.getString(INTENT_KEY_DEFAULT_NAME)
: mOriginalName;
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
mDefaultName = icicle != null ? icicle.getString(INTENT_KEY_DEFAULT_NAME)
: makePlaylistName();
mOriginalName = mDefaultName;
}
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
mPlaylistDialog = new AlertDialog.Builder(this).create();
mPlaylistDialog.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (action != null && mRenameId >= 0 && mOriginalName != null || mDefaultName != null) {
mPlaylist = new EditText(this);
mPlaylist.setSingleLine(true);
mPlaylist.setText(mDefaultName);
mPlaylist.setSelection(mDefaultName.length());
mPlaylist.addTextChangedListener(this);
mPlaylistDialog.setIcon(android.R.drawable.ic_dialog_info);
String promptformat;
String prompt = "";
if (INTENT_RENAME_PLAYLIST.equals(action)) {
promptformat = getString(R.string.rename_playlist_prompt);
prompt = String.format(promptformat, mOriginalName, mDefaultName);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
promptformat = getString(R.string.create_playlist_prompt);
prompt = String.format(promptformat, mDefaultName);
}
mPlaylistDialog.setTitle(prompt);
mPlaylistDialog.setView(mPlaylist, (int) (8 * dm.density), (int) (8 * dm.density),
(int) (8 * dm.density), (int) (4 * dm.density));
if (INTENT_RENAME_PLAYLIST.equals(action)) {
mPlaylistDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.save),
mRenamePlaylistListener);
mPlaylistDialog.setOnShowListener(this);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
mPlaylistDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.save),
mCreatePlaylistListener);
}
mPlaylistDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
mPlaylistDialog.setOnCancelListener(this);
mPlaylistDialog.show();
} else {
Toast.makeText(this, R.string.error_bad_parameters, Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onPause() {
if (mPlaylistDialog != null && mPlaylistDialog.isShowing()) {
mPlaylistDialog.dismiss();
}
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outcicle) {
if (INTENT_RENAME_PLAYLIST.equals(action)) {
outcicle.putString(INTENT_KEY_DEFAULT_NAME, mPlaylist.getText().toString());
outcicle.putLong(INTENT_KEY_RENAME, mRenameId);
} else if (INTENT_CREATE_PLAYLIST.equals(action)) {
outcicle.putString(INTENT_KEY_DEFAULT_NAME, mPlaylist.getText().toString());
}
}
@Override
public void onShow(DialogInterface dialog) {
if (dialog == mPlaylistDialog) {
setSaveButton();
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setSaveButton();
}
private int idForplaylist(String name) {
Cursor cursor = mUtils.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists._ID }, MediaStore.Audio.Playlists.NAME
+ "=?", new String[] { name }, MediaStore.Audio.Playlists.NAME);
int id = -1;
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
id = cursor.getInt(0);
}
cursor.close();
}
return id;
}
private String makePlaylistName() {
String template = getString(R.string.new_playlist_name_template);
int num = 1;
String[] cols = new String[] { MediaStore.Audio.Playlists.NAME };
ContentResolver resolver = getContentResolver();
String whereclause = MediaStore.Audio.Playlists.NAME + " != ''";
Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cols,
whereclause, null, MediaStore.Audio.Playlists.NAME);
if (cursor == null) return null;
String suggestedname;
suggestedname = String.format(template, num++);
// Need to loop until we've made 1 full pass through without finding a
// match. Looping more than once shouldn't happen very often, but will
// happen if you have playlists named
// "New Playlist 1"/10/2/3/4/5/6/7/8/9, where making only one pass would
// result in "New Playlist 10" being erroneously picked for the new
// name.
boolean done = false;
while (!done) {
done = true;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String playlistname = cursor.getString(0);
if (playlistname.compareToIgnoreCase(suggestedname) == 0) {
suggestedname = String.format(template, num++);
done = false;
}
cursor.moveToNext();
}
}
cursor.close();
return suggestedname;
};
private String nameForId(long id) {
Cursor cursor = mUtils.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Playlists.NAME }, MediaStore.Audio.Playlists._ID
+ "=?", new String[] { Long.valueOf(id).toString() },
MediaStore.Audio.Playlists.NAME);
String name = null;
if (cursor != null) {
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
name = cursor.getString(0);
}
cursor.close();
}
return name;
}
private void setSaveButton() {
String typedname = mPlaylist.getText().toString();
Button button = mPlaylistDialog.getButton(Dialog.BUTTON_POSITIVE);
if (button == null) return;
if (typedname.trim().length() == 0 || PLAYLIST_NAME_FAVORITES.equals(typedname)) {
button.setEnabled(false);
} else {
button.setEnabled(true);
if (idForplaylist(typedname) >= 0 && !mOriginalName.equals(typedname)) {
button.setText(R.string.overwrite);
} else {
button.setText(R.string.save);
}
}
button.invalidate();
}
@Override
protected void onResume() {
super.onResume();
if (mPlaylistDialog != null) {
mPlaylistDialog.show();
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/dialog/PlaylistDialog.java
|
Java
|
gpl3
| 9,445
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp;
public interface Constants {
public final static int ACTION_NOW = 1;
public final static int ACTION_NEXT = 2;
public final static int ACTION_LAST = 3;
public final static int ID_NOTIFICATION_PLAYBACK = 1;
public final static int ID_NOTIFICATION_SLEEPTIMER = 2;
public final static int SHUFFLE_NONE = 0;
public final static int SHUFFLE_NORMAL = 1;
public final static int REPEAT_NONE = 0;
public final static int REPEAT_CURRENT = 1;
public final static int REPEAT_ALL = 2;
public final static int PAGE_ARTIST = 0;
public final static int PAGE_ALBUM = 1;
public final static int PAGE_TRACK = 2;
public final static int PAGE_PLAYLIST = 3;
public final static long PLAYLIST_UNKNOWN = -1;
public final static long PLAYLIST_ALL_SONGS = -2;
public final static long PLAYLIST_QUEUE = -3;
public final static long PLAYLIST_NEW = -4;
public final static long PLAYLIST_FAVORITES = -5;
public final static long PLAYLIST_RECENTLY_ADDED = -6;
public final static long PLAYLIST_PODCASTS = -7;
public static final String INTERNAL_VOLUME = "internal";
public static final String EXTERNAL_VOLUME = "external";
public final static String PLAYLIST_NAME_FAVORITES = "YAMMP Favorites";
public final static String TYPE_ARTIST_ALBUM = "artist_album";
public final static String TYPE_ALBUM = "album";
public final static String TYPE_TRACK = "track";
public final static String LOGTAG_SERVICE = "YAMMP.Service";
public final static String LOGTAG_TEST = "YAMMP.Test";
public final static String LOGTAG_MUSICUTILS = "YAMMP.MusicUtils";
public final static String LOGTAG_WIDGET_4x1 = "MusicAppWidgetProvider4x1";
public final static String LOGTAG_WIDGET_2x2 = "MusicAppWidgetProvider2x2";
public final static String SCROBBLE_SLS_API = "com.adam.aslfms.notify.playstatechanged";
public final static int SCROBBLE_PLAYSTATE_START = 0;
public final static int SCROBBLE_PLAYSTATE_RESUME = 1;
public final static int SCROBBLE_PLAYSTATE_PAUSE = 2;
public final static int SCROBBLE_PLAYSTATE_COMPLETE = 3;
public final static int VISUALIZER_TYPE_WAVE_FORM = 1;
public final static int VISUALIZER_TYPE_FFT_SPECTRUM = 2;
public final static int LYRICS_STATUS_OK = 0;
public final static int LYRICS_STATUS_NOT_FOUND = 1;
public final static int LYRICS_STATUS_INVALID = 2;
public final static String PLUGINS_PNAME_PATTERN = "org.yammp.plugin";
public final static String THEMES_PNAME_PATTERN = "org.yammp.theme";
public final static String SERVICECMD = "org.yammp.musicservicecommand";
public final static String CMDNAME = "command";
public final static String CMDTOGGLEPAUSE = "togglepause";
public final static String CMDSTOP = "stop";
public final static String CMDPAUSE = "pause";
public final static String CMDPREVIOUS = "previous";
public final static String CMDNEXT = "next";
public static final String CMDCYCLEREPEAT = "cyclerepeat";
public static final String CMDTOGGLESHUFFLE = "toggleshuffle";
public final static String CMDREFRESHLYRICS = "refreshlyrics";
public final static String CMDRESENDALLLYRICS = "resendalllyrics";
public final static String CMDREFRESHMETADATA = "refreshmetadata";
public final static String CMDTOGGLEFAVORITE = "togglefavorite";
public final static String CMDMUSICWIDGETUPDATE_4x1 = "musicwidgetupdate4x1";
public final static String CMDMUSICWIDGETUPDATE_2x2 = "musicwidgetupdate2x2";
public final static String TOGGLEPAUSE_ACTION = "org.yammp.musicservicecommand.togglepause";
public final static String PAUSE_ACTION = "org.yammp.musicservicecommand.pause";
public final static String PREVIOUS_ACTION = "org.yammp.musicservicecommand.previous";
public final static String NEXT_ACTION = "org.yammp.musicservicecommand.next";
public static final String CYCLEREPEAT_ACTION = "org.yammp.musicservicecommand.cyclerepeat";
public static final String TOGGLESHUFFLE_ACTION = "org.yammp.musicservicecommand.toggleshuffle";
public final static String TESTCMD_MUSICPLAYBACKACTIVITY = "org.yammp.test.musicplaybackactivity";
public final static String SHAREDPREFS_PREFERENCES = "preferences";
public final static String SHAREDPREFS_EQUALIZER = "equalizer";
public final static String SHAREDPREFS_STATES = "states";
public final static String MEDIASTORE_EXTERNAL_AUDIO_ALBUMART_URI = "content:media/external/audio/albumart";
public final static String MEDIASTORE_EXTERNAL_AUDIO_MEDIA_URI = "content:media/external/audio/media/";
public final static String MEDIASTORE_EXTERNAL_AUDIO_ALBUMS_URI = "content:media/external/audio/albums/";
public final static String MEDIASTORE_EXTERNAL_AUDIO_ARTISTS_URI = "content:media/external/audio/artists/";
public final static String MEDIASTORE_EXTERNAL_AUDIO_SEARCH_FANCY_URI = "content:media/external/audio/search/fancy/";
public final static String LASTFM_APIKEY = "e682ad43038e19de1e33f583b191f5b2";
public final static String BEHAVIOR_NEXT_SONG = "next_song";
public final static String BEHAVIOR_PLAY_PAUSE = "play_pause";
public final static String DEFAULT_SHAKING_BEHAVIOR = BEHAVIOR_NEXT_SONG;
public final static String LYRICS_CHARSET = "auto";
public final static long LYRICS_REFRESH_RATE = 200;
public final static long LYRICS_TIMER_DELAY = 50;
public final static boolean DEFAULT_LYRICS_WAKELOCK = false;
public final static boolean DEFAULT_SPLIT_LYRICS = true;
public final static boolean DEFAULT_SKIP_BLANK = true;
public final static boolean DEFAULT_DISPLAY_LYRICS = true;
public final static boolean DEFAULT_DISPLAY_VISUALIZER = true;
public final static int DEFAULT_VISUALIZER_TYPE = VISUALIZER_TYPE_WAVE_FORM;
public final static int DEFAULT_VISUALIZER_REFRESHRATE = 1;
public final static int DEFAULT_VISUALIZER_ACCURACY = 1;
public final static boolean DEFAULT_VISUALIZER_ANTIALIAS = true;
public final static String STATE_KEY_CURRENTTAB = "currenttab";
public final static String STATE_KEY_CURRPOS = "curpos";
public final static String STATE_KEY_CARDID = "cardid";
public final static String STATE_KEY_QUEUE = "queue";
public final static String STATE_KEY_HISTORY = "history";
public final static String STATE_KEY_SEEKPOS = "seekpos";
public final static String STATE_KEY_REPEATMODE = "repeatmode";
public final static String STATE_KEY_SHUFFLEMODE = "shufflemode";
public final static String PREF_KEY_NUMWEEKS = "numweeks";
public final static String KEY_RESCAN_MEDIA = "rescan_media";
public final static String KEY_LYRICS_WAKELOCK = "lyrics_wakelock";
public final static String KEY_ALBUMART_SIZE = "albumart_size";
public final static String KEY_DISPLAY_LYRICS = "display_lyrics";
public final static String KEY_PLUGINS_MANAGER = "plugins_manager";
public final static String KEY_ENABLE_SCROBBLING = "enable_scrobbling";
public final static String KEY_GENTLE_SLEEPTIMER = "gentle_sleeptimer";
public final static String KEY_DISPLAY_VISUALIZER = "display_visualizer";
public final static String KEY_VISUALIZER_TYPE = "visualizer_type";
public final static String KEY_VISUALIZER_REFRESHRATE = "visualizer_refreshrate";
public final static String KEY_VISUALIZER_ACCURACY = "visualizer_accuracy";
public final static String KEY_VISUALIZER_ANTIALIAS = "visualizer_antialias";
public final static String KEY_UI_COLOR = "ui_color";
public final static String KEY_AUTO_COLOR = "auto_color";
public final static String KEY_CUSTOMIZED_COLOR = "customized_color";
public final static String KEY_EQUALIZER_ENABLED = "equalizer_enabled";
public final static String KEY_EQUALIZER_SETTINGS = "equalizer_settings";
public final static String KEY_SHAKE_ENABLED = "shake_enabled";
public final static String KEY_SHAKING_THRESHOLD = "shaking_threshold";
public final static String KEY_SHAKING_BEHAVIOR = "shaking_behavior";
public final static String KEY_BLUR_BACKGROUND = "blur_background";
public final static String KEY_LAST_NOWPLAYING = "last_nowplaying";
public final static float DEFAULT_SHAKING_THRESHOLD = 5000f;
public final static int RESULT_DELETE_MUSIC = 1;
public final static int RESULT_DELETE_ART = 2;
public final static int RESULT_DELETE_LYRICS = 3;
public final static String BROADCAST_KEY_ID = "id";
public final static String BROADCAST_KEY_ARTIST = "artist";
public final static String BROADCAST_KEY_ALBUM = "album";
public final static String BROADCAST_KEY_TRACK = "track";
public final static String BROADCAST_KEY_PLAYING = "playing";
public final static String BROADCAST_KEY_ISFAVORITE = "isfavorite";
public final static String BROADCAST_KEY_SONGID = "songid";
public final static String BROADCAST_KEY_ALBUMID = "albumid";
public final static String BROADCAST_KEY_POSITION = "position";
public final static String BROADCAST_KEY_REPEATMODE = "repeatmode";
public final static String BROADCAST_KEY_SHUFFLEMODE = "shufflemode";
public final static String BROADCAST_KEY_DURATION = "duration";
public final static String BROADCAST_KEY_LISTSIZE = "listsize";
public final static String BROADCAST_KEY_STATE = "state";
public final static String BROADCAST_KEY_APP_NAME = "app-name";
public final static String BROADCAST_KEY_APP_PACKAGE = "app-package";
public final static String BROADCAST_KEY_LYRICS_STATUS = "lyrics_status";
public final static String BROADCAST_KEY_LYRICS_ID = "lyrics_id";
public final static String BROADCAST_KEY_LYRICS = "lyrics";
public final static String INTENT_KEY_CONTENT = "content";
public final static String INTENT_KEY_ITEMS = "items";
public final static String INTENT_KEY_ALBUM = "album";
public final static String INTENT_KEY_ARTIST = "artist";
public final static String INTENT_KEY_TRACK = "track";
public final static String INTENT_KEY_PLAYLIST = "playlist";
public final static String INTENT_KEY_PATH = "path";
public final static String INTENT_KEY_LIST = "list";
public final static String INTENT_KEY_RENAME = "rename";
public final static String INTENT_KEY_DEFAULT_NAME = "default_name";
public final static String INTENT_KEY_FILTER = "filter";
public final static String INTENT_KEY_TYPE = "type";
public final static String INTENT_KEY_ACTION = "action";
public final static String INTENT_KEY_DATA = "data";
public final static String MAP_KEY_NAME = "name";
public final static String MAP_KEY_ID = "id";
public final static String INTENT_SEARCH_LYRICS = "org.yammp.SEARCH_LYRICS";
public final static String INTENT_SEARCH_ALBUMART = "org.yammp.SEARCH_ALBUMART";
public final static String INTENT_DELETE_ITEMS = "org.yammp.DELETE_ITEMS";
public final static String INTENT_CONFIGURE_PLUGIN = "org.yammp.CONFIGURE_PLUGIN";
public final static String INTENT_OPEN_PLUGIN = "org.yammp.OPEN_PLUGIN";
public final static String INTENT_CONFIGURE_THEME = "org.yammp.CONFIGURE_THEME";
public final static String INTENT_PREVIEW_THEME = "org.yammp.PREVIEW_THEME";
public final static String INTENT_APPEARANCE_SETTINGS = "org.yammp.APPEARANCE_SETTINGS";
public final static String INTENT_MUSIC_SETTINGS = "org.yammp.MUSIC_SETTINGS";
public final static String INTENT_PLAYBACK_VIEWER = "org.yammp.PLAYBACK_VIEWER";
public final static String INTENT_MUSIC_BROWSER = "org.yammp.MUSIC_BROWSER";
public final static String INTENT_STREAM_PLAYER = "org.yammp.STREAM_PLAYER";
public final static String INTENT_ADD_TO_PLAYLIST = "org.yammp.ADD_TO_PLAYLIST";
public final static String INTENT_CREATE_PLAYLIST = "org.yammp.CREATE_PLAYLIST";
public final static String INTENT_RENAME_PLAYLIST = "org.yammp.RENAME_PLAYLIST";
public final static String INTENT_WEEK_SELECTOR = "org.yammp.WEEK_SELECTOR";
public final static String INTENT_SLEEP_TIMER = "org.yammp.SLEEP_TIMER";
public final static String INTENT_EQUALIZER = "org.yammp.EQUALIZER";
public final static String INTENT_PLAY_SHORTCUT = "org.yammp.PLAY_SHORTCUT";
public final static String INTENT_PLUGINS_MANAGER = "org.yammp.PLUGINS_MANAGER";
public final static String INTENT_PLAYBACK_SERVICE = "org.yammp.PLAYBACK_SERVICE";
public final static String BROADCAST_PLAYSTATE_CHANGED = "org.yammp.playstatechanged";
public final static String BROADCAST_META_CHANGED = "org.yammp.metachanged";
public final static String BROADCAST_FAVORITESTATE_CHANGED = "org.yammp.favoritestatechanged";
public final static String BROADCAST_NEW_LYRICS_LOADED = "org.yammp.newlyricsloaded";
public final static String BROADCAST_LYRICS_REFRESHED = "org.yammp.lyricsrefreshed";
public final static String BROADCAST_QUEUE_CHANGED = "org.yammp.queuechanged";
public final static String BROADCAST_REPEATMODE_CHANGED = "org.yammp.repeatmodechanged";
public final static String BROADCAST_SHUFFLEMODE_CHANGED = "org.yammp.shufflemodechanged";
public final static String BROADCAST_PLAYBACK_COMPLETE = "org.yammp.playbackcomplete";
public final static String BROADCAST_ASYNC_OPEN_COMPLETE = "org.yammp.asyncopencomplete";
public final static String BROADCAST_REFRESH_PROGRESSBAR = "org.yammp.refreshprogress";
public final static String BROADCAST_PLAYSTATUS_REQUEST = "org.yammp.playstatusrequest";
public final static String BROADCAST_PLAYSTATUS_RESPONSE = "org.yammp.playstatusresponse";
public final static int MENU_OPEN_URL = R.id.open_url;
public final static int MENU_ADD_TO_PLAYLIST = R.id.add_to_playlist;
public final static int MENU_TOGGLE_SHUFFLE = R.id.toggle_shuffle;
public final static int MENU_TOGGLE_REPEAT = R.id.toggle_repeat;
public final static int MENU_SLEEP_TIMER = R.id.sleep_timer;
public final static int MENU_SAVE_AS_PLAYLIST = R.id.save_as_playlist;
public final static int MENU_CLEAR_PLAYLIST = R.id.clear_playlist;
public final static int MENU_PLAYLIST_SELECTED = R.id.playlist_selected;
public final static int MENU_NEW_PLAYLIST = R.id.new_playlist;
public final static int PLAY_SELECTION = R.id.play_selection;
public final static int GOTO_PLAYBACK = R.id.goto_playback;
public final static int GOTO_HOME = android.R.id.home;
public final static int MENU_ADD_TO_FAVORITES = R.id.add_to_favorite;
public final static int PARTY_SHUFFLE = R.id.party_shuffle;
public final static int SHUFFLE_ALL = R.id.shuffle_all;
public final static int PLAY_ALL = R.id.play_all;
public final static int DELETE_ITEMS = R.id.delete_items;
public final static int DELETE_LYRICS = R.id.delete_lyrics;
public final static int EQUALIZER = R.id.equalizer;
public final static int EQUALIZER_PRESETS = R.id.equalizer_presets;
public final static int EQUALIZER_RESET = R.id.equalizer_reset;
public final static int SCAN_DONE = R.id.scan_done;
public final static int QUEUE = R.id.queue;
public final static int SETTINGS = R.id.settings;
public final static int SEARCH = R.id.search;
public final static int REMOVE = R.id.remove;
public final static int PLAY_PAUSE = R.id.play_pause;
public final static int NEXT = R.id.next;
public final static int CHILD_MENU_BASE = 15; // this should be the last
public final static String[] HIDE_PLAYLISTS = new String[] { "Sony Ericsson play queue",
"Sony Ericsson played tracks", "Sony Ericsson temporary playlist", "$$miui" };
/**
* Following genres data is copied from from id3lib 3.8.3
*/
public final static String[] GENRES_DB = { "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", "Psychedelic", "Rave", "Showtunes",
"Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka", "Retro", "Musical",
"Rock & Roll", "Hard Rock", "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 Rap",
"Heavy Metal", "Black Metal", "Crossover", "Contemporary Christian", "Christian Rock ",
"Merengue", "Salsa", "Thrash Metal", "Anime", "JPop", "Synthpop" };
}
|
061304011116lyj-yammp
|
src/org/yammp/Constants.java
|
Java
|
gpl3
| 17,701
|
package org.yammp;
import org.yammp.util.LazyImageLoader;
import org.yammp.util.MediaUtils;
import org.yammp.util.ServiceInterface;
import android.app.Application;
import android.content.res.Configuration;
public class YAMMPApplication extends Application {
private MediaUtils mUtils;
private ServiceInterface mServiceInterface;
private LazyImageLoader mImageLoader;
public LazyImageLoader getLazyImageLoader() {
return mImageLoader;
}
public MediaUtils getMediaUtils() {
return mUtils;
}
public ServiceInterface getServiceInterface() {
return mServiceInterface;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onCreate() {
super.onCreate();
mUtils = new MediaUtils(this);
mImageLoader = new LazyImageLoader(this, R.drawable.ic_mp_albumart_unknown, getResources()
.getDimensionPixelSize(R.dimen.album_art_size) / 2);
mServiceInterface = new ServiceInterface(this);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (mImageLoader != null) {
mImageLoader.clearMemoryCache();
}
}
@Override
public void onTerminate() {
super.onTerminate();
mUtils = null;
}
}
|
061304011116lyj-yammp
|
src/org/yammp/YAMMPApplication.java
|
Java
|
gpl3
| 1,226
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp;
import org.yammp.app.MediaPlayerActivity;
import org.yammp.app.MusicPlaybackActivity;
import org.yammp.util.MediaUtils;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.RemoteViews;
/**
* Simple widget to show currently playing album art along with play/pause and
* next track buttons.
*/
public class MediaAppWidgetProvider4x2 extends AppWidgetProvider implements Constants {
private static String mTrackName, mAlbumName, mArtistName;
private static long mAlbumId, mAudioId;
private static boolean mIsPlaying;
private static String[] mLyrics = new String[] {};
private static int mLyricsStat, mRepeatMode, mShuffleMode;
@Override
public void onReceive(Context context, Intent intent) {
performUpdate(context, intent);
super.onReceive(context, intent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
init(context, appWidgetIds);
}
/**
* Initialize given widgets to default state, where we launch Music on
* default click and hide actions if service not running.
*/
private void init(Context context, int[] appWidgetIds) {
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.album_appwidget4x2);
views.setViewVisibility(R.id.track_name, View.GONE);
views.setViewVisibility(R.id.lyrics_line, View.GONE);
linkButtons(context, views, false);
pushUpdate(context, appWidgetIds, views);
}
/**
* Link up various button actions using {@link PendingIntents}.
*
* @param isPlaying
* True if player is active in background, which means widget
* click will launch {@link MusicPlaybackActivity}, otherwise we
* launch {@link MediaPlayerActivity}.
*/
private void linkButtons(Context context, RemoteViews views, boolean isPlaying) {
// Connect up various buttons and touch events
Intent intent;
PendingIntent pendingIntent;
final ComponentName serviceName = new ComponentName(context, MusicPlaybackService.class);
if (isPlaying) {
pendingIntent = PendingIntent.getActivity(context, 0,
new Intent(INTENT_PLAYBACK_VIEWER), 0);
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
} else {
pendingIntent = PendingIntent.getActivity(context, 0, new Intent(INTENT_MUSIC_BROWSER),
0);
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
}
intent = new Intent(TOGGLEPAUSE_ACTION);
intent.setComponent(serviceName);
pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.control_play, pendingIntent);
intent = new Intent(NEXT_ACTION);
intent.setComponent(serviceName);
pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.control_next, pendingIntent);
intent = new Intent(PREVIOUS_ACTION);
intent.setComponent(serviceName);
pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.control_prev, pendingIntent);
intent = new Intent(CYCLEREPEAT_ACTION);
intent.setComponent(serviceName);
pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.control_repeat, pendingIntent);
intent = new Intent(TOGGLESHUFFLE_ACTION);
intent.setComponent(serviceName);
pendingIntent = PendingIntent.getService(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.control_shuffle, pendingIntent);
}
/**
* Update all active widget instances by pushing changes
*/
private void performUpdate(Context context, Intent intent) {
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, this
.getClass()));
final Resources res = context.getResources();
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.album_appwidget4x2);
if (BROADCAST_META_CHANGED.equals(intent.getAction())
|| BROADCAST_PLAYSTATE_CHANGED.equals(intent.getAction())) {
mTrackName = intent.getStringExtra(BROADCAST_KEY_TRACK);
String artist = intent.getStringExtra(BROADCAST_KEY_ARTIST);
String album = intent.getStringExtra(BROADCAST_KEY_ALBUM);
if (artist != null && !MediaStore.UNKNOWN_STRING.equals(artist)) {
mArtistName = artist;
} else {
mArtistName = context.getString(R.string.unknown_artist);
}
if (album != null && !MediaStore.UNKNOWN_STRING.equals(album)) {
mAlbumName = album;
} else {
mAlbumName = context.getString(R.string.unknown_album);
}
mAlbumId = intent.getLongExtra(BROADCAST_KEY_ALBUMID, -1);
mAudioId = intent.getLongExtra(BROADCAST_KEY_SONGID, -1);
mIsPlaying = intent.getBooleanExtra(BROADCAST_KEY_PLAYING, false);
views.setTextViewText(R.id.lyrics_line, "");
} else if (BROADCAST_NEW_LYRICS_LOADED.equals(intent.getAction())) {
mLyrics = intent.getStringArrayExtra(BROADCAST_KEY_LYRICS);
mLyricsStat = intent.getIntExtra(BROADCAST_KEY_LYRICS_STATUS, LYRICS_STATUS_INVALID);
} else if (BROADCAST_REPEATMODE_CHANGED.equals(intent.getAction())) {
mRepeatMode = intent.getIntExtra(BROADCAST_KEY_REPEATMODE, REPEAT_NONE);
} else if (BROADCAST_SHUFFLEMODE_CHANGED.equals(intent.getAction())) {
mShuffleMode = intent.getIntExtra(BROADCAST_KEY_SHUFFLEMODE, SHUFFLE_NONE);
}
CharSequence errorState = null;
// Format title string with track number, or show SD card message
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_SHARED) || status.equals(Environment.MEDIA_UNMOUNTED)) {
errorState = res.getText(R.string.sdcard_busy_title);
} else if (status.equals(Environment.MEDIA_REMOVED)) {
errorState = res.getText(R.string.sdcard_missing_title);
} else if (mTrackName == null) {
errorState = res.getText(R.string.emptyplaylist);
}
if (errorState != null) {
// Show error state to user
views.setViewVisibility(R.id.album_name, View.GONE);
views.setViewVisibility(R.id.track_name, View.GONE);
views.setTextViewText(R.id.artist_name, errorState);
views.setImageViewResource(R.id.album_art, R.drawable.ic_mp_albumart_unknown);
} else {
// No error, so show normal titles and artwork
views.setViewVisibility(R.id.album_name, View.VISIBLE);
views.setViewVisibility(R.id.track_name, View.VISIBLE);
views.setTextViewText(R.id.artist_name, mArtistName);
views.setTextViewText(R.id.album_name, mAlbumName);
views.setTextViewText(R.id.track_name, mTrackName);
// Set album art
Uri uri = new MediaUtils(context).getArtworkUri(mAudioId, mAlbumId);
if (uri != null) {
views.setImageViewUri(R.id.album_art, uri);
} else {
views.setImageViewResource(R.id.album_art, R.drawable.ic_mp_albumart_unknown);
}
if (BROADCAST_LYRICS_REFRESHED.equals(intent.getAction())) {
int lyrics_id = intent.getIntExtra(BROADCAST_KEY_LYRICS_ID, -1);
if (mLyrics != null && mLyrics.length > lyrics_id && lyrics_id >= 0) {
if (mLyricsStat == LYRICS_STATUS_OK) {
views.setViewVisibility(R.id.track_name, View.VISIBLE);
views.setTextViewText(R.id.lyrics_line, mLyrics[lyrics_id]);
} else {
views.setViewVisibility(R.id.lyrics_line, View.GONE);
views.setTextViewText(R.id.lyrics_line, "");
}
} else {
views.setViewVisibility(R.id.lyrics_line, View.GONE);
}
}
}
// Set correct drawable for pause state
if (mIsPlaying) {
views.setImageViewResource(R.id.control_play, R.drawable.btn_playback_ic_pause);
} else {
views.setImageViewResource(R.id.control_play, R.drawable.btn_playback_ic_play);
}
// Set correct drawable for repeat state
switch (mRepeatMode) {
case REPEAT_ALL:
views.setImageViewResource(R.id.control_repeat, R.drawable.ic_mp_repeat_all_btn);
break;
case REPEAT_CURRENT:
views.setImageViewResource(R.id.control_repeat, R.drawable.ic_mp_repeat_once_btn);
break;
default:
views.setImageViewResource(R.id.control_repeat, R.drawable.ic_mp_repeat_off_btn);
break;
}
// Set correct drawable for shuffle state
switch (mShuffleMode) {
case SHUFFLE_NORMAL:
views.setImageViewResource(R.id.control_shuffle, R.drawable.ic_mp_shuffle_on_btn);
break;
default:
views.setImageViewResource(R.id.control_shuffle, R.drawable.ic_mp_shuffle_off_btn);
break;
}
// Link actions buttons to intents
linkButtons(context, views, mIsPlaying);
pushUpdate(context, appWidgetIds, views);
}
private void pushUpdate(Context context, int[] appWidgetIds, RemoteViews views) {
// Update specific list of appWidgetIds if given, otherwise default to
// all
final AppWidgetManager gm = AppWidgetManager.getInstance(context);
if (appWidgetIds != null) {
gm.updateAppWidget(appWidgetIds, views);
} else {
gm.updateAppWidget(new ComponentName(context, this.getClass()), views);
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/MediaAppWidgetProvider4x2.java
|
Java
|
gpl3
| 10,056
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.widget;
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
/**
* A button that will repeatedly call a 'listener' method as long as the button
* is pressed.
*/
public class RepeatingImageButton extends ImageButton {
private long mStartTime;
private int mRepeatCount;
private OnRepeatListener mListener;
private long mInterval = 500;
private Runnable mRepeater = new Runnable() {
@Override
public void run() {
doRepeat(false);
if (isPressed()) {
postDelayed(this, mInterval);
}
}
};
public RepeatingImageButton(Context context) {
this(context, null);
}
public RepeatingImageButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.imageButtonStyle);
}
public RepeatingImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
setLongClickable(true);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
// need to call super to make long press work, but return
// true so that the application doesn't get the down event.
super.onKeyDown(keyCode, event);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
// remove the repeater, but call the hook one more time
removeCallbacks(mRepeater);
if (mStartTime != 0) {
doRepeat(true);
mStartTime = 0;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// remove the repeater, but call the hook one more time
removeCallbacks(mRepeater);
if (mStartTime != 0) {
doRepeat(true);
mStartTime = 0;
}
}
return super.onTouchEvent(event);
}
@Override
public boolean performLongClick() {
mStartTime = SystemClock.elapsedRealtime();
mRepeatCount = 0;
post(mRepeater);
return true;
}
/**
* Sets the listener to be called while the button is pressed and the
* interval in milliseconds with which it will be called.
*
* @param l
* The listener that will be called
* @param interval
* The interval in milliseconds for calls
*/
public void setRepeatListener(OnRepeatListener l, long interval) {
mListener = l;
mInterval = interval;
}
private void doRepeat(boolean last) {
long now = SystemClock.elapsedRealtime();
if (mListener != null) {
mListener.onRepeat(this, now - mStartTime, last ? -1 : mRepeatCount++);
}
}
public interface OnRepeatListener {
/**
* This method will be called repeatedly at roughly the interval
* specified in setRepeatListener(), for as long as the button is
* pressed.
*
* @param v
* The button as a View.
* @param duration
* The number of milliseconds the button has been pressed so
* far.
* @param repeatcount
* The number of previous calls in this sequence. If this is
* going to be the last call in this sequence (i.e. the user
* just stopped pressing the button), the value will be -1.
*/
void onRepeat(View v, long duration, int repeatcount);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/widget/RepeatingImageButton.java
|
Java
|
gpl3
| 4,205
|
package org.yammp.widget;
import org.yammp.util.LyricsSplitter;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class TextScrollView extends ScrollView implements OnLongClickListener {
// Namespaces to read attributes
private static final String ANDROID_NS = "http://schemas.android.com/apk/res/android";
private static final String ATTR_TEXTSIZE = "textSize";
private static final String ATTR_SHADOWCOLOR = "shadowColor";
private static final String ATTR_SHADOWDX = "shadowDx";
private static final String ATTR_SHADOWDY = "shadowDy";
private static final String ATTR_SHADOWRADIUS = "shadowRadius";
private LinearLayout mContentContainer;
private boolean mSmoothScrolling = false;
private boolean mEnableAutoScrolling = true;
private int mTextColor = Color.WHITE, mShadowColor = Color.BLACK;
private float mTextSize = 15.0f, mShadowDx = 0.0f, mShadowDy = 0.0f, mShadowRadius = 0.0f;
private int mLastLineId = -1;
private String[] mContent;
private final int TIMEOUT = 1;
public OnLineSelectedListener mListener;
private Context mContext;
public Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TIMEOUT:
mHandler.removeMessages(TIMEOUT);
mEnableAutoScrolling = true;
break;
}
}
};
public TextScrollView(Context context) {
super(context);
init(context);
}
public TextScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mShadowRadius = attrs.getAttributeFloatValue(ANDROID_NS, ATTR_SHADOWRADIUS, 0.0f);
mShadowDx = attrs.getAttributeFloatValue(ANDROID_NS, ATTR_SHADOWDX, 0.0f);
mShadowDy = attrs.getAttributeFloatValue(ANDROID_NS, ATTR_SHADOWDY, 0.0f);
String shadow_color_value = attrs.getAttributeValue(ANDROID_NS, ATTR_SHADOWCOLOR);
if (shadow_color_value != null) {
if (shadow_color_value.startsWith("#")) {
try {
mShadowColor = Color.parseColor(shadow_color_value);
} catch (IllegalArgumentException e) {
Log.e("TextScrollView", "Wrong color: " + shadow_color_value);
}
} else if (shadow_color_value.startsWith("@")) {
int colorResourceId = attrs.getAttributeResourceValue(ANDROID_NS, ATTR_SHADOWCOLOR,
0);
if (colorResourceId != 0) {
mShadowColor = context.getResources().getColor(colorResourceId);
}
}
}
String text_size_value = attrs.getAttributeValue(ANDROID_NS, ATTR_TEXTSIZE);
if (text_size_value != null) {
mTextSize = parseTextSize(text_size_value);
}
init(context);
}
@Override
public boolean onLongClick(View view) {
if (mListener != null) {
Object tag = view.getTag();
int id = tag != null ? Integer.valueOf(tag.toString()) : 0;
mListener.onLineSelected(id);
}
return true;
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
mContentContainer.setPadding(0, h / 2, 0, h / 2);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
mHandler.sendEmptyMessageDelayed(TIMEOUT, 2000L);
break;
case MotionEvent.ACTION_DOWN:
mHandler.removeMessages(TIMEOUT);
mEnableAutoScrolling = false;
break;
case MotionEvent.ACTION_MOVE:
mHandler.removeMessages(TIMEOUT);
mEnableAutoScrolling = false;
break;
}
return super.onTouchEvent(event);
}
public void setContentGravity(int gravity) {
if (mContentContainer != null) {
mContentContainer.setGravity(gravity);
}
}
public void setCurrentLine(int lineid, boolean force) {
if (findViewWithTag(mLastLineId) != null) {
((TextView) findViewWithTag(mLastLineId)).setTextColor(Color.argb(0xD0,
Color.red(mTextColor), Color.green(mTextColor), Color.blue(mTextColor)));
((TextView) findViewWithTag(mLastLineId)).getPaint().setFakeBoldText(false);
}
if (findViewWithTag(lineid) != null) {
((TextView) findViewWithTag(lineid)).setTextColor(Color.argb(0xFF,
Color.red(mTextColor), Color.green(mTextColor), Color.blue(mTextColor)));
((TextView) findViewWithTag(lineid)).getPaint().setFakeBoldText(true);
if (mEnableAutoScrolling || force) {
if (mSmoothScrolling) {
smoothScrollTo(0, findViewWithTag(lineid).getTop()
+ findViewWithTag(lineid).getHeight() / 2 - getHeight() / 2);
} else {
scrollTo(0, findViewWithTag(lineid).getTop()
+ findViewWithTag(lineid).getHeight() / 2 - getHeight() / 2);
}
}
mLastLineId = lineid;
}
}
public void setLineSelectedListener(OnLineSelectedListener listener) {
mListener = listener;
}
@Override
public void setSmoothScrollingEnabled(boolean smooth) {
mSmoothScrolling = smooth;
}
public void setTextColor(int color) {
mTextColor = color;
setTextContent(mContent);
setCurrentLine(mLastLineId, true);
}
public void setTextContent(String[] content) {
mContent = content;
mLastLineId = -1;
mContentContainer.removeAllViews();
int content_id = 0;
for (String line : content) {
TextView mTextView = new TextView(mContext);
mTextView.setText(LyricsSplitter.split(line, mTextView.getTextSize()));
mTextView.setTextColor(Color.argb(0xD0, Color.red(mTextColor), Color.green(mTextColor),
Color.blue(mTextColor)));
float density = getResources().getDisplayMetrics().density;
mTextView.setShadowLayer(mShadowRadius * density, mShadowDx, mShadowDy, mShadowColor);
mTextView.setGravity(Gravity.CENTER);
mTextView.setTextSize(mTextSize);
mTextView.setOnLongClickListener(this);
if (content_id < content.length) {
mTextView.setTag(content_id);
content_id++;
}
mContentContainer.addView(mTextView, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER));
}
if (mSmoothScrolling) {
smoothScrollTo(0, 0);
} else {
scrollTo(0, 0);
}
}
public void setTextSize(float size) {
mTextSize = size;
setTextContent(mContent);
setCurrentLine(mLastLineId, true);
}
private void init(Context context) {
mContext = context;
ViewCompat.setOverScrollMode(this, ViewCompat.OVER_SCROLL_NEVER);
setVerticalScrollBarEnabled(false);
mContentContainer = new LinearLayout(context);
mContentContainer.setOrientation(LinearLayout.VERTICAL);
mContentContainer.setPadding(0, getHeight() / 2, 0, getHeight() / 2);
addView(mContentContainer, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
private float parseTextSize(String value) {
float density = getResources().getDisplayMetrics().density;
if (value == null) throw new IllegalArgumentException("Value cannot be null!");
if (value.endsWith("px"))
return Integer.parseInt(value.replaceAll("px", "")) / density;
else if (value.endsWith("dip"))
return Float.parseFloat(value.replaceAll("dip", ""));
else if (value.endsWith("sp"))
return Float.parseFloat(value.replaceAll("sp", ""));
else
throw new IllegalArgumentException("Value " + value + " is not valid!");
}
public interface OnLineSelectedListener {
void onLineSelected(int id);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/widget/TextScrollView.java
|
Java
|
gpl3
| 7,617
|
package org.yammp.widget;
import java.util.LinkedHashMap;
import java.util.Map;
import org.yammp.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
public class SeparatedListAdapter extends BaseAdapter {
private final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
private final ArrayAdapter<String> headers;
private final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
headers.add(section);
sections.put(section, adapter);
}
public boolean areAllItemsSelectable() {
return false;
}
@Override
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : sections.values()) {
total += adapter.getCount() + 1;
}
return total;
}
@Override
public Object getItem(int position) {
for (Object section : sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0) return section;
if (position < size) return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0) return TYPE_SECTION_HEADER;
if (position < size) return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0) return headers.getView(sectionnum, convertView, parent);
if (position < size) return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
@Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : sections.values()) {
total += adapter.getViewTypeCount();
}
return total;
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) != TYPE_SECTION_HEADER;
}
}
|
061304011116lyj-yammp
|
src/org/yammp/widget/SeparatedListAdapter.java
|
Java
|
gpl3
| 2,927
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.RelativeLayout;
/**
* A special variation of RelativeLayout that can be used as a checkable object.
* This allows it to be used as the top-level view of a list view item, which
* also supports checking. Otherwise, it works identically to a RelativeLayout.
*/
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
}
|
061304011116lyj-yammp
|
src/org/yammp/widget/CheckableRelativeLayout.java
|
Java
|
gpl3
| 1,857
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.widget;
import org.yammp.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
public class TouchInterceptor extends ListView {
private ImageView mDragView;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mWindowParams;
private int mDragPos;
private int mSrcDragPos;
private int mDragPointX;
private int mDragPointY;
private int mXOffset;
private int mYOffset;
private OnDragListener mDragListener;
private OnDropListener mDropListener;
private OnRemoveListener mRemoveListener;
private int mUpperBound;
private int mLowerBound;
private int mHeight;
private GestureDetector mGestureDetector;
private Rect mTempRect = new Rect();
private Bitmap mDragBitmap;
private final int mTouchSlop;
private int mItemHeightNormal;
private int mItemHeightExpanded;
private int mItemHeightHalf;
private int mStartX, mStartY = 0;
private boolean mSortDragging, mRemoveDragging = false;
public TouchInterceptor(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
Resources res = getResources();
mItemHeightNormal = res.getDimensionPixelSize(R.dimen.normal_height);
mItemHeightHalf = mItemHeightNormal / 2;
mItemHeightExpanded = mItemHeightNormal * 2;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mDragListener != null || mDropListener != null) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
int x = (int) ev.getX();
int y = (int) ev.getY();
int itemnum = pointToPosition(x, y);
if (itemnum == AdapterView.INVALID_POSITION) {
break;
}
ViewGroup item = (ViewGroup) getChildAt(itemnum - getFirstVisiblePosition());
mDragPointX = x - item.getLeft();
mDragPointY = y - item.getTop();
mXOffset = (int) ev.getRawX() - x;
mYOffset = (int) ev.getRawY() - y;
// The left side of the item is the grabber for dragging the
// item
if (x < mItemHeightNormal) {
item.setDrawingCacheEnabled(true);
// Create a copy of the drawing cache so that it does
// not get recycled by the framework when the list
// tries to clean up memory
Bitmap bitmap = Bitmap.createBitmap(item.getDrawingCache());
item.setVisibility(View.INVISIBLE);
startDragging(bitmap, x, y);
mDragPos = itemnum;
mSrcDragPos = mDragPos;
mHeight = getHeight();
int touchSlop = mTouchSlop;
mUpperBound = Math.min(y - touchSlop, mHeight / 3);
mLowerBound = Math.max(y + touchSlop, mHeight * 2 / 3);
return false;
}
stopDragging();
break;
}
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mGestureDetector != null) {
mGestureDetector.onTouchEvent(ev);
}
if ((mDragListener != null || mDropListener != null) && mDragView != null) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
mStartX = 0;
mStartY = 0;
case MotionEvent.ACTION_CANCEL:
Rect r = mTempRect;
mDragView.getDrawingRect(r);
stopDragging();
if (mDragPos >= 0 && mDragPos < getCount()) {
if (mDropListener != null && mSortDragging && !mRemoveDragging) {
mDropListener.onDrop(mSrcDragPos, mDragPos);
} else if (mRemoveListener != null
&& mRemoveDragging
&& !mSortDragging
&& ev.getX() >= mWindowManager.getDefaultDisplay().getWidth()
- mItemHeightNormal) {
mRemoveListener.onRemove(mDragPos);
}
}
unExpandViews(false);
break;
case MotionEvent.ACTION_DOWN:
mSortDragging = false;
mRemoveDragging = false;
mStartX = (int) ev.getX();
mStartY = (int) ev.getY();
case MotionEvent.ACTION_MOVE:
int x = (int) ev.getX();
int y = (int) ev.getY();
if (Math.abs(x - mStartX) >= mItemHeightNormal / 2
&& Math.abs(y - mStartY) < mItemHeightNormal / 2 && !mRemoveDragging) {
mRemoveDragging = true;
} else if (Math.abs(x - mStartX) < mItemHeightNormal / 2
&& Math.abs(y - mStartY) >= mItemHeightNormal / 2 && !mSortDragging) {
mSortDragging = true;
}
int itemnum = getItemForPosition(y);
if (itemnum >= 0) {
if (mSortDragging && !mRemoveDragging) {
dragView(x, y);
if (action == MotionEvent.ACTION_DOWN || itemnum != mDragPos) {
if (mDragListener != null) {
mDragListener.onDrag(mDragPos, itemnum);
}
mDragPos = itemnum;
doExpansion();
}
int speed = 0;
adjustScrollBounds(y);
if (y > mLowerBound) {
// scroll the list up a bit
if (getLastVisiblePosition() < getCount() - 1) {
speed = y > (mHeight + mLowerBound) / 2 ? 16 : 4;
} else {
speed = 1;
}
} else if (y < mUpperBound) {
// scroll the list down a bit
speed = y < mUpperBound / 2 ? -16 : -4;
if (getFirstVisiblePosition() == 0
&& getChildAt(0).getTop() >= getPaddingTop()) {
// if we're already at the top, don't try to
// scroll, because it causes the framework
// to do some extra drawing that messes up
// our animation
speed = 0;
}
}
if (speed != 0) {
smoothScrollBy(speed, 30);
}
} else if (!mSortDragging && mRemoveDragging) {
dragView(x, y);
}
}
break;
}
return true;
}
return super.onTouchEvent(ev);
}
public void setDragListener(OnDragListener listener) {
mDragListener = listener;
}
public void setDropListener(OnDropListener listener) {
mDropListener = listener;
}
public void setRemoveListener(OnRemoveListener listener) {
mRemoveListener = listener;
}
private void adjustScrollBounds(int y) {
if (y >= mHeight / 3) {
mUpperBound = mHeight / 3;
}
if (y <= mHeight * 2 / 3) {
mLowerBound = mHeight * 2 / 3;
}
}
/**
* pointToPosition() doesn't consider invisible views, but we need to, so
* implement a slightly different version.
*/
private int betterPointToPosition(int x, int y) {
if (y < 0) {
// when dragging off the top of the screen, calculate position
// by going back from a visible item
int pos = betterPointToPosition(x, y + mItemHeightNormal);
if (pos > 0) return pos - 1;
}
Rect frame = mTempRect;
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
child.getHitRect(frame);
if (frame.contains(x, y)) return getFirstVisiblePosition() + i;
}
return INVALID_POSITION;
}
/**
* Adjust visibility and size to make it appear as though an item is being
* dragged around and other items are making room for it: If dropping the
* item would result in it still being in the same place, then make the
* dragged listitem's size normal, but make the item invisible. Otherwise,
* if the dragged listitem is still on screen, make it as small as possible
* and expand the item below the insert point. If the dragged item is not on
* screen, only expand the item below the current insertpoint.
*/
private void doExpansion() {
int childnum = mDragPos - getFirstVisiblePosition();
if (mDragPos > mSrcDragPos) {
childnum++;
}
int numheaders = getHeaderViewsCount();
View first = getChildAt(mSrcDragPos - getFirstVisiblePosition());
for (int i = 0;; i++) {
View vv = getChildAt(i);
if (vv == null) {
break;
}
int height = mItemHeightNormal;
int visibility = View.VISIBLE;
if (mDragPos < numheaders && i == numheaders) {
// dragging on top of the header item, so adjust the item below
// instead
if (vv.equals(first)) {
visibility = View.INVISIBLE;
} else {
height = mItemHeightExpanded;
}
} else if (vv.equals(first)) {
// processing the item that is being dragged
if (mDragPos == mSrcDragPos || getPositionForView(vv) == getCount() - 1) {
// hovering over the original location
visibility = View.INVISIBLE;
} else {
// not hovering over it
// Ideally the item would be completely gone, but neither
// setting its size to 0 nor settings visibility to GONE
// has the desired effect.
height = 1;
}
} else if (i == childnum) {
if (mDragPos >= numheaders && mDragPos < getCount() - 1) {
height = mItemHeightExpanded;
}
}
ViewGroup.LayoutParams params = vv.getLayoutParams();
params.height = height;
vv.setLayoutParams(params);
vv.setVisibility(visibility);
}
}
private void dragView(int x, int y) {
if (mRemoveDragging && !mSortDragging) {
mWindowParams.x = x + mXOffset;
if (x >= mWindowManager.getDefaultDisplay().getWidth() - mItemHeightNormal) {
mDragView.setBackgroundResource(R.drawable.playlist_tile_discard);
} else {
mDragView.setBackgroundResource(R.drawable.playlist_tile_drag);
}
} else if (!mRemoveDragging && mSortDragging) {
mWindowParams.x = mXOffset;
mWindowParams.y = y - mDragPointY + mYOffset;
}
mWindowManager.updateViewLayout(mDragView, mWindowParams);
}
private int getItemForPosition(int y) {
int adjustedy = y - mDragPointY - mItemHeightHalf;
int pos = betterPointToPosition(0, adjustedy);
if (pos >= 0) {
if (pos <= mSrcDragPos) {
pos += 1;
}
} else if (adjustedy < 0) {
// this shouldn't happen anymore now that myPointToPosition deals
// with this situation
pos = 0;
}
return pos;
}
private void startDragging(Bitmap bm, int x, int y) {
stopDragging();
mWindowParams = new WindowManager.LayoutParams();
mWindowParams.gravity = Gravity.TOP | Gravity.LEFT;
mWindowParams.x = x - mDragPointX + mXOffset;
mWindowParams.y = y - mDragPointY + mYOffset;
mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
mWindowParams.format = PixelFormat.TRANSLUCENT;
mWindowParams.windowAnimations = 0;
Context context = getContext();
ImageView v = new ImageView(context);
v.setBackgroundResource(R.drawable.playlist_tile_drag);
v.setPadding(0, 0, 0, 0);
v.setImageBitmap(bm);
mDragBitmap = bm;
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mWindowManager.addView(v, mWindowParams);
mDragView = v;
}
private void stopDragging() {
if (mDragView != null) {
mDragView.setVisibility(GONE);
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(mDragView);
mDragView.setImageDrawable(null);
mDragView = null;
}
if (mDragBitmap != null) {
mDragBitmap.recycle();
mDragBitmap = null;
}
}
/**
* Restore size and visibility for all listitems
*/
private void unExpandViews(boolean deletion) {
for (int i = 0;; i++) {
View v = getChildAt(i);
if (v == null) {
if (deletion) {
// HACK force update of mItemCount
int position = getFirstVisiblePosition();
int y = getChildAt(0).getTop();
setAdapter(getAdapter());
setSelectionFromTop(position, y);
// end hack
}
try {
layoutChildren(); // force children to be recreated where
// needed
v = getChildAt(i);
} catch (IllegalStateException ex) {
// layoutChildren throws this sometimes, presumably because
// we're in the process of being torn down but are still
// getting touch events
}
if (v == null) return;
}
ViewGroup.LayoutParams params = v.getLayoutParams();
params.height = mItemHeightNormal;
v.setLayoutParams(params);
v.setVisibility(View.VISIBLE);
}
}
public interface OnDragListener {
void onDrag(int from, int to);
}
public interface OnDropListener {
void onDrop(int from, int to);
}
public interface OnRemoveListener {
void onRemove(int which);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/widget/TouchInterceptor.java
|
Java
|
gpl3
| 13,303
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.app.BaseActivity;
import org.yammp.util.EqualizerWrapper;
import org.yammp.util.MediaUtils;
import org.yammp.util.PreferencesEditor;
import org.yammp.util.ServiceInterface;
import org.yammp.util.ServiceInterface.MediaStateListener;
import org.yammp.widget.RepeatingImageButton;
import org.yammp.widget.RepeatingImageButton.OnRepeatListener;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MusicPlaybackFragment extends SherlockFragment implements Constants, OnClickListener,
OnLongClickListener, OnRepeatListener, MediaStateListener, ViewFactory {
private long mStartSeekPos = 0;
private long mLastSeekEventTime;
private RepeatingImageButton mPrevButton;
private ImageButton mPauseButton;
private RepeatingImageButton mNextButton;
private PreferencesEditor mPrefs;
private boolean mShowFadeAnimation = false;
private boolean mLyricsWakelock = DEFAULT_LYRICS_WAKELOCK;
int mInitialX = -1;
int mLastX = -1;
int mTextWidth = 0;
int mViewWidth = 0;
boolean mDraggingLabel = false;
private BroadcastReceiver mScreenTimeoutListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
if (mInterface != null) {
mInterface.addMediaStateListener(MusicPlaybackFragment.this);
}
getSherlockActivity().invalidateOptionsMenu();
} else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
if (mInterface != null) {
mInterface.removeMediaStateListener(MusicPlaybackFragment.this);
}
}
}
};
private MediaUtils mUtils;
private ServiceInterface mInterface;
private ImageSwitcher mAlbum;
private AsyncAlbumArtLoader mAlbumArtLoader;
@Override
public View makeView() {
ImageView view = new ImageView(getActivity());
view.setScaleType(ImageView.ScaleType.FIT_CENTER);
view.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return view;
}
@Override
public void onActivityCreated(Bundle icicle) {
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
mInterface = ((YAMMPApplication) getSherlockActivity().getApplication())
.getServiceInterface();
mPrefs = new PreferencesEditor(getSherlockActivity());
super.onActivityCreated(icicle);
setHasOptionsMenu(true);
configureActivity();
mInterface.addMediaStateListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.pause:
doPauseResume();
break;
case R.id.prev:
doPrev();
break;
case R.id.next:
doNext();
break;
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.music_playback, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.music_playback, container, false);
}
@Override
public void onFavoriteStateChanged() {
getSherlockActivity().invalidateOptionsMenu();
}
@Override
public boolean onLongClick(View v) {
// TODO search media info
String track = getSherlockActivity().getTitle().toString();
String artist = "";// mArtistNameView.getText().toString();
String album = "";// mAlbumNameView.getText().toString();
CharSequence title = getString(R.string.mediasearch, track);
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, track);
String query = track;
if (!getString(R.string.unknown_artist).equals(artist)
&& !getString(R.string.unknown_album).equals(album)) {
query = artist + " " + track;
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
} else if (getString(R.string.unknown_artist).equals(artist)
&& !getString(R.string.unknown_album).equals(album)) {
query = album + " " + track;
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
} else if (!getString(R.string.unknown_artist).equals(artist)
&& getString(R.string.unknown_album).equals(album)) {
query = artist + " " + track;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
}
i.putExtra(SearchManager.QUERY, query);
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
startActivity(Intent.createChooser(i, title));
return true;
}
@Override
public void onMetaChanged() {
getSherlockActivity().invalidateOptionsMenu();
setPauseButtonImage();
if (mAlbumArtLoader != null) {
mAlbumArtLoader.cancel(true);
}
mAlbumArtLoader = new AsyncAlbumArtLoader();
mAlbumArtLoader.execute();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case MENU_TOGGLE_SHUFFLE:
if (mInterface != null) {
mInterface.toggleShuffle();
}
break;
case MENU_TOGGLE_REPEAT:
if (mInterface != null) {
mInterface.toggleRepeat();
}
break;
case MENU_ADD_TO_FAVORITES:
if (mInterface != null) {
mInterface.toggleFavorite();
}
break;
case MENU_ADD_TO_PLAYLIST:
intent = new Intent(INTENT_ADD_TO_PLAYLIST);
long[] list_to_be_added = new long[1];
list_to_be_added[0] = mUtils.getCurrentAudioId();
intent.putExtra(INTENT_KEY_LIST, list_to_be_added);
startActivity(intent);
break;
case EQUALIZER:
intent = new Intent(INTENT_EQUALIZER);
startActivity(intent);
break;
case MENU_SLEEP_TIMER:
intent = new Intent(INTENT_SLEEP_TIMER);
startActivity(intent);
break;
case DELETE_ITEMS:
intent = new Intent(INTENT_DELETE_ITEMS);
Bundle bundle = new Bundle();
bundle.putString(
INTENT_KEY_PATH,
Uri.withAppendedPath(Audio.Media.EXTERNAL_CONTENT_URI,
Uri.encode(String.valueOf(mUtils.getCurrentAudioId()))).toString());
intent.putExtras(bundle);
startActivity(intent);
break;
case SETTINGS:
intent = new Intent(INTENT_APPEARANCE_SETTINGS);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPlayStateChanged() {
setPauseButtonImage();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(EQUALIZER);
if (item != null) {
item.setVisible(EqualizerWrapper.isSupported());
}
item = menu.findItem(MENU_TOGGLE_SHUFFLE);
if (item != null && mInterface != null) {
switch (mInterface.getShuffleMode()) {
case SHUFFLE_NONE:
item.setIcon(R.drawable.ic_mp_shuffle_off_btn);
break;
default:
item.setIcon(R.drawable.ic_mp_shuffle_on_btn);
break;
}
}
item = menu.findItem(MENU_TOGGLE_REPEAT);
if (item != null && mInterface != null) {
switch (mInterface.getRepeatMode()) {
case REPEAT_ALL:
item.setIcon(R.drawable.ic_mp_repeat_all_btn);
break;
case REPEAT_CURRENT:
item.setIcon(R.drawable.ic_mp_repeat_once_btn);
break;
default:
item.setIcon(R.drawable.ic_mp_repeat_off_btn);
break;
}
}
item = menu.findItem(MENU_ADD_TO_FAVORITES);
if (item != null && mInterface != null) {
item.setIcon(mInterface.isFavorite(mInterface.getAudioId()) ? R.drawable.ic_menu_star
: R.drawable.ic_menu_star_off);
}
super.onPrepareOptionsMenu(menu);
}
@Override
public void onQueueChanged() {
}
@Override
public void onRepeat(View v, long howlong, int repcnt) {
switch (v.getId()) {
case R.id.prev:
scanBackward(repcnt, howlong);
break;
case R.id.next:
scanForward(repcnt, howlong);
break;
}
}
@Override
public void onRepeatModeChanged() {
getSherlockActivity().invalidateOptionsMenu();
}
@Override
public void onResume() {
super.onResume();
setPauseButtonImage();
}
@Override
public void onShuffleModeChanged() {
getSherlockActivity().invalidateOptionsMenu();
}
@Override
public void onStart() {
super.onStart();
loadPreferences();
if (mLyricsWakelock) {
getSherlockActivity().getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getSherlockActivity().getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
}
try {
float mTransitionAnimation = Settings.System.getFloat(getSherlockActivity()
.getContentResolver(), Settings.System.TRANSITION_ANIMATION_SCALE);
if (mTransitionAnimation > 0.0) {
mShowFadeAnimation = true;
} else {
mShowFadeAnimation = false;
}
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
IntentFilter s = new IntentFilter();
s.addAction(Intent.ACTION_SCREEN_ON);
s.addAction(Intent.ACTION_SCREEN_OFF);
getSherlockActivity().registerReceiver(mScreenTimeoutListener, new IntentFilter(s));
}
@Override
public void onStop() {
getSherlockActivity().unregisterReceiver(mScreenTimeoutListener);
getSherlockActivity().getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onStop();
}
private void configureActivity() {
View view = getView();
mPrevButton = (RepeatingImageButton) view.findViewById(R.id.prev);
mPrevButton.setOnClickListener(this);
mPrevButton.setRepeatListener(this, 260);
mPauseButton = (ImageButton) view.findViewById(R.id.pause);
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(this);
mNextButton = (RepeatingImageButton) view.findViewById(R.id.next);
mNextButton.setOnClickListener(this);
mNextButton.setRepeatListener(this, 260);
mAlbum = (ImageSwitcher) view.findViewById(R.id.album_art);
// mAlbum.setOnLongClickListener(mSearchAlbumArtListener);
mAlbum.setFactory(this);
getFragmentManager().beginTransaction()
.replace(R.id.playback_info_lyrics, new LyricsFragment()).commit();
}
private void doNext() {
if (mInterface == null) return;
mInterface.next();
}
private void doPauseResume() {
if (mInterface != null) {
if (mInterface.isPlaying()) {
mInterface.pause();
} else {
mInterface.play();
}
setPauseButtonImage();
}
}
private void doPrev() {
if (mInterface == null) return;
if (mInterface.position() < 2000) {
mInterface.prev();
} else {
mInterface.seek(0);
mInterface.play();
}
}
private void loadPreferences() {
mLyricsWakelock = mPrefs.getBooleanPref(KEY_LYRICS_WAKELOCK, DEFAULT_LYRICS_WAKELOCK);
}
private void scanBackward(int repcnt, long delta) {
if (mInterface == null) return;
if (repcnt == 0) {
mStartSeekPos = mInterface.position();
mLastSeekEventTime = 0;
} else {
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos - delta;
if (newpos < 0) {
// move to previous track
mInterface.prev();
long duration = mInterface.duration();
mStartSeekPos += duration;
newpos += duration;
}
if (delta - mLastSeekEventTime > 250 || repcnt < 0) {
mInterface.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
} else {
}
}
}
private void scanForward(int repcnt, long delta) {
if (mInterface == null) return;
if (repcnt == 0) {
mStartSeekPos = mInterface.position();
mLastSeekEventTime = 0;
} else {
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos + delta;
long duration = mInterface.duration();
if (newpos >= duration) {
// move to next track
mInterface.next();
mStartSeekPos -= duration; // is OK to go negative
newpos -= duration;
}
if (delta - mLastSeekEventTime > 250 || repcnt < 0) {
mInterface.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
} else {
}
}
}
private void setPauseButtonImage() {
if (mInterface != null) {
mPauseButton.setImageResource(mInterface.isPlaying() ? R.drawable.btn_playback_ic_pause
: R.drawable.btn_playback_ic_play);
} else {
}
}
private class AsyncAlbumArtLoader extends AsyncTask<Void, Void, Drawable> {
@Override
public Drawable doInBackground(Void... params) {
if (isDetached() || !isAdded()) return null;
if (mInterface != null) {
Bitmap bitmap = mUtils.getArtwork(mInterface.getAudioId(), mInterface.getAlbumId());
if (bitmap == null) return null;
int value = 0;
if (bitmap.getHeight() <= bitmap.getWidth()) {
value = bitmap.getHeight();
} else {
value = bitmap.getWidth();
}
Bitmap result = Bitmap.createBitmap(bitmap, (bitmap.getWidth() - value) / 2,
(bitmap.getHeight() - value) / 2, value, value);
return new BitmapDrawable(getResources(), result);
}
return null;
}
@Override
public void onPostExecute(Drawable result) {
if (isDetached() || !isAdded()) return;
if (mAlbum != null) {
if (result != null) {
mAlbum.setImageDrawable(result);
} else {
mAlbum.setImageResource(R.drawable.ic_mp_albumart_unknown);
}
}
if (mInterface != null) {
((BaseActivity) getSherlockActivity()).setBackground(mInterface.getAudioId(),
mInterface.getAlbumId());
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/MusicPlaybackFragment.java
|
Java
|
gpl3
| 15,302
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import java.io.File;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.app.BaseActivity;
import org.yammp.app.MediaPlayerActivity;
import org.yammp.app.TrackBrowserActivity;
import org.yammp.dialog.DeleteDialogFragment;
import org.yammp.util.LazyImageLoader;
import org.yammp.util.MediaUtils;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class AlbumFragment extends SherlockFragment implements Constants, OnItemClickListener,
OnItemSelectedListener, OnScrollListener, LoaderCallbacks<Cursor> {
private AlbumsAdapter mAdapter;
private GridView mGridView;
private Cursor mCursor;
private int mSelectedPosition;
private long mSelectedId;
private String mCurrentAlbumName, mCurrentArtistNameForAlbum;
private int mIdIdx, mAlbumIdx, mArtistIdx, mArtIdx;
private LazyImageLoader mImageLoader;
private BroadcastReceiver mMediaStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mGridView.invalidateViews();
}
};
MediaUtils mUtils;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
private boolean mScrollStopped = true;
private int mFirstVisible = 0;
public AlbumFragment() {
}
public AlbumFragment(Bundle args) {
setArguments(args);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
mImageLoader = ((YAMMPApplication) getSherlockActivity().getApplication())
.getLazyImageLoader();
mAdapter = new AlbumsAdapter(getSherlockActivity(), R.layout.album_grid_item, null,
new String[] {}, new int[] {}, 0);
View fragmentView = getView();
mGridView = (GridView) fragmentView.findViewById(android.R.id.list);
mGridView.setAdapter(mAdapter);
mGridView.setOnItemClickListener(this);
mGridView.setOnItemSelectedListener(this);
mGridView.setOnCreateContextMenuListener(this);
mGridView.setOnScrollListener(this);
registerForContextMenu(mGridView);
getLoaderManager().initLoader(0, null, this);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getGroupId() == hashCode()) {
if (mCursor == null) return true;
switch (item.getItemId()) {
case PLAY_SELECTION:
int position = mSelectedPosition;
long[] list = mUtils.getSongListForAlbum(mSelectedId);
mUtils.playAll(list, position);
return true;
case DELETE_ITEMS:
DeleteDialogFragment
.getInstance(false, mSelectedId, DeleteDialogFragment.ALBUM).show(
getFragmentManager(), "dialog");
return true;
case DELETE_LYRICS:
DeleteDialogFragment
.getInstance(false, mSelectedId, DeleteDialogFragment.ALBUM).show(
getFragmentManager(), "dialog");
return true;
case SEARCH:
doSearch();
return true;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
if (mCursor == null) return;
menu.add(hashCode(), PLAY_SELECTION, 0, R.string.play_selection);
menu.add(hashCode(), DELETE_ITEMS, 0, R.string.delete_music);
menu.add(hashCode(), DELETE_LYRICS, 0, R.string.delete_lyrics);
AdapterContextMenuInfo adapterinfo = (AdapterContextMenuInfo) info;
mSelectedPosition = adapterinfo.position;
mCursor.moveToPosition(mSelectedPosition);
try {
mSelectedId = mCursor.getLong(mIdIdx);
} catch (IllegalArgumentException ex) {
mSelectedId = adapterinfo.id;
}
mCurrentArtistNameForAlbum = mCursor.getString(mArtistIdx);
mCurrentAlbumName = mCursor.getString(mAlbumIdx);
if (mCurrentAlbumName != null && !MediaStore.UNKNOWN_STRING.equals(mCurrentAlbumName)) {
menu.add(hashCode(), SEARCH, 0, android.R.string.search_go);
menu.setHeaderTitle(mCurrentAlbumName);
} else {
menu.setHeaderTitle(R.string.unknown_album);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] cols = new String[] { Audio.Albums._ID, Audio.Albums.ALBUM, Audio.Albums.ARTIST,
Audio.Albums.ALBUM_ART };
Uri uri = Audio.Albums.EXTERNAL_CONTENT_URI;
return new CursorLoader(getSherlockActivity(), uri, cols, null, null,
Audio.Albums.DEFAULT_SORT_ORDER);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.albums_browser, container, false);
}
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
showDetails(position, id);
}
@Override
public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {
((MediaPlayerActivity) getSherlockActivity()).setBackground(0, id);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.changeCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
getSherlockActivity().finish();
return;
}
mCursor = data;
mIdIdx = data.getColumnIndexOrThrow(Audio.Albums._ID);
mAlbumIdx = data.getColumnIndexOrThrow(Audio.Albums.ALBUM);
mArtistIdx = data.getColumnIndexOrThrow(Audio.Albums.ARTIST);
mArtIdx = data.getColumnIndexOrThrow(Audio.Albums.ALBUM_ART);
mAdapter.changeCursor(data);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
super.onSaveInstanceState(outState);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
long item_id = view.getItemIdAtPosition(firstVisibleItem);
((BaseActivity) getSherlockActivity()).setBackground(0, item_id);
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_META_CHANGED);
filter.addAction(BROADCAST_QUEUE_CHANGED);
getSherlockActivity().registerReceiver(mMediaStatusReceiver, filter);
}
@Override
public void onStop() {
getSherlockActivity().unregisterReceiver(mMediaStatusReceiver);
super.onStop();
}
private void doSearch() {
CharSequence title = null;
String query = null;
Intent i = new Intent();
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
title = mCurrentAlbumName;
if (MediaStore.UNKNOWN_STRING.equals(mCurrentArtistNameForAlbum)) {
query = mCurrentAlbumName;
} else {
query = mCurrentArtistNameForAlbum + " " + mCurrentAlbumName;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, mCurrentArtistNameForAlbum);
}
if (MediaStore.UNKNOWN_STRING.equals(mCurrentAlbumName)) {
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, mCurrentAlbumName);
}
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
title = getString(R.string.mediasearch, title);
i.putExtra(SearchManager.QUERY, query);
startActivity(Intent.createChooser(i, title));
}
private void showDetails(int index, long id) {
Bundle bundle = new Bundle();
bundle.putString(INTENT_KEY_TYPE, MediaStore.Audio.Albums.CONTENT_TYPE);
bundle.putLong(Audio.Albums._ID, id);
View detailsFrame = getSherlockActivity().findViewById(R.id.frame_details);
boolean mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE
&& getResources().getBoolean(R.bool.dual_pane);
if (mDualPane) {
mGridView.setSelection(index);
TrackFragment fragment = new TrackFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClass(getSherlockActivity(), TrackBrowserActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class AlbumsAdapter extends SimpleCursorAdapter {
private AlbumsAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to,
int flags) {
super(context, layout, cursor, from, to, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewholder = (ViewHolder) view.getTag();
if (viewholder == null) return;
String album_name = cursor.getString(mAlbumIdx);
if (album_name == null || MediaStore.UNKNOWN_STRING.equals(album_name)) {
viewholder.album_name.setText(R.string.unknown_album);
} else {
viewholder.album_name.setText(album_name);
}
String artist_name = cursor.getString(mArtistIdx);
if (artist_name == null || MediaStore.UNKNOWN_STRING.equals(artist_name)) {
viewholder.artist_name.setText(R.string.unknown_artist);
} else {
viewholder.artist_name.setText(artist_name);
}
// We don't actually need the path to the thumbnail file,
// we just use it to see if there is album art or not
long aid = cursor.getLong(mIdIdx);
long currentalbumid = mUtils.getCurrentAlbumId();
if (currentalbumid == aid) {
viewholder.album_name.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.ic_indicator_nowplaying_small, 0);
} else {
viewholder.album_name.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
String art = cursor.getString(mArtIdx);
if (art != null && art.toString().length() > 0) {
mImageLoader.displayImage(new File(art), viewholder.album_art);
} else {
viewholder.album_art.setImageResource(R.drawable.ic_mp_albumart_unknown);
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = super.newView(context, cursor, parent);
ViewHolder viewholder = new ViewHolder(view);
view.setTag(viewholder);
return view;
}
private class ViewHolder {
TextView album_name;
TextView artist_name;
ImageView album_art;
public ViewHolder(View view) {
album_name = (TextView) view.findViewById(R.id.album_name);
artist_name = (TextView) view.findViewById(R.id.artist_name);
album_art = (ImageView) view.findViewById(R.id.album_art);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/AlbumFragment.java
|
Java
|
gpl3
| 12,590
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
public class QueryFragment extends SherlockListFragment implements Constants,
LoaderCallbacks<Cursor> {
private QueryListAdapter mAdapter;
private String mFilterString = "";
private Cursor mQueryCursor;
private ListView mTrackList;
private MediaUtils mUtils;
public QueryFragment() {
}
public QueryFragment(Bundle arguments) {
setArguments(arguments);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
mAdapter = new QueryListAdapter(getActivity(), R.layout.query_list_item, null,
new String[] {}, new int[] {}, 0);
setListAdapter(mAdapter);
getListView().setOnCreateContextMenuListener(this);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, getArguments(), this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String filter = "";
if (args != null) {
filter = args.getString(INTENT_KEY_FILTER) != null ? args.getString(INTENT_KEY_FILTER)
: "";
}
StringBuilder where = new StringBuilder();
where.append(Audio.Media.IS_MUSIC + "=1");
where.append(" AND " + Audio.Media.TITLE + " != ''");
String[] cols = new String[] { BaseColumns._ID, Audio.Media.MIME_TYPE,
Audio.Artists.ARTIST, Audio.Albums.ALBUM, Audio.Media.TITLE, "data1", "data2" };
Uri uri = Uri.parse("content://media/external/audio/search/fancy/" + Uri.encode(filter));
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), uri, cols, where.toString(), null, null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.query_browser, container, false);
return view;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Dialog doesn't allow us to wait for a result, so we need to store
// the info we need for when the dialog posts its result
mQueryCursor.moveToPosition(position);
if (mQueryCursor.isBeforeFirst() || mQueryCursor.isAfterLast()) return;
String selectedType = mQueryCursor.getString(mQueryCursor
.getColumnIndexOrThrow(Audio.Media.MIME_TYPE));
if ("artist".equals(selectedType)) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/album");
intent.putExtra("artist", Long.valueOf(id).toString());
startActivity(intent);
} else if ("album".equals(selectedType)) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
intent.putExtra("album", Long.valueOf(id).toString());
startActivity(intent);
} else if (position >= 0 && id >= 0) {
long[] list = new long[] { id };
mUtils.playAll(list, 0);
} else {
Log.e("QueryBrowser", "invalid position/id: " + position + "/" + id);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
getActivity().finish();
return;
}
mQueryCursor = data;
mAdapter.swapCursor(data);
}
public void onServiceConnected(ComponentName name, IBinder service) {
Bundle bundle = getArguments();
String action = bundle != null ? bundle.getString(INTENT_KEY_ACTION) : null;
String data = bundle != null ? bundle.getString(INTENT_KEY_DATA) : null;
if (Intent.ACTION_VIEW.equals(action)) {
// this is something we got from the search bar
Uri uri = Uri.parse(data);
if (data.startsWith("content://media/external/audio/media/")) {
// This is a specific file
String id = uri.getLastPathSegment();
long[] list = new long[] { Long.valueOf(id) };
mUtils.playAll(list, 0);
getActivity().finish();
return;
} else if (data.startsWith("content://media/external/audio/albums/")) {
// This is an album, show the songs on it
Intent i = new Intent(Intent.ACTION_PICK);
i.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
i.putExtra("album", uri.getLastPathSegment());
startActivity(i);
return;
} else if (data.startsWith("content://media/external/audio/artists/")) {
// This is an artist, show the albums for that artist
Intent i = new Intent(Intent.ACTION_PICK);
i.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/album");
i.putExtra("artist", uri.getLastPathSegment());
startActivity(i);
return;
}
}
mFilterString = bundle != null ? bundle.getString(SearchManager.QUERY) : null;
if (MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)) {
String focus = bundle != null ? bundle.getString(MediaStore.EXTRA_MEDIA_FOCUS) : null;
String artist = bundle != null ? bundle.getString(MediaStore.EXTRA_MEDIA_ARTIST) : null;
String album = bundle != null ? bundle.getString(MediaStore.EXTRA_MEDIA_ALBUM) : null;
String title = bundle != null ? bundle.getString(MediaStore.EXTRA_MEDIA_TITLE) : null;
if (focus != null) {
if (focus.startsWith("audio/") && title != null) {
mFilterString = title;
} else if (Audio.Albums.ENTRY_CONTENT_TYPE.equals(focus)) {
if (album != null) {
mFilterString = album;
if (artist != null) {
mFilterString = mFilterString + " " + artist;
}
}
} else if (Audio.Artists.ENTRY_CONTENT_TYPE.equals(focus)) {
if (artist != null) {
mFilterString = artist;
}
}
}
}
mTrackList = getListView();
mTrackList.setTextFilterEnabled(true);
}
public void onServiceDisconnected(ComponentName name) {
}
private class QueryListAdapter extends SimpleCursorAdapter {
private QueryListAdapter(Context context, int layout, Cursor cursor, String[] from,
int[] to, int flags) {
super(context, layout, cursor, from, to, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewholder = (ViewHolder) view.getTag();
String mimetype = cursor.getString(cursor.getColumnIndexOrThrow(Audio.Media.MIME_TYPE));
if (mimetype == null) {
mimetype = "audio/";
}
if (mimetype.equals("artist")) {
viewholder.result_icon.setImageResource(R.drawable.ic_mp_list_artist);
String name = cursor.getString(cursor.getColumnIndexOrThrow(Audio.Artists.ARTIST));
String displayname = name;
boolean isunknown = false;
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
displayname = context.getString(R.string.unknown_artist);
isunknown = true;
}
viewholder.query_result.setText(displayname);
int numalbums = cursor.getInt(cursor.getColumnIndexOrThrow("data1"));
int numsongs = cursor.getInt(cursor.getColumnIndexOrThrow("data2"));
String songs_albums = mUtils.makeAlbumsSongsLabel(numalbums, numsongs, isunknown);
viewholder.result_summary.setText(songs_albums);
} else if (mimetype.equals("album")) {
viewholder.result_icon.setImageResource(R.drawable.ic_mp_list_album);
String name = cursor.getString(cursor.getColumnIndexOrThrow(Audio.Albums.ALBUM));
String displayname = name;
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
displayname = context.getString(R.string.unknown_album);
}
viewholder.query_result.setText(displayname);
name = cursor.getString(cursor.getColumnIndexOrThrow(Audio.Artists.ARTIST));
displayname = name;
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
displayname = context.getString(R.string.unknown_artist);
}
viewholder.result_summary.setText(displayname);
} else if (mimetype.startsWith("audio/") || mimetype.equals("application/ogg")
|| mimetype.equals("application/x-ogg")) {
viewholder.result_icon.setImageResource(R.drawable.ic_mp_list_song);
String name = cursor.getString(cursor.getColumnIndexOrThrow(Audio.Media.TITLE));
viewholder.query_result.setText(name);
String displayname = cursor.getString(cursor
.getColumnIndexOrThrow(Audio.Artists.ARTIST));
if (displayname == null || displayname.equals(MediaStore.UNKNOWN_STRING)) {
displayname = context.getString(R.string.unknown_artist);
}
name = cursor.getString(cursor.getColumnIndexOrThrow(Audio.Albums.ALBUM));
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
name = context.getString(R.string.unknown_album);
}
viewholder.result_summary.setText(displayname + " - " + name);
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = super.newView(context, cursor, parent);
ViewHolder viewholder = new ViewHolder(view);
view.setTag(viewholder);
return view;
}
private class ViewHolder {
ImageView result_icon;
TextView query_result;
TextView result_summary;
public ViewHolder(View view) {
result_icon = (ImageView) view.findViewById(R.id.icon);
query_result = (TextView) view.findViewById(R.id.name);
result_summary = (TextView) view.findViewById(R.id.summary);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/QueryFragment.java
|
Java
|
gpl3
| 11,229
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.fragment;
import org.yammp.R;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Video;
import android.view.View;
import android.widget.MediaController;
import android.widget.VideoView;
public class MovieViewControl implements MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
@SuppressWarnings("unused")
private static final String TAG = "MovieViewControl";
private static final int ONE_MINUTE = 60 * 1000;
private static final int TWO_MINUTES = 2 * ONE_MINUTE;
private static final int FIVE_MINUTES = 5 * ONE_MINUTE;
// Copied from MediaPlaybackService in the Music Player app. Should be
// public, but isn't.
private static final String SERVICECMD = "com.android.music.musicservicecommand";
private static final String CMDNAME = "command";
private static final String CMDPAUSE = "pause";
private final VideoView mVideoView;
private final View mProgressView;
private final Uri mUri;
private final ContentResolver mContentResolver;
// State maintained for proper onPause/OnResume behaviour.
private int mPositionWhenPaused = -1;
private boolean mWasPlayingWhenPaused = false;
private MediaController mMediaController;
Handler mHandler = new Handler();
Runnable mPlayingChecker = new Runnable() {
@Override
public void run() {
if (mVideoView.isPlaying()) {
mProgressView.setVisibility(View.GONE);
} else {
mHandler.postDelayed(mPlayingChecker, 250);
}
}
};
public MovieViewControl(View view, Context context, Uri uri) {
mContentResolver = context.getContentResolver();
mVideoView = (VideoView) view.findViewById(R.id.surface_view);
mProgressView = view.findViewById(R.id.progress_indicator);
mUri = uri;
/*
* For streams that we expect to be slow to start up, show a progress
* spinner until playback starts.
*/
String scheme = mUri.getScheme();
if ("http".equalsIgnoreCase(scheme) || "rtsp".equalsIgnoreCase(scheme)) {
mHandler.postDelayed(mPlayingChecker, 250);
} else {
mProgressView.setVisibility(View.GONE);
}
mVideoView.setOnErrorListener(this);
mVideoView.setOnCompletionListener(this);
mVideoView.setVideoURI(mUri);
mMediaController = new MediaController(context);
mVideoView.setMediaController(mMediaController);
/* make the video view handle keys for seeking and pausing */
mVideoView.requestFocus();
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDPAUSE);
context.sendBroadcast(i);
final Integer bookmark = getBookmark();
if (bookmark != null) {
mVideoView.seekTo(bookmark);
mVideoView.start();
} else {
mVideoView.start();
}
}
public void onCompletion() {
}
@Override
public void onCompletion(MediaPlayer mp) {
onCompletion();
}
@Override
public boolean onError(MediaPlayer player, int arg1, int arg2) {
mHandler.removeCallbacksAndMessages(null);
mProgressView.setVisibility(View.GONE);
return false;
}
public void onPause() {
mHandler.removeCallbacksAndMessages(null);
setBookmark(mVideoView.getCurrentPosition());
mPositionWhenPaused = mVideoView.getCurrentPosition();
mWasPlayingWhenPaused = mVideoView.isPlaying();
mVideoView.stopPlayback();
}
public void onResume() {
if (mPositionWhenPaused >= 0) {
mVideoView.setVideoURI(mUri);
mVideoView.seekTo(mPositionWhenPaused);
mPositionWhenPaused = -1;
if (mWasPlayingWhenPaused) {
mMediaController.show(0);
}
}
}
private Integer getBookmark() {
if (!uriSupportsBookmarks(mUri)) return null;
String[] projection = new String[] { Video.VideoColumns.DURATION,
Video.VideoColumns.BOOKMARK };
try {
Cursor cursor = mContentResolver.query(mUri, projection, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int duration = getCursorInteger(cursor, 0);
int bookmark = getCursorInteger(cursor, 1);
if (bookmark < TWO_MINUTES || duration < FIVE_MINUTES
|| bookmark > duration - ONE_MINUTE) return null;
return Integer.valueOf(bookmark);
}
} finally {
cursor.close();
}
}
} catch (SQLiteException e) {
// ignore
}
return null;
}
private void setBookmark(int bookmark) {
if (!uriSupportsBookmarks(mUri)) return;
ContentValues values = new ContentValues();
values.put(Video.VideoColumns.BOOKMARK, Integer.toString(bookmark));
try {
mContentResolver.update(mUri, values, null, null);
} catch (SecurityException ex) {
// Ignore, can happen if we try to set the bookmark on a read-only
// resource such as a video attached to GMail.
} catch (SQLiteException e) {
/*
* ignore. can happen if the content doesn't support a bookmark
* column.
*/
} catch (UnsupportedOperationException e) {
/* ignore. can happen if the external volume is already detached. */
}
}
private static int getCursorInteger(Cursor cursor, int index) {
try {
return cursor.getInt(index);
} catch (SQLiteException e) {
return 0;
} catch (NumberFormatException e) {
return 0;
}
}
private static boolean uriSupportsBookmarks(Uri uri) {
String scheme = uri.getScheme();
String authority = uri.getAuthority();
return "content".equalsIgnoreCase(scheme)
&& MediaStore.AUTHORITY.equalsIgnoreCase(authority);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/MovieViewControl.java
|
Java
|
gpl3
| 6,202
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.fragment;
import org.yammp.R;
import com.actionbarsherlock.app.SherlockActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
/**
* This activity plays a video from a specified URI.
*/
public class VideoPlaybackActivity extends SherlockActivity {
private MovieViewControl mControl;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.movie_view);
View rootView = findViewById(R.id.root);
Intent intent = getIntent();
mControl = new MovieViewControl(rootView, this, intent.getData()) {
@Override
public void onCompletion() {
finish();
}
};
if (intent.hasExtra(MediaStore.EXTRA_SCREEN_ORIENTATION)) {
int orientation = intent.getIntExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
if (orientation != getRequestedOrientation()) {
setRequestedOrientation(orientation);
}
}
}
@Override
public void onPause() {
mControl.onPause();
super.onPause();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) mControl.onResume();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/VideoPlaybackActivity.java
|
Java
|
gpl3
| 1,857
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.app.TrackBrowserActivity;
import org.yammp.widget.SeparatedListAdapter;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class PlaylistFragment extends ListFragment implements LoaderCallbacks<Cursor>, Constants {
private PlaylistsAdapter mPlaylistsAdapter;
private SmartPlaylistsAdapter mSmartPlaylistsAdapter;
private SeparatedListAdapter mAdapter;
private Long[] mSmartPlaylists = new Long[] { PLAYLIST_FAVORITES, PLAYLIST_RECENTLY_ADDED,
PLAYLIST_PODCASTS };
private int mIdIdx, mNameIdx;
public PlaylistFragment() {
}
public PlaylistFragment(Bundle args) {
setArguments(args);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mPlaylistsAdapter = new PlaylistsAdapter(getActivity(), null, false);
mSmartPlaylistsAdapter = new SmartPlaylistsAdapter(getActivity(),
R.layout.playlist_list_item, mSmartPlaylists);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] cols = new String[] { MediaStore.Audio.Playlists._ID,
MediaStore.Audio.Playlists.NAME };
Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI;
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Playlists.NAME + " != '" + PLAYLIST_NAME_FAVORITES + "'");
for (String hide_playlist : HIDE_PLAYLISTS) {
where.append(" AND " + MediaStore.Audio.Playlists.NAME + " != '" + hide_playlist + "'");
}
return new CursorLoader(getActivity(), uri, cols, where.toString(), null,
MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.playlists_browser, container, false);
return view;
}
@Override
public void onListItemClick(ListView listview, View view, int position, long id) {
long playlist_id = (Long) ((Object[]) view.getTag())[1];
showDetails(position, playlist_id);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mPlaylistsAdapter.swapCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
getActivity().finish();
return;
}
mIdIdx = data.getColumnIndexOrThrow(MediaStore.Audio.Playlists._ID);
mNameIdx = data.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME);
mPlaylistsAdapter.changeCursor(data);
mAdapter = new SeparatedListAdapter(getActivity());
mAdapter.addSection(getString(R.string.my_playlists), mPlaylistsAdapter);
mAdapter.addSection(getString(R.string.smart_playlists), mSmartPlaylistsAdapter);
setListAdapter(mAdapter);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
super.onSaveInstanceState(outState);
}
private void showDetails(int index, long id) {
View detailsFrame = getActivity().findViewById(R.id.frame_details);
boolean mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
long playlist_id = id;
Bundle bundle = new Bundle();
bundle.putString(INTENT_KEY_TYPE, MediaStore.Audio.Playlists.CONTENT_TYPE);
bundle.putLong(MediaStore.Audio.Playlists._ID, playlist_id);
if (mDualPane) {
TrackFragment fragment = new TrackFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
} else {
Intent intent = new Intent(getActivity(), TrackBrowserActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class PlaylistsAdapter extends CursorAdapter {
private PlaylistsAdapter(Context context, Cursor cursor, boolean autoRequery) {
super(context, cursor, autoRequery);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewholder = (ViewHolder) ((Object[]) view.getTag())[0];
String playlist_name = cursor.getString(mNameIdx);
viewholder.playlist_name.setText(playlist_name);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.playlist_list_item, null);
ViewHolder viewholder = new ViewHolder(view);
view.setTag(new Object[] { viewholder, cursor.getLong(mIdIdx) });
return view;
}
private class ViewHolder {
TextView playlist_name;
public ViewHolder(View view) {
playlist_name = (TextView) view.findViewById(R.id.playlist_name);
}
}
}
private class SmartPlaylistsAdapter extends ArrayAdapter<Long> {
Long[] playlists = new Long[] {};
private SmartPlaylistsAdapter(Context context, int resid, Long[] playlists) {
super(context, resid, playlists);
this.playlists = playlists;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder viewholder = view != null ? (ViewHolder) ((Object[]) view.getTag())[0]
: null;
if (viewholder == null) {
view = getLayoutInflater(getArguments()).inflate(R.layout.playlist_list_item, null);
viewholder = new ViewHolder(view);
view.setTag(new Object[] { viewholder, playlists[position] });
}
switch (playlists[position].intValue()) {
case (int) PLAYLIST_FAVORITES:
viewholder.playlist_name.setText(R.string.favorites);
viewholder.playlist_name.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_mp_list_playlist_favorite, 0, 0, 0);
break;
case (int) PLAYLIST_RECENTLY_ADDED:
viewholder.playlist_name.setText(R.string.recently_added);
viewholder.playlist_name.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_mp_list_playlist_recent, 0, 0, 0);
break;
case (int) PLAYLIST_PODCASTS:
viewholder.playlist_name.setText(R.string.podcasts);
viewholder.playlist_name.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_mp_list_playlist_podcast, 0, 0, 0);
break;
}
return view;
}
private class ViewHolder {
TextView playlist_name;
public ViewHolder(View view) {
playlist_name = (TextView) view.findViewById(R.id.playlist_name);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/PlaylistFragment.java
|
Java
|
gpl3
| 7,908
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import org.yammp.util.PreferencesEditor;
import org.yammp.widget.TouchInterceptor;
import org.yammp.widget.TouchInterceptor.OnDropListener;
import org.yammp.widget.TouchInterceptor.OnRemoveListener;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.Genres;
import android.provider.MediaStore.Audio.Playlists;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
public class TrackFragment extends SherlockListFragment implements LoaderCallbacks<Cursor>,
Constants, OnDropListener, OnRemoveListener {
private TracksAdapter mAdapter;
private Cursor mCursor;
private int mSelectedPosition;
private long mSelectedId;
private String mCurrentTrackName, mCurrentAlbumName, mCurrentArtistNameForAlbum;
private int mIdIdx, mTrackIdx, mAlbumIdx, mArtistIdx, mDurationIdx;
private boolean mEditMode = false;
private ListView mListView;
long mPlaylistId = -1;
private BroadcastReceiver mMediaStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (getListView() != null) {
getListView().invalidateViews();
}
}
};
private MediaUtils mUtils;
public TrackFragment() {
}
public TrackFragment(Bundle arguments) {
setArguments(arguments);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
if (getArguments() != null) {
String mimetype = getArguments().getString(INTENT_KEY_TYPE);
if (Audio.Playlists.CONTENT_TYPE.equals(mimetype)) {
mPlaylistId = getArguments().getLong(Audio.Playlists._ID);
switch ((int) mPlaylistId) {
case (int) PLAYLIST_QUEUE:
mEditMode = true;
break;
case (int) PLAYLIST_FAVORITES:
mEditMode = true;
break;
default:
if (mPlaylistId > 0) {
mEditMode = true;
}
break;
}
}
}
mAdapter = new TracksAdapter(getActivity(), mEditMode ? R.layout.track_list_item_edit_mode
: R.layout.track_list_item, null, new String[] {}, new int[] {}, 0);
setListAdapter(mAdapter);
mListView = getListView();
mListView.setOnCreateContextMenuListener(this);
getLoaderManager().initLoader(0, null, this);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (mCursor == null) return false;
Intent intent;
switch (item.getItemId()) {
case PLAY_SELECTION:
int position = mSelectedPosition;
if (mPlaylistId == PLAYLIST_QUEUE) {
mUtils.setQueuePosition(position);
return true;
}
mUtils.playAll(mCursor, position);
return true;
case DELETE_ITEMS:
intent = new Intent(INTENT_DELETE_ITEMS);
Bundle bundle = new Bundle();
bundle.putString(
INTENT_KEY_PATH,
Uri.withAppendedPath(Audio.Media.EXTERNAL_CONTENT_URI,
Uri.encode(String.valueOf(mSelectedId))).toString());
intent.putExtras(bundle);
startActivity(intent);
return true;
case SEARCH:
doSearch();
return true;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
if (mCursor == null) return;
getActivity().getMenuInflater().inflate(R.menu.music_browser_item, menu);
AdapterContextMenuInfo adapterinfo = (AdapterContextMenuInfo) info;
mSelectedPosition = adapterinfo.position;
mCursor.moveToPosition(mSelectedPosition);
try {
mSelectedId = mCursor.getLong(mIdIdx);
} catch (IllegalArgumentException ex) {
mSelectedId = adapterinfo.id;
}
mCurrentAlbumName = mCursor.getString(mAlbumIdx);
mCurrentArtistNameForAlbum = mCursor.getString(mArtistIdx);
mCurrentTrackName = mCursor.getString(mTrackIdx);
menu.setHeaderTitle(mCurrentTrackName);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] cols = new String[] { Audio.Media._ID, Audio.Media.TITLE, Audio.Media.DATA,
Audio.Media.ALBUM, Audio.Media.ARTIST, Audio.Media.ARTIST_ID, Audio.Media.DURATION };
StringBuilder where = new StringBuilder();
String sort_order = Audio.Media.TITLE;
where.append(Audio.Media.IS_MUSIC + "=1");
where.append(" AND " + Audio.Media.TITLE + " != ''");
Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
if (getArguments() != null) {
String mimetype = getArguments().getString(INTENT_KEY_TYPE);
if (Audio.Playlists.CONTENT_TYPE.equals(mimetype)) {
where = new StringBuilder();
where.append(Playlists.Members.IS_MUSIC + "=1");
where.append(" AND " + Playlists.Members.TITLE + " != ''");
switch ((int) mPlaylistId) {
case (int) PLAYLIST_QUEUE:
uri = Audio.Media.EXTERNAL_CONTENT_URI;
long[] mNowPlaying = mUtils.getQueue();
if (mNowPlaying.length == 0) return null;
where = new StringBuilder();
where.append(MediaStore.Audio.Media._ID + " IN (");
if (mNowPlaying == null || mNowPlaying.length <= 0) return null;
for (long queue_id : mNowPlaying) {
where.append(queue_id + ",");
}
where.deleteCharAt(where.length() - 1);
where.append(")");
sort_order = null;
break;
case (int) PLAYLIST_FAVORITES:
long favorites_id = mUtils.getFavoritesId();
cols = new String[] { Playlists.Members._ID, Playlists.Members.AUDIO_ID,
Playlists.Members.TITLE, Playlists.Members.ALBUM,
Playlists.Members.ARTIST, Playlists.Members.DURATION };
uri = Playlists.Members.getContentUri(EXTERNAL_VOLUME, favorites_id);
sort_order = Playlists.Members.DEFAULT_SORT_ORDER;
break;
case (int) PLAYLIST_RECENTLY_ADDED:
int X = new PreferencesEditor(getActivity()).getIntPref(PREF_KEY_NUMWEEKS,
2) * 3600 * 24 * 7;
where = new StringBuilder();
where.append(Audio.Media.TITLE + " != ''");
where.append(" AND " + Audio.Media.IS_MUSIC + "=1");
where.append(" AND " + MediaStore.MediaColumns.DATE_ADDED + ">"
+ (System.currentTimeMillis() / 1000 - X));
sort_order = Audio.Media.DATE_ADDED;
break;
case (int) PLAYLIST_PODCASTS:
where = new StringBuilder();
where.append(Audio.Media.TITLE + " != ''");
where.append(" AND " + Audio.Media.IS_PODCAST + "=1");
sort_order = Audio.Media.DATE_ADDED;
break;
default:
if (id < 0) return null;
cols = new String[] { Playlists.Members._ID, Playlists.Members.AUDIO_ID,
Playlists.Members.TITLE, Playlists.Members.ALBUM,
Playlists.Members.ARTIST, Playlists.Members.DURATION };
uri = Playlists.Members.getContentUri(EXTERNAL_VOLUME, mPlaylistId);
sort_order = Playlists.Members.DEFAULT_SORT_ORDER;
break;
}
} else if (Audio.Genres.CONTENT_TYPE.equals(mimetype)) {
long genre_id = getArguments().getLong(Audio.Genres._ID);
uri = Genres.Members.getContentUri(EXTERNAL_VOLUME, genre_id);
cols = new String[] { Genres.Members._ID, Genres.Members.TITLE,
Genres.Members.ALBUM, Genres.Members.ARTIST, Genres.Members.DURATION };
where = new StringBuilder();
where.append(Genres.Members.IS_MUSIC + "=1");
where.append(" AND " + Genres.Members.TITLE + " != ''");
sort_order = Genres.Members.DEFAULT_SORT_ORDER;
} else {
if (Audio.Albums.CONTENT_TYPE.equals(mimetype)) {
sort_order = Audio.Media.TRACK;
long album_id = getArguments().getLong(Audio.Albums._ID);
where.append(" AND " + Audio.Media.ALBUM_ID + "=" + album_id);
} else if (Audio.Artists.CONTENT_TYPE.equals(mimetype)) {
sort_order = Audio.Media.TITLE;
long artist_id = getArguments().getLong(Audio.Artists._ID);
where.append(" AND " + Audio.Media.ARTIST_ID + "=" + artist_id);
}
}
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), uri, cols, where.toString(), null, sort_order);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tracks_browser, container, false);
return view;
}
@Override
public void onDrop(int from, int to) {
if (mPlaylistId >= 0) {
Playlists.Members.moveItem(getActivity().getContentResolver(), mPlaylistId, from, to);
} else if (mPlaylistId == PLAYLIST_QUEUE) {
mUtils.moveQueueItem(from, to);
reloadQueueCursor();
} else if (mPlaylistId == PLAYLIST_FAVORITES) {
long favorites_id = mUtils.getFavoritesId();
Playlists.Members.moveItem(getActivity().getContentResolver(), favorites_id, from, to);
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (mCursor == null || mCursor.getCount() == 0) return;
// When selecting a track from the queue, just jump there instead of
// reloading the queue. This is both faster, and prevents accidentally
// dropping out of party shuffle.
if (mPlaylistId == PLAYLIST_QUEUE) {
mUtils.setQueueId(id);
return;
}
mUtils.playAll(mCursor, position);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursor = null;
mAdapter.changeCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
getActivity().finish();
return;
}
mCursor = data;
if (getArguments() != null
&& Playlists.CONTENT_TYPE.equals(getArguments().getString(INTENT_KEY_TYPE))
&& (getArguments().getLong(Playlists._ID) >= 0 || getArguments().getLong(
Playlists._ID) == PLAYLIST_FAVORITES)) {
mIdIdx = data.getColumnIndexOrThrow(Playlists.Members.AUDIO_ID);
mTrackIdx = data.getColumnIndexOrThrow(Playlists.Members.TITLE);
mAlbumIdx = data.getColumnIndexOrThrow(Playlists.Members.ALBUM);
mArtistIdx = data.getColumnIndexOrThrow(Playlists.Members.ARTIST);
mDurationIdx = data.getColumnIndexOrThrow(Playlists.Members.DURATION);
} else if (getArguments() != null
&& Genres.CONTENT_TYPE.equals(getArguments().getString(INTENT_KEY_TYPE))) {
mIdIdx = data.getColumnIndexOrThrow(Genres.Members._ID);
mTrackIdx = data.getColumnIndexOrThrow(Genres.Members.TITLE);
mAlbumIdx = data.getColumnIndexOrThrow(Genres.Members.ALBUM);
mArtistIdx = data.getColumnIndexOrThrow(Genres.Members.ARTIST);
mDurationIdx = data.getColumnIndexOrThrow(Genres.Members.DURATION);
} else {
mIdIdx = data.getColumnIndexOrThrow(Audio.Media._ID);
mTrackIdx = data.getColumnIndexOrThrow(Audio.Media.TITLE);
mAlbumIdx = data.getColumnIndexOrThrow(Audio.Media.ALBUM);
mArtistIdx = data.getColumnIndexOrThrow(Audio.Media.ARTIST);
mDurationIdx = data.getColumnIndexOrThrow(Audio.Media.DURATION);
}
mAdapter.changeCursor(data);
if (mEditMode) {
((TouchInterceptor) mListView).setDropListener(this);
((TouchInterceptor) mListView).setRemoveListener(this);
mListView.setDivider(null);
mListView.setSelector(R.drawable.list_selector_background);
}
}
@Override
public void onRemove(int which) {
removePlaylistItem(which);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
super.onSaveInstanceState(outState);
}
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_META_CHANGED);
filter.addAction(BROADCAST_QUEUE_CHANGED);
getActivity().registerReceiver(mMediaStatusReceiver, filter);
}
@Override
public void onStop() {
getActivity().unregisterReceiver(mMediaStatusReceiver);
super.onStop();
}
private void doSearch() {
CharSequence title = null;
String query = null;
Intent i = new Intent();
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
title = mCurrentTrackName;
if (MediaStore.UNKNOWN_STRING.equals(mCurrentArtistNameForAlbum)) {
query = mCurrentTrackName;
} else {
query = mCurrentArtistNameForAlbum + " " + mCurrentTrackName;
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, mCurrentArtistNameForAlbum);
}
if (MediaStore.UNKNOWN_STRING.equals(mCurrentAlbumName)) {
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, mCurrentAlbumName);
}
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
title = getString(R.string.mediasearch, title);
i.putExtra(SearchManager.QUERY, query);
startActivity(Intent.createChooser(i, title));
}
private void reloadQueueCursor() {
if (mPlaylistId == PLAYLIST_QUEUE) {
String[] cols = new String[] { Audio.Media._ID, Audio.Media.TITLE, Audio.Media.DATA,
Audio.Media.ALBUM, Audio.Media.ARTIST, Audio.Media.ARTIST_ID,
Audio.Media.DURATION };
StringBuilder where = new StringBuilder();
where.append(Playlists.Members.IS_MUSIC + "=1");
where.append(" AND " + Playlists.Members.TITLE + " != ''");
Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
long[] mNowPlaying = mUtils.getQueue();
if (mNowPlaying.length == 0) {
// return;
}
where = new StringBuilder();
where.append(MediaStore.Audio.Media._ID + " IN (");
for (int i = 0; i < mNowPlaying.length; i++) {
where.append(mNowPlaying[i]);
if (i < mNowPlaying.length - 1) {
where.append(",");
}
}
where.append(")");
mCursor = mUtils.query(uri, cols, where.toString(), null, null);
mAdapter.changeCursor(mCursor);
}
}
private void removePlaylistItem(int which) {
mCursor.moveToPosition(which);
long id = mCursor.getLong(mIdIdx);
if (mPlaylistId >= 0) {
Uri uri = Playlists.Members.getContentUri("external", mPlaylistId);
getActivity().getContentResolver().delete(uri, Playlists.Members.AUDIO_ID + "=" + id,
null);
} else if (mPlaylistId == PLAYLIST_QUEUE) {
mUtils.removeTrack(id);
reloadQueueCursor();
} else if (mPlaylistId == PLAYLIST_FAVORITES) {
mUtils.removeFromFavorites(id);
}
mListView.invalidateViews();
}
private class TracksAdapter extends SimpleCursorAdapter {
private TracksAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to,
int flags) {
super(context, layout, cursor, from, to, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewholder = (ViewHolder) view.getTag();
String track_name = cursor.getString(mTrackIdx);
viewholder.track_name.setText(track_name);
String artist_name = cursor.getString(mArtistIdx);
if (artist_name == null || MediaStore.UNKNOWN_STRING.equals(artist_name)) {
viewholder.artist_name.setText(R.string.unknown_artist);
} else {
viewholder.artist_name.setText(artist_name);
}
long secs = cursor.getLong(mDurationIdx) / 1000;
if (secs <= 0) {
viewholder.track_duration.setText("");
} else {
viewholder.track_duration.setText(mUtils.makeTimeString(secs));
}
long audio_id = cursor.getLong(mIdIdx);
long currentaudioid = mUtils.getCurrentAudioId();
if (currentaudioid == audio_id) {
viewholder.track_name.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.ic_indicator_nowplaying_small, 0);
} else {
viewholder.track_name.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = super.newView(context, cursor, parent);
ViewHolder viewholder = new ViewHolder(view);
view.setTag(viewholder);
return view;
}
private class ViewHolder {
TextView track_name;
TextView artist_name;
TextView track_duration;
public ViewHolder(View view) {
track_name = (TextView) view.findViewById(R.id.name);
artist_name = (TextView) view.findViewById(R.id.summary);
track_duration = (TextView) view.findViewById(R.id.duration);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/TrackFragment.java
|
Java
|
gpl3
| 17,682
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.app.TrackBrowserActivity;
import org.yammp.util.MediaUtils;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockListFragment;
public class GenreFragment extends SherlockListFragment implements LoaderCallbacks<Cursor>,
Constants {
private GenresAdapter mAdapter;
private int mNameIdx;
private MediaUtils mUtils;
public GenreFragment() {
}
public GenreFragment(Bundle args) {
setArguments(args);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
setHasOptionsMenu(true);
mAdapter = new GenresAdapter(getActivity(), null, false);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] cols = new String[] { Audio.Genres._ID, Audio.Genres.NAME };
String where = mUtils.getBetterGenresWhereClause();
Uri uri = Audio.Genres.EXTERNAL_CONTENT_URI;
return new CursorLoader(getActivity(), uri, cols, where, null,
Audio.Genres.DEFAULT_SORT_ORDER);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.playlists_browser, container, false);
return view;
}
@Override
public void onListItemClick(ListView listview, View view, int position, long id) {
showDetails(position, id);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
getActivity().finish();
return;
}
mNameIdx = data.getColumnIndexOrThrow(Audio.Genres.NAME);
mAdapter.changeCursor(data);
setListAdapter(mAdapter);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
super.onSaveInstanceState(outState);
}
private void showDetails(int index, long id) {
View detailsFrame = getActivity().findViewById(R.id.frame_details);
boolean mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
Bundle bundle = new Bundle();
bundle.putString(INTENT_KEY_TYPE, Audio.Genres.CONTENT_TYPE);
bundle.putLong(Audio.Genres._ID, id);
if (mDualPane) {
TrackFragment fragment = new TrackFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
} else {
Intent intent = new Intent(getActivity(), TrackBrowserActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class GenresAdapter extends CursorAdapter {
private GenresAdapter(Context context, Cursor cursor, boolean autoRequery) {
super(context, cursor, autoRequery);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder viewholder = (ViewHolder) view.getTag();
String genre_name = cursor.getString(mNameIdx);
viewholder.genre_name.setText(mUtils.parseGenreName(genre_name));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.playlist_list_item, null);
ViewHolder viewholder = new ViewHolder(view);
view.setTag(viewholder);
return view;
}
private class ViewHolder {
TextView genre_name;
public ViewHolder(View view) {
genre_name = (TextView) view.findViewById(R.id.playlist_name);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/GenreFragment.java
|
Java
|
gpl3
| 5,204
|
package org.yammp.fragment;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.xmlpull.v1.XmlPullParserException;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.util.LyricsDownloader;
import org.yammp.util.LyricsDownloader.SearchResultItem;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListFragment;
public class LyricsSearchFragment extends SherlockListFragment implements Constants,
OnClickListener, TextWatcher {
private LyricsDownloader mDownloader = new LyricsDownloader();
private SearchResultAdapter mAdapter;
private EditText mTrackName, mArtistName;
private Button mSearchButton;
private String mTrack, mArtist, mPath;
private ProgressBar mProgress;
private LyricsSearchTask mSearchTask;
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = savedInstanceState == null ? getArguments() : savedInstanceState;
mTrack = args.getString(INTENT_KEY_TRACK);
mArtist = args.getString(INTENT_KEY_ARTIST);
mPath = args.getString(INTENT_KEY_PATH);
View view = getView();
mTrackName = (EditText) view.findViewById(R.id.track_name);
mTrackName.addTextChangedListener(this);
mTrackName.setText(mTrack);
mArtistName = (EditText) view.findViewById(R.id.artist_name);
mArtistName.setText(mArtist);
mSearchButton = (Button) view.findViewById(R.id.search);
mSearchButton.setOnClickListener(this);
mProgress = (ProgressBar) view.findViewById(R.id.progress);
// mAdapter = new SearchResultAdapter(getSherlockActivity(), null);
// setListAdapter(mAdapter);
}
@Override
public void onClick(View view) {
if (mSearchTask != null) {
mSearchTask.cancel(true);
} else {
mSearchTask = new LyricsSearchTask(mTrackName.getText().toString(), mArtistName
.getText().toString());
mSearchTask.execute();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.search_lyrics, container, false);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mSearchButton != null) {
mSearchButton.setEnabled(s != null
&& s.toString().trim().replaceAll("[\\p{P} ]", "").length() > 0);
}
}
private class LyricsSearchTask extends AsyncTask<Void, Void, SearchResultItem[]> {
private String title, artist;
public LyricsSearchTask(String title, String artist) {
this.title = title;
this.artist = artist;
}
@Override
public SearchResultItem[] doInBackground(Void... params) {
try {
return mDownloader.search(artist, title);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onPostExecute(SearchResultItem[] result) {
if (result == null) {
} else if (result.length > 0) {
mAdapter = new SearchResultAdapter(getSherlockActivity(), result);
setListAdapter(mAdapter);
} else {
Toast.makeText(getSherlockActivity(), R.string.search_noresult, Toast.LENGTH_SHORT)
.show();
}
mSearchTask = null;
mSearchButton.setText(android.R.string.search_go);
mProgress.setVisibility(View.GONE);
}
@Override
public void onPreExecute() {
mSearchButton.setText(android.R.string.cancel);
mProgress.setVisibility(View.VISIBLE);
}
}
private class SearchResultAdapter extends ArrayAdapter<SearchResultItem> {
public SearchResultAdapter(Context context, SearchResultItem[] objects) {
super(context, android.R.layout.two_line_list_item, android.R.id.text1, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView title = (TextView) view.findViewById(android.R.id.text1);
TextView artist = (TextView) view.findViewById(android.R.id.text2);
title.setSingleLine(true);
title.setText(getItem(position).title);
artist.setSingleLine(true);
artist.setText(getItem(position).artist);
return view;
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/LyricsSearchFragment.java
|
Java
|
gpl3
| 4,839
|
package org.yammp.fragment;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Video;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import com.actionbarsherlock.app.SherlockListFragment;
public class VideoFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
mAdapter = new SimpleCursorAdapter(getSherlockActivity(),
android.R.layout.simple_list_item_1, null, new String[] { Video.Media.TITLE },
new int[] { android.R.id.text1 }, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int loader, Bundle args) {
String[] cols = new String[] { Video.Media._ID, Video.Media.TITLE, Video.Media.DATA,
Video.Media.MIME_TYPE, Video.Media.ARTIST };
Uri uri = Video.Media.EXTERNAL_CONTENT_URI;
String sort_order = Video.Media.TITLE + " COLLATE UNICODE";
String where = Video.Media.TITLE + " != ''";
return new CursorLoader(getSherlockActivity(), uri, cols, where, null, sort_order);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.changeCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mAdapter.changeCursor(cursor);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/VideoFragment.java
|
Java
|
gpl3
| 1,685
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import java.io.File;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.app.TrackBrowserActivity;
import org.yammp.dialog.DeleteDialogFragment;
import org.yammp.util.LazyImageLoader;
import org.yammp.util.MediaUtils;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class ArtistFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor>, Constants, OnGroupExpandListener,
OnItemSelectedListener {
private ArtistsAdapter mArtistsAdapter;
private ExpandableListView mListView;
private int mSelectedGroupPosition;
private long mSelectedGroupId, mSelectedChildId;
private Cursor mGroupCursor;
private String mCurrentGroupArtistName, mCurrentChildArtistNameForAlbum,
mCurrentChildAlbumName;
private boolean mGroupSelected, mChildSelected = false;
private LazyImageLoader mImageLoader;
private int mGroupArtistIdIdx, mGroupArtistIdx, mGroupAlbumIdx, mGroupSongIdx;
private BroadcastReceiver mMediaStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mListView.invalidateViews();
}
};
private MediaUtils mUtils;
public ArtistFragment() {
}
public ArtistFragment(Bundle args) {
setArguments(args);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
setHasOptionsMenu(true);
mImageLoader = ((YAMMPApplication) getSherlockActivity().getApplication())
.getLazyImageLoader();
mArtistsAdapter = new ArtistsAdapter(getSherlockActivity(), null,
R.layout.artist_list_item_group, new String[] {}, new int[] {},
R.layout.artist_list_item_child, new String[] {}, new int[] {});
mListView = (ExpandableListView) getView().findViewById(R.id.artist_expandable_list);
mListView.setAdapter(mArtistsAdapter);
mListView.setOnGroupExpandListener(this);
mListView.setOnCreateContextMenuListener(this);
mListView.setOnItemSelectedListener(this);
registerForContextMenu(mListView);
getLoaderManager().initLoader(0, null, this);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getGroupId() == hashCode()) {
switch (item.getItemId()) {
case PLAY_SELECTION:
if (mGroupSelected && !mChildSelected) {
long[] list = mUtils.getSongListForArtist(mSelectedGroupId);
mUtils.playAll(list, 0);
} else if (mChildSelected && !mGroupSelected) {
long[] list = mUtils.getSongListForAlbum(mSelectedChildId);
mUtils.playAll(list, 0);
}
return true;
case DELETE_ITEMS:
if (mGroupSelected && !mChildSelected) {
DeleteDialogFragment.getInstance(false, mSelectedGroupId,
DeleteDialogFragment.ARTIST).show(getFragmentManager(), "dialog");
} else if (mChildSelected && !mGroupSelected) {
DeleteDialogFragment.getInstance(false, mSelectedChildId,
DeleteDialogFragment.ARTIST).show(getFragmentManager(), "dialog");
}
return true;
case DELETE_LYRICS:
if (mGroupSelected && !mChildSelected) {
DeleteDialogFragment.getInstance(true, mSelectedGroupId,
DeleteDialogFragment.ARTIST).show(getFragmentManager(), "dialog");
} else if (mChildSelected && !mGroupSelected) {
DeleteDialogFragment.getInstance(true, mSelectedChildId,
DeleteDialogFragment.ARTIST).show(getFragmentManager(), "dialog");
}
return true;
case SEARCH:
if (mGroupSelected && !mChildSelected) {
doSearch(mCurrentGroupArtistName, null);
} else if (mChildSelected && !mGroupSelected) {
doSearch(mCurrentChildArtistNameForAlbum, mCurrentChildAlbumName);
}
return true;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo info) {
ExpandableListContextMenuInfo mi = (ExpandableListContextMenuInfo) info;
int itemtype = ExpandableListView.getPackedPositionType(mi.packedPosition);
mSelectedGroupPosition = ExpandableListView.getPackedPositionGroup(mi.packedPosition);
int gpos = mSelectedGroupPosition;
if (itemtype == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
mGroupSelected = true;
mChildSelected = false;
mGroupCursor.moveToPosition(gpos);
menu.add(hashCode(), PLAY_SELECTION, 0, R.string.play_selection);
menu.add(hashCode(), DELETE_ITEMS, 0, R.string.delete_music);
menu.add(hashCode(), DELETE_LYRICS, 0, R.string.delete_lyrics);
if (gpos == -1) {
// this shouldn't happen
Log.d("Artist/Album", "no group");
return;
}
mCurrentGroupArtistName = mGroupCursor.getString(mGroupArtistIdx);
mSelectedGroupId = mGroupCursor.getLong(mGroupArtistIdIdx);
if (mCurrentGroupArtistName != null
&& !MediaStore.UNKNOWN_STRING.equals(mCurrentGroupArtistName)) {
menu.setHeaderTitle(mCurrentGroupArtistName);
menu.add(hashCode(), SEARCH, 0, android.R.string.search_go);
} else {
menu.setHeaderTitle(getString(R.string.unknown_artist));
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] cols = new String[] { Audio.Artists._ID, Audio.Artists.ARTIST,
Audio.Artists.NUMBER_OF_ALBUMS, Audio.Artists.NUMBER_OF_TRACKS };
Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI;
return new CursorLoader(getSherlockActivity(), uri, cols, null, null,
Audio.Artists.DEFAULT_SORT_ORDER);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.artist_album_browser, container, false);
return view;
}
@Override
public void onGroupExpand(int position) {
long id = mArtistsAdapter.getGroupId(position);
showGroupDetails(position, id);
}
@Override
public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {
if (view.getTag() != null && view.getTag() instanceof ViewHolderChild) {
mListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
((ViewHolderChild) view.getTag()).gridview.requestFocus();
} else {
mListView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
mListView.requestFocus();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mArtistsAdapter.setGroupCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data == null) {
getSherlockActivity().finish();
return;
}
mGroupCursor = data;
mGroupArtistIdIdx = data.getColumnIndexOrThrow(Audio.Artists._ID);
mGroupArtistIdx = data.getColumnIndexOrThrow(Audio.Artists.ARTIST);
mGroupAlbumIdx = data.getColumnIndexOrThrow(Audio.Artists.NUMBER_OF_ALBUMS);
mGroupSongIdx = data.getColumnIndexOrThrow(Audio.Artists.NUMBER_OF_TRACKS);
mArtistsAdapter.changeCursor(data);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
if (!mListView.isFocused()) {
mListView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
mListView.requestFocus();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putAll(getArguments() != null ? getArguments() : new Bundle());
super.onSaveInstanceState(outState);
}
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_META_CHANGED);
filter.addAction(BROADCAST_QUEUE_CHANGED);
getSherlockActivity().registerReceiver(mMediaStatusReceiver, filter);
}
@Override
public void onStop() {
getSherlockActivity().unregisterReceiver(mMediaStatusReceiver);
super.onStop();
}
private void doSearch(String artist, String album) {
CharSequence title = null;
String query = null;
boolean isUnknownArtist = artist == null || MediaStore.UNKNOWN_STRING.equals(artist);
boolean isUnknownAlbum = album == null || MediaStore.UNKNOWN_STRING.equals(album);
if (isUnknownArtist && isUnknownAlbum) return;
Intent i = new Intent();
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
title = album != null ? album : artist;
query = album != null ? album : artist;
if (!isUnknownArtist) {
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
}
if (!isUnknownAlbum) {
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
}
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*");
title = getString(R.string.mediasearch, title);
i.putExtra(SearchManager.QUERY, query);
startActivity(Intent.createChooser(i, title));
}
private void showGroupDetails(int groupPosition, long id) {
View detailsFrame = getSherlockActivity().findViewById(R.id.frame_details);
boolean mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (mDualPane) {
mListView.setSelectedGroup(groupPosition);
TrackFragment fragment = new TrackFragment();
Bundle args = new Bundle();
args.putString(INTENT_KEY_TYPE, MediaStore.Audio.Artists.CONTENT_TYPE);
args.putLong(Audio.Artists._ID, id);
fragment.setArguments(args);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
private class AlbumChildAdapter extends SimpleCursorAdapter implements
OnCreateContextMenuListener {
private int mAlbumIndex;
private int mArtistIndex;
private int mAlbumArtIndex;
private AlbumChildAdapter(Context context, int layout, Cursor cursor, String[] from,
int[] to, int flags) {
super(context, layout, cursor, from, to, flags);
getColumnIndices(cursor);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
view.setOnCreateContextMenuListener(this);
ViewHolderItem viewholder = (ViewHolderItem) view.getTag();
if (viewholder == null) return;
String album_name = cursor.getString(mAlbumIndex);
boolean unknown = album_name == null || album_name.equals(MediaStore.UNKNOWN_STRING);
if (unknown) {
album_name = context.getString(R.string.unknown_album);
}
viewholder.album_name.setText(album_name);
String artist_name = cursor.getString(mArtistIndex);
if (artist_name == null || artist_name.equals(MediaStore.UNKNOWN_STRING)) {
artist_name = context.getString(R.string.unknown_artist);
}
viewholder.artist_name.setText(artist_name);
long aid = cursor.getLong(0);
long currentalbumid = mUtils.getCurrentAlbumId();
if (currentalbumid == aid) {
viewholder.album_name.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.ic_indicator_nowplaying_small, 0);
} else {
viewholder.album_name.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
String art = cursor.getString(mAlbumArtIndex);
if (art != null && art.toString().length() > 0) {
mImageLoader.displayImage(new File(art), viewholder.album_art);
} else {
viewholder.album_art.setImageResource(R.drawable.ic_mp_albumart_unknown);
}
viewholder.album_id = aid;
viewholder.album_name_string = album_name;
viewholder.artist_name_string = artist_name;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = super.newView(context, cursor, parent);
ViewHolderItem mViewHolder = new ViewHolderItem(view);
view.setTag(mViewHolder);
return view;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) {
mGroupSelected = false;
mChildSelected = true;
getSherlockActivity().getMenuInflater().inflate(R.menu.music_browser_item, menu);
if (v.getTag() == null) return;
ViewHolderItem viewholder = (ViewHolderItem) v.getTag();
mCurrentChildArtistNameForAlbum = viewholder.artist_name_string;
mCurrentChildAlbumName = viewholder.album_name_string;
mSelectedChildId = viewholder.album_id;
if (mCurrentChildAlbumName == null
|| MediaStore.UNKNOWN_STRING.equals(mCurrentChildAlbumName)) {
menu.setHeaderTitle(getString(R.string.unknown_artist));
menu.findItem(R.id.search).setEnabled(false);
menu.findItem(R.id.search).setVisible(false);
} else {
menu.setHeaderTitle(mCurrentChildAlbumName);
}
}
private void getColumnIndices(Cursor cursor) {
if (cursor != null) {
mAlbumIndex = cursor.getColumnIndexOrThrow(Audio.Albums.ALBUM);
mArtistIndex = cursor.getColumnIndexOrThrow(Audio.Albums.ARTIST);
mAlbumArtIndex = cursor.getColumnIndexOrThrow(Audio.Albums.ALBUM_ART);
}
}
private class ViewHolderItem {
TextView album_name;
TextView artist_name;
ImageView album_art;
long album_id;
String album_name_string;
String artist_name_string;
public ViewHolderItem(View view) {
album_name = (TextView) view.findViewById(R.id.album_name);
artist_name = (TextView) view.findViewById(R.id.artist_name);
album_art = (ImageView) view.findViewById(R.id.album_art);
}
}
}
private class ArtistsAdapter extends SimpleCursorTreeAdapter implements OnItemClickListener {
public ArtistsAdapter(Context context, Cursor cursor, int glayout, String[] gfrom,
int[] gto, int clayout, String[] cfrom, int[] cto) {
super(context, cursor, glayout, gfrom, gto, clayout, cfrom, cto);
}
@Override
public void bindChildView(View view, Context context, Cursor cursor, boolean isLastChild) {
ViewHolderChild viewholder = (ViewHolderChild) view.getTag();
viewholder.gridview.setAdapter(new AlbumChildAdapter(context, R.layout.album_grid_item,
cursor, new String[] {}, new int[] {}, 0));
viewholder.gridview.setOnItemClickListener(this);
int item_width = getResources().getDimensionPixelOffset(R.dimen.gridview_item_width);
int item_height = getResources().getDimensionPixelOffset(R.dimen.gridview_item_height);
int parent_width = mListView.getWidth();
int albums_count = cursor.getCount();
int gridview_columns = (int) (Math.floor(parent_width / item_width) > 0 ? Math
.floor(parent_width / item_width) : 1);
int gridview_rows = (int) Math.ceil((float) albums_count / gridview_columns);
int default_padding = getResources().getDimensionPixelOffset(
R.dimen.default_element_spacing);
int paddings_sum = default_padding * (gridview_rows + 1);
viewholder.gridview.getLayoutParams().height = item_height * gridview_rows
+ paddings_sum;
}
@Override
public void bindGroupView(View view, Context context, Cursor cursor, boolean isexpanded) {
ViewHolderGroup viewholder = (ViewHolderGroup) view.getTag();
String artist = cursor.getString(mGroupArtistIdx);
boolean unknown = artist == null || MediaStore.UNKNOWN_STRING.equals(artist);
if (unknown) {
viewholder.artist_name.setText(R.string.unknown_artist);
} else {
viewholder.artist_name.setText(artist);
}
int numalbums = cursor.getInt(mGroupAlbumIdx);
int numsongs = cursor.getInt(mGroupSongIdx);
String songs_albums = mUtils.makeAlbumsLabel(numalbums, numsongs, unknown);
viewholder.album_track_count.setText(songs_albums);
long currentartistid = mUtils.getCurrentArtistId();
long aid = cursor.getLong(mGroupArtistIdIdx);
if (currentartistid == aid) {
viewholder.artist_name.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.ic_indicator_nowplaying_small, 0);
} else {
viewholder.artist_name.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
}
@Override
public int getChildrenCount(int groupPosition) {
return 1;
}
@Override
public View newChildView(Context context, Cursor cursor, boolean isLastChild,
ViewGroup parent) {
View view = super.newChildView(context, cursor, isLastChild, parent);
ViewHolderChild viewholder = new ViewHolderChild(view);
view.setTag(viewholder);
return view;
}
@Override
public View newGroupView(Context context, Cursor cursor, boolean isExpanded,
ViewGroup parent) {
View view = super.newGroupView(context, cursor, isExpanded, parent);
ViewHolderGroup viewholder = new ViewHolderGroup(view);
view.setTag(viewholder);
return view;
}
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
showDetails(position, id);
}
private void showDetails(int childPosition, long id) {
View detailsFrame = getSherlockActivity().findViewById(R.id.frame_details);
boolean mDualPane = detailsFrame != null
&& detailsFrame.getVisibility() == View.VISIBLE;
Bundle bundle = new Bundle();
bundle.putString(INTENT_KEY_TYPE, MediaStore.Audio.Albums.CONTENT_TYPE);
bundle.putLong(MediaStore.Audio.Albums._ID, id);
if (mDualPane) {
TrackFragment fragment = new TrackFragment();
fragment.setArguments(bundle);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.frame_details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
} else {
Intent intent = new Intent(getSherlockActivity(), TrackBrowserActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
long id = groupCursor.getLong(groupCursor.getColumnIndexOrThrow(Audio.Artists._ID));
String[] cols = new String[] { Audio.Albums._ID, Audio.Albums.ALBUM,
Audio.Albums.ARTIST, Audio.Albums.NUMBER_OF_SONGS,
Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST, Audio.Albums.ALBUM_ART };
Uri uri = Audio.Artists.Albums.getContentUri(EXTERNAL_VOLUME, id);
Cursor c = getSherlockActivity().getContentResolver().query(uri, cols, null, null,
Audio.Albums.DEFAULT_SORT_ORDER);
return c;
}
}
private class ViewHolderChild {
GridView gridview;
public ViewHolderChild(View view) {
gridview = (GridView) view.findViewById(R.id.artist_child_grid_view);
}
}
private class ViewHolderGroup {
TextView artist_name;
TextView album_track_count;
public ViewHolderGroup(View view) {
artist_name = (TextView) view.findViewById(R.id.name);
album_track_count = (TextView) view.findViewById(R.id.summary);
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/ArtistFragment.java
|
Java
|
gpl3
| 20,360
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.util.PluginInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListFragment;
public class PluginFragment extends SherlockListFragment implements Constants,
LoaderCallbacks<List<PluginInfo>> {
private PluginAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mAdapter = new PluginAdapter(getActivity(), R.layout.playlist_list_item);
setListAdapter(mAdapter);
setListShown(false);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<List<PluginInfo>> onCreateLoader(int id, Bundle args) {
return new PluginsListLoader(getActivity());
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
PluginInfo item = mAdapter.getItem(position);
Intent intent = new Intent();
intent.setPackage(item.pname);
try {
intent.setAction(INTENT_CONFIGURE_PLUGIN);
startActivity(intent);
} catch (ActivityNotFoundException e1) {
try {
intent.setAction(INTENT_OPEN_PLUGIN);
startActivity(intent);
} catch (ActivityNotFoundException e2) {
Toast.makeText(getActivity(), R.string.plugin_not_supported, Toast.LENGTH_SHORT)
.show();
}
}
}
@Override
public void onLoaderReset(Loader<List<PluginInfo>> loader) {
mAdapter.setData(null);
}
@Override
public void onLoadFinished(Loader<List<PluginInfo>> loader, List<PluginInfo> data) {
mAdapter.setData(data);
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
public static class PluginsListLoader extends AsyncTaskLoader<List<PluginInfo>> {
private PackageManager mPackageManager;
private PackageIntentReceiver mPackageObserver;
private InterestingConfigChanges mLastConfig = new InterestingConfigChanges();
List<PluginInfo> mApps;
/**
* Perform alphabetical comparison of application entry objects.
*/
public static final Comparator<PluginInfo> ALPHA_COMPARATOR = new Comparator<PluginInfo>() {
private final Collator sCollator = Collator.getInstance();
@Override
public int compare(PluginInfo object1, PluginInfo object2) {
return sCollator.compare(object1.name, object2.name);
}
};
public PluginsListLoader(Context context) {
super(context);
mPackageManager = context.getPackageManager();
}
@Override
public void deliverResult(List<PluginInfo> apps) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (apps != null) {
onReleaseResources(apps);
}
}
List<PluginInfo> oldApps = apps;
mApps = apps;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(apps);
}
// At this point we can release the resources associated with
// 'oldApps' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldApps != null) {
onReleaseResources(oldApps);
}
}
@Override
public List<PluginInfo> loadInBackground() {
List<PluginInfo> plugins = new ArrayList<PluginInfo>();
List<Intent> intents = new ArrayList<Intent>();
intents.add(new Intent(INTENT_CONFIGURE_PLUGIN));
intents.add(new Intent(INTENT_OPEN_PLUGIN));
for (Intent intent : intents) {
for (ResolveInfo info : mPackageManager.queryIntentActivities(intent, 0)) {
plugins.add(new PluginInfo(info, mPackageManager));
}
}
Collections.sort(plugins, ALPHA_COMPARATOR);
return plugins;
}
/**
* Handles a request to cancel a load.
*/
@Override
public void onCanceled(List<PluginInfo> apps) {
super.onCanceled(apps);
// At this point we can release the resources associated with 'apps'
// if needed.
onReleaseResources(apps);
}
/**
* Helper function to take care of releasing resources associated with
* an actively loaded data set.
*/
protected void onReleaseResources(List<PluginInfo> apps) {
// For a simple List<> there is nothing to do. For something
// like a Cursor, we would close it here.
}
/**
* Handles a request to completely reset the Loader.
*/
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (mApps != null) {
onReleaseResources(mApps);
mApps = null;
}
// Stop monitoring for changes.
if (mPackageObserver != null) {
getContext().unregisterReceiver(mPackageObserver);
mPackageObserver = null;
}
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
if (mApps != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(mApps);
}
// Start watching for changes in the app data.
if (mPackageObserver == null) {
mPackageObserver = new PackageIntentReceiver(this);
}
// Has something interesting in the configuration changed since we
// last built the app list?
boolean configChange = mLastConfig.applyNewConfig(getContext().getResources());
if (takeContentChanged() || mApps == null || configChange) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Helper for determining if the configuration has changed in an
* interesting way so we need to rebuild the app list.
*/
public static class InterestingConfigChanges {
final Configuration mLastConfiguration = new Configuration();
int mLastDensity;
boolean applyNewConfig(Resources res) {
int configChanges = mLastConfiguration.updateFrom(res.getConfiguration());
boolean densityChanged = mLastDensity != res.getDisplayMetrics().densityDpi;
if (densityChanged
|| (configChanges & (ActivityInfo.CONFIG_LOCALE
| ActivityInfo.CONFIG_UI_MODE | ActivityInfo.CONFIG_SCREEN_LAYOUT)) != 0) {
mLastDensity = res.getDisplayMetrics().densityDpi;
return true;
}
return false;
}
}
/**
* Helper class to look for interesting changes to the installed apps so
* that the loader can be updated.
*/
public static class PackageIntentReceiver extends BroadcastReceiver {
final PluginsListLoader mLoader;
public PackageIntentReceiver(PluginsListLoader loader) {
mLoader = loader;
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
mLoader.getContext().registerReceiver(this, filter);
// Register for events related to sdcard installation.
IntentFilter sdFilter = new IntentFilter();
sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
mLoader.getContext().registerReceiver(this, sdFilter);
}
@Override
public void onReceive(Context context, Intent intent) {
// Tell the loader about the change.
mLoader.onContentChanged();
}
}
}
private class PluginAdapter extends ArrayAdapter<PluginInfo> {
public PluginAdapter(Context context, int resource) {
super(context, resource);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = getLayoutInflater(getArguments()).inflate(R.layout.plugin_list_item, parent,
false);
} else {
view = convertView;
}
ViewHolder viewholder = view.getTag() == null ? new ViewHolder(view)
: (ViewHolder) view.getTag();
PluginInfo info = getItem(position);
viewholder.plugin_icon.setImageDrawable(info.icon);
viewholder.plugin_name.setText(info.name);
viewholder.plugin_description.setText(info.description);
return view;
}
public void setData(List<PluginInfo> data) {
clear();
if (data != null) {
for (PluginInfo item : data) {
add(item);
}
}
}
private class ViewHolder {
ImageView plugin_icon;
TextView plugin_name;
TextView plugin_description;
public ViewHolder(View view) {
plugin_icon = (ImageView) view.findViewById(R.id.plugin_icon);
plugin_name = (TextView) view.findViewById(R.id.plugin_name);
plugin_description = (TextView) view.findViewById(R.id.plugin_description);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/PluginFragment.java
|
Java
|
gpl3
| 10,530
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.ServiceInterface;
import org.yammp.util.ServiceInterface.LyricsStateListener;
import org.yammp.widget.TextScrollView;
import org.yammp.widget.TextScrollView.OnLineSelectedListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.actionbarsherlock.app.SherlockFragment;
public class LyricsFragment extends SherlockFragment implements Constants, OnLineSelectedListener,
OnClickListener, OnBackStackChangedListener, LyricsStateListener {
private ServiceInterface mInterface = null;
private final static String SEARCH_LYRICS = "search_lyrics";
// for lyrics displaying
private TextScrollView mLyricsScrollView;
private Button mLyricsEmptyView;
private LinearLayout mLyricsSearchLayout;
private boolean mIntentDeRegistered = false;
private LyricsSearchFragment mSearchFragment;
private boolean mSearchShowed = false;
private BroadcastReceiver mScreenTimeoutListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
if (mIntentDeRegistered) {
mIntentDeRegistered = false;
}
loadLyricsToView();
scrollLyrics(true);
} else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
if (!mIntentDeRegistered) {
mIntentDeRegistered = true;
}
}
}
};
@Override
public void onActivityCreated(Bundle savedInstanceState) {
mInterface = ((YAMMPApplication) getSherlockActivity().getApplication())
.getServiceInterface();
super.onActivityCreated(savedInstanceState);
mSearchFragment = new LyricsSearchFragment();
getFragmentManager().addOnBackStackChangedListener(this);
View view = getView();
mLyricsScrollView = (TextScrollView) view.findViewById(R.id.lyrics_scroll);
mLyricsScrollView.setContentGravity(Gravity.CENTER_HORIZONTAL);
mLyricsScrollView.setLineSelectedListener(this);
mLyricsEmptyView = (Button) view.findViewById(R.id.lyrics_empty);
mLyricsEmptyView.setOnClickListener(this);
mLyricsSearchLayout = (LinearLayout) view.findViewById(R.id.search_lyrics);
mInterface.addLyricsStateListener(this);
}
@Override
public void onBackStackChanged() {
if (mSearchFragment != null) {
boolean search_showed = mSearchFragment.isAdded();
mSearchShowed = search_showed;
mLyricsSearchLayout.setVisibility(search_showed ? View.VISIBLE : View.GONE);
if (mInterface != null) {
boolean lyrics_status_ok = mInterface.getLyricsStatus() == LYRICS_STATUS_OK;
mLyricsEmptyView.setVisibility(search_showed || lyrics_status_ok ? View.GONE
: View.VISIBLE);
mLyricsScrollView.setVisibility(search_showed || !lyrics_status_ok ? View.GONE
: View.VISIBLE);
}
}
}
@Override
public void onClick(View v) {
searchLyrics();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.lyrics_view, container, false);
}
@Override
public void onLineSelected(int id) {
if (mInterface != null) {
mInterface.seek(mInterface.getPositionByLyricsId(id));
}
}
@Override
public void onLyricsRefreshed() {
scrollLyrics(false);
}
@Override
public void onNewLyricsLoaded() {
loadLyricsToView();
}
@Override
public void onStart() {
super.onStart();
try {
float mWindowAnimation = Settings.System.getFloat(getActivity().getContentResolver(),
Settings.System.WINDOW_ANIMATION_SCALE);
mLyricsScrollView.setSmoothScrollingEnabled(mWindowAnimation > 0.0);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
IntentFilter screenstatusfilter = new IntentFilter();
screenstatusfilter.addAction(Intent.ACTION_SCREEN_ON);
screenstatusfilter.addAction(Intent.ACTION_SCREEN_OFF);
getActivity().registerReceiver(mScreenTimeoutListener, screenstatusfilter);
}
@Override
public void onStop() {
getActivity().unregisterReceiver(mScreenTimeoutListener);
super.onStop();
}
// TODO lyrics load animation
private void loadLyricsToView() {
if (mLyricsScrollView == null || mInterface == null) return;
mLyricsScrollView.setTextContent(mInterface.getLyrics());
if (!mSearchShowed) {
if (mInterface.getLyricsStatus() == LYRICS_STATUS_OK) {
mLyricsScrollView.setVisibility(View.VISIBLE);
mLyricsEmptyView.setVisibility(View.GONE);
} else {
mLyricsScrollView.setVisibility(View.GONE);
mLyricsEmptyView.setVisibility(View.VISIBLE);
}
}
}
private void scrollLyrics(boolean force) {
if (mInterface == null) return;
if (mLyricsScrollView == null) return;
mLyricsScrollView.setCurrentLine(mInterface.getCurrentLyricsId(), force);
}
private void searchLyrics() {
if (mInterface == null) return;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Bundle args = new Bundle();
args.putString(INTENT_KEY_TRACK, mInterface.getTrackName());
args.putString(INTENT_KEY_ARTIST, mInterface.getArtistName());
String media_path = mInterface.getMediaPath();
String lyrics_path = media_path.substring(0, media_path.lastIndexOf(".")) + ".lrc";
args.putString(INTENT_KEY_PATH, lyrics_path);
mSearchFragment.setArguments(args);
ft.replace(R.id.search_lyrics, mSearchFragment);
ft.addToBackStack(SEARCH_LYRICS);
ft.commit();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/LyricsFragment.java
|
Java
|
gpl3
| 6,834
|
/*
* YAMMP - Yet Another Multi Media Player for android
* Copyright (C) 2011-2012 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This file is part of YAMMP.
*
* YAMMP 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.
*
* YAMMP 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 YAMMP. If not, see <http://www.gnu.org/licenses/>.
*/
package org.yammp.fragment;
import java.util.ArrayList;
import org.yammp.Constants;
import org.yammp.R;
import org.yammp.YAMMPApplication;
import org.yammp.util.MediaUtils;
import org.yammp.util.PreferencesEditor;
import org.yammp.util.ServiceInterface;
import org.yammp.util.ServiceInterface.MediaStateListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MusicBrowserFragment extends SherlockFragment implements Constants,
OnPageChangeListener, MediaStateListener {
private ViewPager mViewPager;
private TabsAdapter mAdapter;
private PreferencesEditor mPrefs;
private ProgressBar mProgress;
private ServiceInterface mInterface;
private MediaUtils mUtils;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.music_browser, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mUtils = ((YAMMPApplication) getSherlockActivity().getApplication()).getMediaUtils();
mInterface = ((YAMMPApplication) getSherlockActivity().getApplication())
.getServiceInterface();
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.music_browser, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mViewPager.setOnPageChangeListener(this);
mAdapter = new TabsAdapter(getFragmentManager());
mPrefs = new PreferencesEditor(getActivity());
mProgress = (ProgressBar) view.findViewById(R.id.progress);
mAdapter.addFragment(new ArtistFragment(), getString(R.string.artists).toUpperCase());
mAdapter.addFragment(new AlbumFragment(), getString(R.string.albums).toUpperCase());
mAdapter.addFragment(new TrackFragment(), getString(R.string.tracks).toUpperCase());
mAdapter.addFragment(new PlaylistFragment(), getString(R.string.playlists).toUpperCase());
mAdapter.addFragment(new GenreFragment(), getString(R.string.genres).toUpperCase());
new AdapterTask().execute();
return view;
}
@Override
public void onFavoriteStateChanged() {
}
@Override
public void onMetaChanged() {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case PLAY_PAUSE:
mInterface.togglePause();
break;
case NEXT:
mInterface.next();
break;
case SHUFFLE_ALL:
mUtils.shuffleAll();
break;
case SETTINGS:
intent = new Intent(INTENT_MUSIC_SETTINGS);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageSelected(int position) {
mPrefs.setIntState(STATE_KEY_CURRENTTAB, position);
}
@Override
public void onPlayStateChanged() {
getSherlockActivity().invalidateOptionsMenu();
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(PLAY_PAUSE);
if (item != null) {
item.setIcon(mInterface.isPlaying() ? R.drawable.ic_action_media_pause
: R.drawable.ic_action_media_play);
}
super.onPrepareOptionsMenu(menu);
}
@Override
public void onQueueChanged() {
}
@Override
public void onRepeatModeChanged() {
}
@Override
public void onShuffleModeChanged() {
}
@Override
public void onStart() {
super.onStart();
mInterface.addMediaStateListener(this);
}
@Override
public void onStop() {
mInterface.removeMediaStateListener(this);
super.onStop();
}
private class AdapterTask extends AsyncTask<Void, Void, Void> {
@Override
public Void doInBackground(Void... params) {
return null;
}
@Override
public void onPostExecute(Void result) {
mProgress.findViewById(R.id.progress).setVisibility(View.INVISIBLE);
mViewPager.findViewById(R.id.pager).setVisibility(View.VISIBLE);
mViewPager.setAdapter(mAdapter);
int currenttab = mPrefs.getIntState(STATE_KEY_CURRENTTAB, 0);
mViewPager.setCurrentItem(currenttab);
}
@Override
public void onPreExecute() {
mViewPager.setAdapter(null);
mProgress.setVisibility(View.VISIBLE);
mViewPager.setVisibility(View.INVISIBLE);
}
}
private class TabsAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
private ArrayList<String> mTitles = new ArrayList<String>();
public TabsAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment, String name) {
mFragments.add(fragment);
mTitles.add(name);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/fragment/MusicBrowserFragment.java
|
Java
|
gpl3
| 6,222
|
/*
* Copyright (C) 2012 The MusicMod Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class LyricsDownloader {
private final static char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
private final static String UTF_8 = "utf-8";
public OnProgressChangeListener mListener;
/**
* Download lyrics from server
*
* @param id
* Id of selected item.
* @param file
* Destination file.
*/
public void download(int id, String verify_code, File file) throws MalformedURLException,
IOException {
String url_string = getDownloadUrl(id, verify_code);
URL url = new URL(url_string);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
FileOutputStream output = new FileOutputStream(file);
InputStream input = connection.getInputStream();
int total_size = connection.getContentLength();
int downloaded_size = 0;
byte[] buffer = new byte[1024];
int buffer_length = 0;
while ((buffer_length = input.read(buffer)) > 0) {
output.write(buffer, 0, buffer_length);
downloaded_size += buffer_length;
if (mListener != null) {
mListener.onProgressChange(downloaded_size, total_size);
}
}
output.close();
}
/**
* Download lyrics from server
*
* @param id
* Id of selected item.
* @param file
* Destination file path.
*/
public void download(int id, String verify_code, String path) throws MalformedURLException,
IOException {
download(id, verify_code, new File(path));
}
/**
* Search lyrics from server
*
* @return result list in string array.
*
* @param artist
* The artist of sound track.
* @param track
* The name of sound track.
*/
public SearchResultItem[] search(String track, String artist)
throws UnsupportedEncodingException, XmlPullParserException, IOException {
String url = getSearchUrl(encode(artist), encode(track));
return parseResult(get(url, UTF_8));
}
public void setOnProgressChangeListener(OnProgressChangeListener listener) {
mListener = listener;
}
private String encode(String source) {
final String UTF_16LE = "utf-16le";
if (source == null) {
source = "";
}
source = source.replaceAll("[\\p{P} ]", "").toLowerCase();
byte[] bytes = null;
try {
bytes = source.getBytes(UTF_16LE);
} catch (Exception e) {
e.printStackTrace();
bytes = source.getBytes();
}
char[] charactor = new char[2];
StringBuilder builder = new StringBuilder();
for (byte byteValue : bytes) {
charactor[0] = digit[byteValue >>> 4 & 0X0F];
charactor[1] = digit[byteValue & 0X0F];
builder.append(charactor);
}
return builder.toString();
}
// get text from url
private String get(String url, String encoding) throws UnsupportedEncodingException,
IOException {
if (url == null) return null;
URLConnection conn = new URL(url).openConnection();
conn.connect();
String contentType = conn.getContentType();
if (contentType == null) {
contentType = encoding;
}
Pattern pattern = Pattern.compile("(?i)\\bcharset=([^\\s;]+)");
Matcher matcher = pattern.matcher(contentType);
String encoder = encoding;
if (matcher.find()) {
encoder = matcher.group(1);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
encoder));
char[] str = new char[4096];
StringBuilder builder = new StringBuilder();
for (int len; (len = reader.read(str)) > -1;) {
builder.append(str, 0, len);
}
return builder.toString();
}
private SearchResultItem[] parseResult(String xml) throws XmlPullParserException, IOException {
if (xml == null || "".equals(xml)) return new SearchResultItem[] {};
List<SearchResultItem> mItemList = new ArrayList<SearchResultItem>();
final String TAG_RESULT = "result", TAG_LRC = "lrc";
final String ATTR_ID = "id", ATTR_ARTIST = "artist", ATTR_TITLE = "title";
SearchResultItem item = null;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(xml));
int eventType = parser.getEventType();
String tagName;
boolean lookingForEndOfUnknownTag = false;
String unknownTagName = null;
// This loop will skip to the result start tag
do {
if (eventType == XmlPullParser.START_TAG) {
tagName = parser.getName();
if (TAG_RESULT.equals(tagName)) {
// Go to next tag
eventType = parser.next();
break;
}
throw new RuntimeException("Expecting " + TAG_RESULT + " , got " + tagName);
}
eventType = parser.next();
} while (eventType != XmlPullParser.END_DOCUMENT);
boolean reachedEndOfResult = false;
while (!reachedEndOfResult) {
switch (eventType) {
case XmlPullParser.START_TAG:
if (lookingForEndOfUnknownTag) {
break;
}
tagName = parser.getName();
if (TAG_LRC.equals(tagName)) {
String artist = parser
.getAttributeValue(parser.getNamespace(), ATTR_ARTIST);
String title = parser.getAttributeValue(parser.getNamespace(), ATTR_TITLE);
int id = Integer.valueOf(parser.getAttributeValue(parser.getNamespace(),
ATTR_ID));
String verify_code = verify(artist, title, id);
item = new SearchResultItem(title, artist, id, verify_code);
} else {
lookingForEndOfUnknownTag = true;
unknownTagName = tagName;
}
break;
case XmlPullParser.END_TAG:
tagName = parser.getName();
if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
lookingForEndOfUnknownTag = false;
unknownTagName = null;
} else if (TAG_LRC.equals(tagName)) {
if (item != null) {
mItemList.add(item);
}
} else if (TAG_RESULT.equals(tagName)) {
reachedEndOfResult = true;
}
break;
}
eventType = parser.next();
}
return mItemList.toArray(new SearchResultItem[mItemList.size()]);
}
private String verify(String artist, String track, int id) {
if (artist == null) {
artist = "";
}
if (track == null) throw new IllegalArgumentException("Track name cannot be null!");
byte[] bytes;
try {
bytes = (artist + track).getBytes(UTF_8);
} catch (UnsupportedEncodingException e) {
return "";
}
int[] song = new int[bytes.length];
for (int i = 0; i < bytes.length; i++) {
song[i] = bytes[i] & 0xff;
}
int intVal1 = 0, intVal2 = 0, intVal3 = 0;
intVal1 = (id & 0xFF00) >> 8;
if ((id & 0xFF0000) == 0) {
intVal3 = 0xFF & ~intVal1;
} else {
intVal3 = 0xFF & (id & 0x00FF0000) >> 16;
}
intVal3 = intVal3 | (0xFF & id) << 8;
intVal3 = intVal3 << 8;
intVal3 = intVal3 | 0xFF & intVal1;
intVal3 = intVal3 << 8;
if ((id & 0xFF000000) == 0) {
intVal3 = intVal3 | 0xFF & ~id;
} else {
intVal3 = intVal3 | 0xFF & id >> 24;
}
int uBound = bytes.length - 1;
while (uBound >= 0) {
int c = song[uBound];
if (c >= 0x80) {
c = c - 0x100;
}
intVal1 = c + intVal2;
intVal2 = intVal2 << uBound % 2 + 4;
intVal2 = intVal1 + intVal2;
uBound -= 1;
}
uBound = 0;
intVal1 = 0;
while (uBound <= bytes.length - 1) {
int c = song[uBound];
if (c >= 128) {
c -= 256;
}
int intVal4 = c + intVal1;
intVal1 = intVal1 << uBound % 2 + 3;
intVal1 = intVal1 + intVal4;
uBound += 1;
}
int intVal5 = intVal2 ^ intVal3;
intVal5 = intVal5 + (intVal1 | id);
intVal5 = intVal5 * (intVal1 | intVal3);
intVal5 = intVal5 * (intVal2 ^ id);
return String.valueOf(intVal5);
}
private static String getDownloadUrl(int id, String code) {
return "http://ttlrcct.qianqian.com/dll/lyricsvr.dll?dl?Id=" + id + "&Code=" + code;
}
private static String getSearchUrl(String track, String artist) {
if (track == null) throw new IllegalArgumentException("Track name cannot be null!");
if (artist == null)
return "http://ttlrcct.qianqian.com/dll/lyricsvr.dll?sh?Title=" + track + "&Flags=0";
return "http://ttlrcct.qianqian.com/dll/lyricsvr.dll?sh?Artist=" + artist + "&Title="
+ track + "&Flags=0";
}
public interface OnProgressChangeListener {
void onProgressChange(int progress, int total);
}
public class SearchResultItem {
public String title = "";
public String artist = "";
public int id = 0;
public String verify_code = "";
public SearchResultItem(String title, String artist, int id, String verify_code) {
this.title = title;
this.artist = artist;
this.id = id;
this.verify_code = verify_code;
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/LyricsDownloader.java
|
Java
|
gpl3
| 9,853
|
package org.yammp.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
/**
* Lazy image loader for {@link ListView} and {@link GridView} etc.</br> </br>
* Inspired by <a url="https://github.com/thest1/LazyList">LazyList</a>, this
* class has extra features like image loading/caching image to
* /mnt/sdcard/Android/data/[package name]/cache features.</br> </br> Requires
* Android 2.2, you can modify {@link Context#getExternalCacheDir()} to other to
* support Android 2.1 and below.
*
* @author mariotaku
*
*/
public class LazyImageLoader {
MemoryCache mMemoryCache = new MemoryCache();
FileCache mFileCache;
private Map<ImageView, Object> mImageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, Object>());
ExecutorService mExecutorService;
private int mFallbackRes;
private int mRequiredSize;
public LazyImageLoader(Context context, int fallback, int required_size) {
mFileCache = new FileCache(context);
mExecutorService = Executors.newFixedThreadPool(5);
mFallbackRes = fallback;
mRequiredSize = required_size % 2 == 0 ? required_size : required_size + 1;
}
public void clearFileCache() {
mFileCache.clear();
}
public void clearMemoryCache() {
mMemoryCache.clear();
}
public void displayImage(File file, ImageView imageview) {
if (file == null) {
imageview.setImageResource(mFallbackRes);
return;
}
mImageViews.put(imageview, file);
Bitmap bitmap = mMemoryCache.get(file);
if (bitmap != null) {
imageview.setImageBitmap(bitmap);
} else {
queuePhoto(file, imageview);
imageview.setImageResource(mFallbackRes);
}
}
public void displayImage(URL url, ImageView imageview) {
if (url == null) {
imageview.setImageResource(mFallbackRes);
return;
}
mImageViews.put(imageview, url);
Bitmap bitmap = mMemoryCache.get(url);
if (bitmap != null) {
imageview.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageview);
imageview.setImageResource(mFallbackRes);
}
}
private void copyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f, ImageView imageview) {
try {
// decode image size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, options);
// Find the correct scale value. It should be the power of 2.
int width_tmp = options.outWidth, height_tmp = options.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < mRequiredSize || height_tmp / 2 < mRequiredSize) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
private Bitmap getBitmapFromFile(File file, ImageView imageview) {
if (file == null) return null;
File f = mFileCache.getFile(file);
// from SD cache
Bitmap bitmap = decodeFile(f, imageview);
if (bitmap != null)
return bitmap;
else {
bitmap = decodeFile(file, imageview);
if (bitmap == null) return null;
try {
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
private Bitmap getBitmapFromWeb(URL url, ImageView imageview) {
if (url == null) return null;
File f = mFileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f, imageview);
if (b != null) return b;
// from web
try {
Bitmap bitmap = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
copyStream(is, os);
os.close();
bitmap = decodeFile(f, imageview);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void queuePhoto(File file, ImageView imageview) {
LocalImageToLoad p = new LocalImageToLoad(file, imageview);
mExecutorService.submit(new LocalImageLoader(p));
}
private void queuePhoto(URL url, ImageView imageview) {
WebImageToLoad p = new WebImageToLoad(url, imageview);
mExecutorService.submit(new WebImageLoader(p));
}
boolean imageViewReused(LocalImageToLoad imagetoload) {
Object tag = mImageViews.get(imagetoload.imageview);
if (tag == null || !tag.equals(imagetoload.file)) return true;
return false;
}
boolean imageViewReused(WebImageToLoad imagetoload) {
Object tag = mImageViews.get(imagetoload.imageview);
if (tag == null || !tag.equals(imagetoload.url)) return true;
return false;
}
public class MemoryCache {
private Map<Object, SoftReference<Bitmap>> mCache = Collections
.synchronizedMap(new HashMap<Object, SoftReference<Bitmap>>());
public void clear() {
mCache.clear();
}
public Bitmap get(Object tag) {
if (!mCache.containsKey(tag)) return null;
SoftReference<Bitmap> ref = mCache.get(tag);
return ref.get();
}
public void put(Object id, Bitmap bitmap) {
mCache.put(id, new SoftReference<Bitmap>(bitmap));
}
}
private class FileCache {
private File cacheDir;
public FileCache(Context context) {
/* Find the dir to save cached images. */
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cacheDir = context.getExternalCacheDir();
} else {
cacheDir = context.getCacheDir();
}
if (cacheDir != null && !cacheDir.exists()) {
cacheDir.mkdirs();
}
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null) return;
for (File f : files) {
f.delete();
}
}
/**
* I identify images by hashcode. Not a perfect solution, good for the
* demo.
*/
public File getFile(Object tag) {
String filename = String.valueOf(tag.hashCode());
File f = new File(cacheDir, filename);
return f;
}
}
// Used to display bitmap in the UI thread
private class LocalBitmapDisplayer implements Runnable {
Bitmap bitmap;
LocalImageToLoad imagetoload;
public LocalBitmapDisplayer(Bitmap b, LocalImageToLoad p) {
bitmap = b;
imagetoload = p;
}
@Override
public void run() {
if (imageViewReused(imagetoload)) return;
if (bitmap != null) {
imagetoload.imageview.setImageBitmap(bitmap);
} else {
imagetoload.imageview.setImageResource(mFallbackRes);
}
}
}
private class LocalImageLoader implements Runnable {
LocalImageToLoad imagetoload;
LocalImageLoader(LocalImageToLoad imagetoload) {
this.imagetoload = imagetoload;
}
@Override
public void run() {
if (imageViewReused(imagetoload) || imagetoload.file == null) return;
Bitmap bmp = getBitmapFromFile(imagetoload.file, imagetoload.imageview);
mMemoryCache.put(imagetoload.file, bmp);
if (imageViewReused(imagetoload)) return;
LocalBitmapDisplayer bd = new LocalBitmapDisplayer(bmp, imagetoload);
Activity a = (Activity) imagetoload.imageview.getContext();
a.runOnUiThread(bd);
}
}
private class LocalImageToLoad {
public File file;
public ImageView imageview;
public LocalImageToLoad(File file, ImageView imageview) {
this.file = file;
this.imageview = imageview;
}
}
// Used to display bitmap in the UI thread
private class WebBitmapDisplayer implements Runnable {
Bitmap bitmap;
WebImageToLoad imagetoload;
public WebBitmapDisplayer(Bitmap b, WebImageToLoad p) {
bitmap = b;
imagetoload = p;
}
@Override
public void run() {
if (imageViewReused(imagetoload)) return;
if (bitmap != null) {
imagetoload.imageview.setImageBitmap(bitmap);
} else {
imagetoload.imageview.setImageResource(mFallbackRes);
}
}
}
private class WebImageLoader implements Runnable {
WebImageToLoad imagetoload;
WebImageLoader(WebImageToLoad imagetoload) {
this.imagetoload = imagetoload;
}
@Override
public void run() {
if (imageViewReused(imagetoload) || imagetoload.url == null) return;
Bitmap bmp = getBitmapFromWeb(imagetoload.url, imagetoload.imageview);
mMemoryCache.put(imagetoload.url, bmp);
if (imageViewReused(imagetoload)) return;
WebBitmapDisplayer bd = new WebBitmapDisplayer(bmp, imagetoload);
Activity a = (Activity) imagetoload.imageview.getContext();
a.runOnUiThread(bd);
}
}
// Task for the queue
private class WebImageToLoad {
public URL url;
public ImageView imageview;
public WebImageToLoad(URL url, ImageView imageview) {
this.url = url;
this.imageview = imageview;
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/LazyImageLoader.java
|
Java
|
gpl3
| 10,250
|
package org.yammp.util;
import java.lang.reflect.InvocationTargetException;
import android.util.Log;
/**
* An Equalizer is used to alter the frequency response of a particular music
* source or of the main output mix.
* <p>
* An application creates an Equalizer object to instantiate and control an
* Equalizer engine in the audio framework. The application can either simply
* use predefined presets or have a more precise control of the gain in each
* frequency band controlled by the equalizer.
* <p>
* The methods, parameter types and units exposed by the Equalizer
* implementation are directly mapping those defined by the OpenSL ES 1.0.1
* Specification (http://www.khronos.org/opensles/) for the SLEqualizerItf
* interface. Please refer to this specification for more details.
* <p>
* To attach the Equalizer to a particular AudioTrack or MediaPlayer, specify
* the audio session ID of this AudioTrack or MediaPlayer when constructing the
* Equalizer. If the audio session ID 0 is specified, the Equalizer applies to
* the main audio output mix.
* <p>
* Creating an Equalizer on the output mix (audio session 0) requires permission
* {@link android.Manifest.permission#MODIFY_AUDIO_SETTINGS}
* <p>
* See {@link android.media.MediaPlayer#getAudioSessionId()} for details on
* audio sessions.
* <p>
* See {@link android.media.audiofx.AudioEffect} class for more details on
* controlling audio effects.
*
* @author mariotaku
*
*/
public class EqualizerWrapper {
private Object mEqualizer = null;
/**
* Class constructor.
*
* @param priority
* the priority level requested by the application for
* controlling the Equalizer engine. As the same engine can be
* shared by several applications, this parameter indicates how
* much the requesting application needs control of effect
* parameters. The normal priority is 0, above normal is a
* positive number, below normal a negative number.
* @param audioSession
* system wide unique audio session identifier. The Equalizer
* will be attached to the MediaPlayer or AudioTrack in the same
* audio session.
*
* @throws RuntimeException
* @throws UnsupportedOperationException
* @throws IllegalStateException
* @throws IllegalArgumentException
*/
public EqualizerWrapper(int priority, int audioSession) {
try {
mEqualizer = Class.forName("android.media.audiofx.Equalizer")
.getConstructor(new Class[] { int.class, int.class })
.newInstance(new Object[] { priority, audioSession });
return;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mEqualizer = null;
}
/**
* Gets the band that has the most effect on the given frequency.
*
* @param frequency
* frequency in milliHertz which is to be equalized via the
* returned band.
* @return the frequency band that has most effect on the given frequency.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public short getBand(int frequency) {
if (mEqualizer == null) return 0;
try {
return (Short) mEqualizer.getClass().getMethod("getBand", new Class[] { int.class })
.invoke(mEqualizer, new Object[] { frequency });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets the frequency range of the given frequency band.
*
* @param band
* frequency band whose frequency range is requested. The
* numbering of the bands starts from 0 and ends at (number of
* bands - 1).
* @return the frequency range in millHertz in an array of integers. The
* first element is the lower limit of the range, the second element
* the upper limit.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public int[] getBandFreqRange(short band) {
if (mEqualizer == null) return null;
try {
return (int[]) mEqualizer.getClass()
.getMethod("getBandFreqRange", new Class[] { short.class })
.invoke(mEqualizer, new Object[] { band });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
/**
* Gets the gain set for the given equalizer band.
*
* @param band
* frequency band whose gain is requested. The numbering of the
* bands starts from 0 and ends at (number of bands - 1).
* @return the gain in millibels of the given band.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public short getBandLevel(short band) {
if (mEqualizer == null) return 0;
try {
return (Short) mEqualizer.getClass()
.getMethod("getBandLevel", new Class[] { short.class })
.invoke(mEqualizer, new Object[] { band });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets the level range for use by {@link #setBandLevel(short,short)}. The
* level is expressed in milliBel.
*
* @return the band level range in an array of short integers. The first
* element is the lower limit of the range, the second element the
* upper limit.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public short[] getBandLevelRange() {
if (mEqualizer == null) return null;
try {
return (short[]) mEqualizer.getClass().getMethod("getBandLevelRange", new Class[] {})
.invoke(mEqualizer, new Object[] {});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
/**
* Gets the center frequency of the given band.
*
* @param band
* frequency band whose center frequency is requested. The
* numbering of the bands starts from 0 and ends at (number of
* bands - 1).
* @return the center frequency in milliHertz
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public int getCenterFreq(short band) {
if (mEqualizer == null) return 0;
try {
return (Integer) mEqualizer.getClass()
.getMethod("getCenterFreq", new Class[] { short.class })
.invoke(mEqualizer, new Object[] { band });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets current preset.
*
* @return the preset that is set at the moment.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public short getCurrentPreset() {
if (mEqualizer == null) return 0;
try {
return (Short) mEqualizer.getClass().getMethod("getCurrentPreset", new Class[] {})
.invoke(mEqualizer, new Object[] {});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets the number of frequency bands supported by the Equalizer engine.
*
* @return the number of bands
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public short getNumberOfBands() {
if (mEqualizer == null) return 0;
try {
return (Short) mEqualizer.getClass().getMethod("getNumberOfBands", new Class[] {})
.invoke(mEqualizer, new Object[] {});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets the total number of presets the equalizer supports. The presets will
* have indices [0, number of presets-1].
*
* @return the number of presets the equalizer supports.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public short getNumberOfPresets() {
if (mEqualizer == null) return 0;
try {
return (Short) mEqualizer.getClass().getMethod("getNumberOfPresets", new Class[] {})
.invoke(mEqualizer, new Object[] {});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return 0;
}
/**
* Gets the preset name based on the index.
*
* @param preset
* index of the preset. The valid range is [0, number of
* presets-1].
* @return a string containing the name of the given preset.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
*/
public String getPresetName(short preset) {
if (mEqualizer == null) return null;
try {
return (String) mEqualizer.getClass()
.getMethod("getPresetName", new Class[] { short.class })
.invoke(mEqualizer, new Object[] { preset });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
/**
* Releases the native AudioEffect resources. It is a good practice to
* release the effect engine when not in use as control can be returned to
* other applications or the native resources released.
*/
public void release() {
if (mEqualizer == null) return;
try {
mEqualizer.getClass().getMethod("release", new Class[] {})
.invoke(mEqualizer, new Object[] {});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* Sets the given equalizer band to the given gain value.
*
* @param band
* frequency band that will have the new gain. The numbering of
* the bands starts from 0 and ends at (number of bands - 1).
* @param level
* new gain in millibels that will be set to the given band.
* getBandLevelRange() will define the maximum and minimum
* values.
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
* @see #getNumberOfBands()
*/
public void setBandLevel(short band, short level) {
if (mEqualizer == null) return;
try {
mEqualizer.getClass()
.getMethod("setBandLevel", new Class[] { short.class, short.class })
.invoke(mEqualizer, new Object[] { band, level });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* Enable or disable the effect. Creating an audio effect does not
* automatically apply this effect on the audio source. It creates the
* resources necessary to process this effect but the audio signal is still
* bypassed through the effect engine. Calling this method will make that
* the effect is actually applied or not to the audio content being played
* in the corresponding audio session.
*
* @param enabled
* the requested enable state
* @return {@link android.media.audiofx.AudioEffect#SUCCESS} in case of
* success,
* {@link android.media.audiofx.AudioEffect#ERROR_INVALID_OPERATION}
* or {@link android.media.audiofx.AudioEffect#ERROR_DEAD_OBJECT} in
* case of failure.
* @throws IllegalStateException
*/
public int setEnabled(boolean enabled) {
if (mEqualizer == null) return -1;
try {
return (Integer) mEqualizer.getClass()
.getMethod("setEnabled", new Class[] { boolean.class })
.invoke(mEqualizer, new Object[] { enabled });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return -1;
}
/**
* Sets the equalizer according to the given preset.
*
* @param preset
* new preset that will be taken into use. The valid range is [0,
* number of presets-1].
* @throws IllegalStateException
* @throws IllegalArgumentException
* @throws UnsupportedOperationException
* @see #getNumberOfPresets()
*/
public void usePreset(short preset) {
if (mEqualizer == null) return;
try {
mEqualizer.getClass().getMethod("usePreset", new Class[] { short.class })
.invoke(mEqualizer, new Object[] { preset });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* Detect whether equalizer is supported.
*
* @return whether equalizer is supported.
*/
public static boolean isSupported() {
try {
Class.forName("android.media.audiofx.Equalizer");
} catch (ClassNotFoundException e) {
Log.w("EuqalizerWrapper", "Equalizer is not supported!");
return false;
}
return true;
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/EqualizerWrapper.java
|
Java
|
gpl3
| 15,062
|
package org.yammp.util;
public class VisualizerWrapper {
public static VisualizerCompat getInstance(int audioSessionId, int fps) {
if (isAudioFXSupported())
return new VisualizerCompatAudioFX(audioSessionId, fps);
else if (isScoopSupported()) return new VisualizerCompatScoop(audioSessionId, fps);
return null;
}
private static boolean isAudioFXSupported() {
try {
Class.forName("android.media.audiofx.Visualizer");
} catch (Exception e) {
return false;
}
return true;
}
private static boolean isScoopSupported() {
try {
Class.forName("android.media.MediaPlayer").getMethod("snoop", short[].class, int.class);
} catch (Exception e) {
return false;
}
return true;
}
public interface OnDataChangedListener {
public void onFftDataChanged(byte[] data, int len);
public void onWaveDataChanged(byte[] data, int len, boolean scoop);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/VisualizerWrapper.java
|
Java
|
gpl3
| 887
|
package org.yammp.util;
import android.content.ContextWrapper;
public class ServiceToken {
ContextWrapper mWrappedContext;
ServiceToken(ContextWrapper context) {
mWrappedContext = context;
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/ServiceToken.java
|
Java
|
gpl3
| 202
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import android.database.AbstractCursor;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.util.Log;
/**
* A variant of MergeCursor that sorts the cursors being merged. If decent
* performance is ever obtained, it can be put back under android.database.
*/
public class SortCursor extends AbstractCursor {
private static final String TAG = "SortCursor";
private Cursor mCursor; // updated in onMove
private Cursor[] mCursors;
private int[] mSortColumns;
private final int ROWCACHESIZE = 64;
private int mRowNumCache[] = new int[ROWCACHESIZE];
private int mCursorCache[] = new int[ROWCACHESIZE];
private int mCurRowNumCache[][];
private int mLastCacheHit = -1;
private DataSetObserver mObserver = new DataSetObserver() {
@Override
public void onChanged() {
// Reset our position so the optimizations in move-related code
// don't screw us over
mPos = -1;
}
@Override
public void onInvalidated() {
mPos = -1;
}
};
public SortCursor(Cursor[] cursors, String sortcolumn) {
mCursors = cursors;
int length = mCursors.length;
mSortColumns = new int[length];
for (int i = 0; i < length; i++) {
if (mCursors[i] == null) {
continue;
}
// Register ourself as a data set observer
mCursors[i].registerDataSetObserver(mObserver);
mCursors[i].moveToFirst();
// We don't catch the exception
mSortColumns[i] = mCursors[i].getColumnIndexOrThrow(sortcolumn);
}
mCursor = null;
String smallest = "";
for (int j = 0; j < length; j++) {
if (mCursors[j] == null || mCursors[j].isAfterLast()) {
continue;
}
String current = mCursors[j].getString(mSortColumns[j]);
if (mCursor == null || current.compareToIgnoreCase(smallest) < 0) {
smallest = current;
mCursor = mCursors[j];
}
}
for (int i = mRowNumCache.length - 1; i >= 0; i--) {
mRowNumCache[i] = -2;
}
mCurRowNumCache = new int[ROWCACHESIZE][length];
}
@Override
public void close() {
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] == null) {
continue;
}
mCursors[i].close();
}
}
@Override
public void deactivate() {
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] == null) {
continue;
}
mCursors[i].deactivate();
}
}
@Override
public byte[] getBlob(int column) {
return mCursor.getBlob(column);
}
@Override
public String[] getColumnNames() {
if (mCursor != null)
return mCursor.getColumnNames();
else {
// All of the cursors may be empty, but they can still return
// this information.
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] != null) return mCursors[i].getColumnNames();
}
throw new IllegalStateException("No cursor that can return names");
}
}
@Override
public int getCount() {
int count = 0;
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] != null) {
count += mCursors[i].getCount();
}
}
return count;
}
@Override
public double getDouble(int column) {
return mCursor.getDouble(column);
}
@Override
public float getFloat(int column) {
return mCursor.getFloat(column);
}
@Override
public int getInt(int column) {
return mCursor.getInt(column);
}
@Override
public long getLong(int column) {
return mCursor.getLong(column);
}
@Override
public short getShort(int column) {
return mCursor.getShort(column);
}
@Override
public String getString(int column) {
return mCursor.getString(column);
}
@Override
public boolean isNull(int column) {
return mCursor.isNull(column);
}
@Override
public boolean onMove(int oldPosition, int newPosition) {
if (oldPosition == newPosition) return true;
/*
* Find the right cursor Because the client of this cursor (the
* listadapter/view) tends to jump around in the cursor somewhat, a
* simple cache strategy is used to avoid having to search all cursors
* from the start. TODO: investigate strategies for optimizing random
* access and reverse-order access.
*/
int cache_entry = newPosition % ROWCACHESIZE;
if (mRowNumCache[cache_entry] == newPosition) {
int which = mCursorCache[cache_entry];
mCursor = mCursors[which];
if (mCursor == null) {
Log.w(TAG, "onMove: cache results in a null cursor.");
return false;
}
mCursor.moveToPosition(mCurRowNumCache[cache_entry][which]);
mLastCacheHit = cache_entry;
return true;
}
mCursor = null;
int length = mCursors.length;
if (mLastCacheHit >= 0) {
for (int i = 0; i < length; i++) {
if (mCursors[i] == null) {
continue;
}
mCursors[i].moveToPosition(mCurRowNumCache[mLastCacheHit][i]);
}
}
if (newPosition < oldPosition || oldPosition == -1) {
for (int i = 0; i < length; i++) {
if (mCursors[i] == null) {
continue;
}
mCursors[i].moveToFirst();
}
oldPosition = 0;
}
if (oldPosition < 0) {
oldPosition = 0;
}
// search forward to the new position
int smallestIdx = -1;
for (int i = oldPosition; i <= newPosition; i++) {
String smallest = "";
smallestIdx = -1;
for (int j = 0; j < length; j++) {
if (mCursors[j] == null || mCursors[j].isAfterLast()) {
continue;
}
String current = mCursors[j].getString(mSortColumns[j]);
if (smallestIdx < 0 || current.compareToIgnoreCase(smallest) < 0) {
smallest = current;
smallestIdx = j;
}
}
if (i == newPosition) {
break;
}
if (mCursors[smallestIdx] != null) {
mCursors[smallestIdx].moveToNext();
}
}
mCursor = mCursors[smallestIdx];
mRowNumCache[cache_entry] = newPosition;
mCursorCache[cache_entry] = smallestIdx;
for (int i = 0; i < length; i++) {
if (mCursors[i] != null) {
mCurRowNumCache[cache_entry][i] = mCursors[i].getPosition();
}
}
mLastCacheHit = -1;
return true;
}
@Override
public void registerDataSetObserver(DataSetObserver observer) {
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] != null) {
mCursors[i].registerDataSetObserver(observer);
}
}
}
@Override
public boolean requery() {
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] == null) {
continue;
}
if (mCursors[i].requery() == false) return false;
}
return true;
}
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
int length = mCursors.length;
for (int i = 0; i < length; i++) {
if (mCursors[i] != null) {
mCursors[i].unregisterDataSetObserver(observer);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/SortCursor.java
|
Java
|
gpl3
| 7,300
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import java.util.ArrayList;
import org.yammp.Constants;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.FloatMath;
public class ShakeListener implements SensorEventListener, Constants {
private boolean mFirstSensorUpdate, mFirstDeltaUpdate = true;
private long mCurrentTimeStamp, mLastShakeTimeStamp;
private long mShakeInterval = 250;
private long mLastUpdateTime;
private float mLastX, mLastY, mLastZ;
private float mCurrentSpeed, mLastSpeed;
private SensorManager mSensorManager;
private ArrayList<OnShakeListener> mListeners;
private float mShakeThreshold = DEFAULT_SHAKING_THRESHOLD;
public ShakeListener(Context context) {
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
mListeners = new ArrayList<OnShakeListener>();
}
public float getShakeThreshold() {
return mShakeThreshold;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
mCurrentTimeStamp = event.timestamp / 1000 / 1000;
float eventX = event.values[SensorManager.DATA_X], eventY = event.values[SensorManager.DATA_Y], eventZ = event.values[SensorManager.DATA_Z];
if (mFirstSensorUpdate) {
mLastX = eventX;
mLastY = eventY;
mLastZ = eventZ;
mLastUpdateTime = mCurrentTimeStamp;
mFirstDeltaUpdate = true;
mFirstSensorUpdate = false;
return;
}
float deltaX = eventX - mLastX, deltaY = eventY - mLastY, deltaZ = eventZ - mLastZ;
mLastX = eventX;
mLastY = eventY;
mLastZ = eventZ;
float deltaTimeForSpeed = mCurrentTimeStamp - mLastUpdateTime;
mLastUpdateTime = mCurrentTimeStamp;
if (mFirstDeltaUpdate) {
mCurrentSpeed = FloatMath.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ)
/ deltaTimeForSpeed;
mFirstDeltaUpdate = false;
return;
}
mLastSpeed = mCurrentSpeed;
mCurrentSpeed = FloatMath.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ)
/ deltaTimeForSpeed;
float delta = Math.abs(mLastSpeed - mCurrentSpeed) / deltaTimeForSpeed * 1000 * 1000;
if (delta > mShakeThreshold) {
if (mCurrentTimeStamp > mLastShakeTimeStamp + mShakeInterval) {
mLastShakeTimeStamp = mCurrentTimeStamp;
notifyListeners();
}
}
}
public void registerOnShakeListener(OnShakeListener listener) {
if (!mListeners.contains(listener)) {
mListeners.add(listener);
}
}
public void setShakeThreshold(float threshold) {
mShakeThreshold = threshold;
}
public void start() throws UnsupportedOperationException {
Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (sensor == null) throw new UnsupportedOperationException();
boolean success = mSensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_UI);
if (!success) throw new UnsupportedOperationException();
mFirstSensorUpdate = true;
}
public void stop() {
if (mSensorManager != null) {
mSensorManager.unregisterListener(this);
}
}
public void unregisterOnShakeListener(OnShakeListener listener) {
mListeners.remove(listener);
}
private void notifyListeners() {
for (OnShakeListener listener : mListeners) {
listener.onShake();
}
}
public interface OnShakeListener {
void onShake();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/ShakeListener.java
|
Java
|
gpl3
| 4,049
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import net.roarsoftware.lastfm.Album;
import net.roarsoftware.lastfm.Artist;
import net.roarsoftware.lastfm.Image;
import net.roarsoftware.lastfm.ImageSize;
import org.yammp.Constants;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class ImageDownloader implements Constants {
public void getArtistImage(String artist) {
Image[] images = Artist
.getImages(artist, LASTFM_APIKEY)
.getPageResults()
.toArray(new Image[Artist.getImages(artist, LASTFM_APIKEY).getPageResults().size()]);
for (Image image : images) {
Log.d("ImageDownloader", "url = " + image.getImageURL(ImageSize.ORIGINAL));
}
}
public String getArtistQueryURL(String mArtistTitle, int limit) {
return "http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="
+ URLEncoder.encode(mArtistTitle) + "&api_key=" + LASTFM_APIKEY + "&limit=" + limit;
}
public static Bitmap getCoverBitmap(String urlString) {
try {
URL url = new URL(urlString);
return getCoverBitmap(url);
} catch (Exception e) {
return null;
}
}
public static Bitmap getCoverBitmap(URL url) {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
return BitmapFactory.decodeStream(is);
} catch (Exception e) {
return null;
}
}
public static String getCoverUrl(String artist, String album) throws Exception {
Album albumInfo = Album.getInfo(artist, album, LASTFM_APIKEY);
return albumInfo.getImageURL(ImageSize.MEGA);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/ImageDownloader.java
|
Java
|
gpl3
| 2,394
|
package org.yammp.util;
import java.util.Timer;
import java.util.TimerTask;
import org.yammp.util.VisualizerWrapper.OnDataChangedListener;
import android.media.audiofx.Visualizer;
import android.os.Handler;
import android.os.Message;
public class VisualizerCompatAudioFX extends VisualizerCompat {
private OnDataChangedListener mListener;
private Timer mTimer;
private boolean mWaveEnabled, mFftEnabled;
private Visualizer mVisualizer;
private Handler mVisualizerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case WAVE_CHANGED:
if (mListener != null) {
byte[] wave_data = (byte[]) ((Object[]) msg.obj)[0];
int len = (Integer) ((Object[]) msg.obj)[1];
mListener.onWaveDataChanged(wave_data, (int) (len * accuracy), false);
}
break;
case FFT_CHANGED:
if (mListener != null) {
byte[] fft_data = (byte[]) ((Object[]) msg.obj)[0];
int len = (Integer) ((Object[]) msg.obj)[1];
mListener.onFftDataChanged(fft_data, (int) (len * accuracy));
}
break;
}
}
};
public VisualizerCompatAudioFX(int audioSessionId, int fps) {
super(audioSessionId, fps);
mVisualizer = new Visualizer(audioSessionId);
duration = 1000 / fps;
mTimer = new Timer();
}
@Override
public boolean getEnabled() {
return mVisualizer.getEnabled();
}
@Override
public void release() {
mVisualizer.setEnabled(false);
mVisualizer.release();
}
@Override
public void setAccuracy(float accuracy) {
if (accuracy > 1.0f || accuracy <= 0.0f)
throw new IllegalArgumentException(
"Invalid accuracy value! Allowed value range is \"0 < accuracy <= 1.0\"!");
mVisualizer.setCaptureSize((int) (Visualizer.getMaxCaptureRate() * accuracy));
}
@Override
public void setEnabled(boolean enabled) {
mVisualizer.setEnabled(enabled);
if (mTimer != null) {
if (enabled) {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new VisualizerTimer(), 0, duration);
} else {
mTimer.cancel();
}
}
}
@Override
public void setFftEnabled(boolean fft) {
mFftEnabled = fft;
}
@Override
public void setOnDataChangedListener(OnDataChangedListener listener) {
mListener = listener;
}
@Override
public void setWaveFormEnabled(boolean wave) {
mWaveEnabled = wave;
}
private class VisualizerTimer extends TimerTask {
@Override
public void run() {
byte[] wave_data = new byte[mVisualizer.getCaptureSize()];
byte[] fft_data = new byte[mVisualizer.getCaptureSize()];
if (mWaveEnabled) {
int ret = Visualizer.ERROR;
try {
ret = mVisualizer.getWaveForm(wave_data);
} catch (IllegalStateException e) {
}
if (ret == Visualizer.SUCCESS && wave_data != null) {
Message msg = new Message();
msg.what = WAVE_CHANGED;
msg.obj = new Object[] { wave_data, wave_data.length };
mVisualizerHandler.sendMessage(msg);
}
}
if (mFftEnabled) {
int ret = Visualizer.ERROR;
try {
ret = mVisualizer.getFft(fft_data);
} catch (IllegalStateException e) {
}
if (ret == Visualizer.SUCCESS && fft_data != null) {
Message msg = new Message();
msg.what = FFT_CHANGED;
msg.obj = new Object[] { fft_data, fft_data.length };
mVisualizerHandler.sendMessage(msg);
}
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/VisualizerCompatAudioFX.java
|
Java
|
gpl3
| 3,326
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import android.graphics.Paint;
public class LyricsSplitter {
public static String split(String line, float pixels) {
if (measureString(line, pixels) <= 294)
return line;
else {
int half = line.length() / 2;
for (int i = 0; i < half / 2; i++) {
int pos = half - i;
char c = line.charAt(pos);
if (c == ' ' || c == '\u3000')
return line.substring(0, pos).trim() + "\n"
+ line.substring(pos + 1, line.length()).trim();
else if (c == '(' || c == '<' || c == '[' || c == '{' || c == '\uFF08'
|| c == '\u3010' || c == '\u3016' || c == '\u300C' || c == '/')
return line.substring(0, pos).trim() + "\n"
+ line.substring(pos, line.length()).trim();
else if (c == ')' || c == '>' || c == ']' || c == '}' || c == '\uFF09'
|| c == '\u3011' || c == '\u3017' || c == '\u300D' || c == ','
|| c == '\uFF0C' || c == '\u3002')
return line.substring(0, pos + 1).trim() + "\n"
+ line.substring(pos + 1, line.length()).trim();
pos = half + i + 1;
c = line.charAt(pos);
if (c == ' ' || c == '\u3000')
return line.substring(0, pos).trim() + "\n"
+ line.substring(pos + 1, line.length()).trim();
else if (c == '(' || c == '<' || c == '[' || c == '{' || c == '\uFF08'
|| c == '\u3010' || c == '\u3016' || c == '\u300C' || c == '/')
return line.substring(0, pos).trim() + "\n"
+ line.substring(pos, line.length()).trim();
else if (c == ')' || c == '>' || c == ']' || c == '}' || c == '\uFF09'
|| c == '\u3011' || c == '\u3017' || c == '\u300D' || c == ','
|| c == '\uFF0C' || c == '\u3002')
return line.substring(0, pos + 1).trim() + "\n"
+ line.substring(pos + 1, line.length()).trim();
}
return line.substring(0, half) + "\n" + line.substring(half, line.length());
}
}
private static float measureString(String line, float pixels) {
Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize(pixels);
return mTextPaint.measureText(line);
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/LyricsSplitter.java
|
Java
|
gpl3
| 2,671
|
/*
* Copyright (C) 2012 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.yammp.Constants;
import org.yammp.IMusicPlaybackService;
import org.yammp.MusicPlaybackService;
import org.yammp.R;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Audio.Genres;
import android.provider.MediaStore.Audio.Playlists;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;
public class MediaUtils implements Constants {
private Context mContext;
private static IMusicPlaybackService mService = null;
private static HashMap<Context, ServiceBinder> mConnectionMap = new HashMap<Context, ServiceBinder>();
private final static long[] mEmptyList = new long[0];
private static ContentValues[] sContentValuesCache = null;
/*
* Try to use String.format() as little as possible, because it creates a
* new Formatter every time you call it, which is very inefficient. Reusing
* an existing Formatter more than tripled the speed of makeTimeString().
* This Formatter/StringBuilder are also used by makeAlbumSongsLabel()
*/
private static StringBuilder sFormatBuilder = new StringBuilder();
private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
private static final Object[] sTimeArgs = new Object[5];
private static final BitmapFactory.Options mBitmapOptionsCache = new BitmapFactory.Options();
private static final BitmapFactory.Options mBitmapOptions = new BitmapFactory.Options();
private static final Uri mArtworkUri = Uri.parse("content://media/external/audio/albumart");
private static final HashMap<Long, Bitmap> mArtBitmapCache = new HashMap<Long, Bitmap>();
private static final HashMap<Long, Drawable> mArtCache = new HashMap<Long, Drawable>();
private static int mArtCacheId = -1;
static {
// for the cache,
// 565 is faster to decode and display
// and we don't want to dither here because the image will be scaled
// down later
mBitmapOptionsCache.inPreferredConfig = Bitmap.Config.RGB_565;
mBitmapOptionsCache.inDither = false;
mBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
mBitmapOptions.inDither = false;
}
private static LogEntry[] mMusicLog = new LogEntry[100];
private static int mLogPtr = 0;
private static Time mTime = new Time();
public MediaUtils(Context context) {
mContext = context;
}
public void addToCurrentPlaylist(long[] list) {
if (mService == null) return;
try {
mService.enqueue(list, MusicPlaybackService.ACTION_LAST);
String message = mContext.getResources().getQuantityString(
R.plurals.NNNtrackstoplaylist, list.length, Integer.valueOf(list.length));
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
} catch (RemoteException ex) {
}
}
public void addToFavorites(long id) {
long favorites_id;
if (id < 0) {
// this shouldn't happen (the menuitems shouldn't be visible
// unless the selected item represents something playable
Log.e(LOGTAG_MUSICUTILS, "playlist id " + id + " is invalid.");
} else {
ContentResolver resolver = mContext.getContentResolver();
// need to determine the number of items currently in the playlist,
// so the play_order field can be maintained.
String favorites_where = Audio.Playlists.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'";
String[] favorites_cols = new String[] { Audio.Playlists._ID };
Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor = resolver.query(favorites_uri, favorites_cols, favorites_where, null,
null);
if (cursor.getCount() <= 0) {
favorites_id = createPlaylist(PLAYLIST_NAME_FAVORITES);
} else {
cursor.moveToFirst();
favorites_id = cursor.getLong(0);
cursor.close();
}
String[] cols = new String[] { Playlists.Members.AUDIO_ID };
Uri uri = Playlists.Members.getContentUri("external", favorites_id);
Cursor cur = resolver.query(uri, cols, null, null, null);
int base = cur.getCount();
cur.moveToFirst();
while (!cur.isAfterLast()) {
if (cur.getLong(0) == id) return;
cur.moveToNext();
}
cur.close();
ContentValues values = new ContentValues();
values.put(Playlists.Members.AUDIO_ID, id);
values.put(Playlists.Members.PLAY_ORDER, base + 1);
resolver.insert(uri, values);
}
}
public void addToPlaylist(long[] ids, long playlistid) {
if (ids == null) {
// this shouldn't happen (the menuitems shouldn't be visible
// unless the selected item represents something playable
Log.e("MusicBase", "ListSelection null");
} else {
int size = ids.length;
ContentResolver resolver = mContext.getContentResolver();
// need to determine the number of items currently in the playlist,
// so the play_order field can be maintained.
String[] cols = new String[] { "count(*)" };
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
Cursor cur = resolver.query(uri, cols, null, null, null);
cur.moveToFirst();
int base = cur.getInt(0);
cur.close();
int numinserted = 0;
for (int i = 0; i < size; i += 1000) {
makeInsertItems(ids, i, 1000, base);
numinserted += resolver.bulkInsert(uri, sContentValuesCache);
}
String message = mContext.getResources().getQuantityString(
R.plurals.NNNtrackstoplaylist, numinserted, numinserted);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
// mLastPlaylistSelected = playlistid;
}
}
public ServiceToken bindToService() {
return bindToService(null);
}
public ServiceToken bindToService(ServiceConnection callback) {
ContextWrapper cw = new ContextWrapper(mContext);
cw.startService(new Intent(cw, MusicPlaybackService.class));
ServiceBinder sb = new ServiceBinder(callback);
if (cw.bindService(new Intent(cw, MusicPlaybackService.class), sb, 0)) {
mConnectionMap.put(cw, sb);
return new ServiceToken(cw);
}
Log.e("Music", "Failed to bind to service");
return null;
}
public void clearAlbumArtCache() {
synchronized (mArtBitmapCache) {
mArtBitmapCache.clear();
}
}
public void clearPlaylist(int plid) {
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", plid);
mContext.getContentResolver().delete(uri, null, null);
return;
}
public void clearQueue() {
if (mService == null) return;
try {
mService.removeTracks(0, Integer.MAX_VALUE);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public long createPlaylist(String name) {
if (name != null && name.length() > 0) {
ContentResolver resolver = mContext.getContentResolver();
String[] cols = new String[] { MediaStore.Audio.Playlists.NAME };
String whereclause = MediaStore.Audio.Playlists.NAME + " = '" + name + "'";
Cursor cur = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, cols,
whereclause, null, null);
if (cur.getCount() <= 0) {
ContentValues values = new ContentValues(1);
values.put(MediaStore.Audio.Playlists.NAME, name);
Uri uri = resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values);
return Long.parseLong(uri.getLastPathSegment());
}
return -1;
}
return -1;
}
public void debugDump(PrintWriter out) {
for (int i = 0; i < mMusicLog.length; i++) {
int idx = mLogPtr + i;
if (idx >= mMusicLog.length) {
idx -= mMusicLog.length;
}
LogEntry entry = mMusicLog[idx];
if (entry != null) {
entry.dump(out);
}
}
}
public void debugLog(Object o) {
mMusicLog[mLogPtr] = new LogEntry(o);
mLogPtr++;
if (mLogPtr >= mMusicLog.length) {
mLogPtr = 0;
}
}
public void deleteLyrics(long[] list) {
String[] cols = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID };
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media._ID + " IN (");
for (int i = 0; i < list.length; i++) {
where.append(list[i]);
if (i < list.length - 1) {
where.append(",");
}
}
where.append(")");
Cursor c = query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols, where.toString(), null,
null);
int mDeletedLyricsCount = 0;
if (c != null) {
// remove files from card
c.moveToFirst();
while (!c.isAfterLast()) {
String name = c.getString(1);
String lyrics = name.substring(0, name.lastIndexOf(".")) + ".lrc";
File f = new File(lyrics);
try { // File.delete can throw a security exception
if (!f.delete()) {
// I'm not sure if we'd ever get here (deletion would
// have to fail, but no exception thrown)
Log.e(LOGTAG_MUSICUTILS, "Failed to delete file " + lyrics);
} else {
mDeletedLyricsCount += 1;
}
c.moveToNext();
} catch (SecurityException ex) {
c.moveToNext();
}
}
c.close();
}
String message = mContext.getResources().getQuantityString(R.plurals.NNNlyricsdeleted,
mDeletedLyricsCount, Integer.valueOf(mDeletedLyricsCount));
reloadLyrics();
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
public void deleteTracks(long[] list) {
String[] cols = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID };
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media._ID + " IN (");
for (int i = 0; i < list.length; i++) {
where.append(list[i]);
if (i < list.length - 1) {
where.append(",");
}
}
where.append(")");
Cursor c = query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols, where.toString(), null,
null);
if (c != null) {
// step 1: remove selected tracks from the current playlist, as well
// as from the album art cache
try {
c.moveToFirst();
while (!c.isAfterLast()) {
// remove from current playlist
long id = c.getLong(0);
mService.removeTrack(id);
// remove from album art cache
long artIndex = c.getLong(2);
synchronized (mArtBitmapCache) {
mArtBitmapCache.remove(artIndex);
}
c.moveToNext();
}
} catch (RemoteException ex) {
}
// step 2: remove selected tracks from the database
mContext.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
where.toString(), null);
// step 3: remove files from card
c.moveToFirst();
while (!c.isAfterLast()) {
String name = c.getString(1);
File f = new File(name);
try { // File.delete can throw a security exception
if (!f.delete()) {
// I'm not sure if we'd ever get here (deletion would
// have to fail, but no exception thrown)
Log.e(LOGTAG_MUSICUTILS, "Failed to delete file " + name);
}
c.moveToNext();
} catch (SecurityException ex) {
c.moveToNext();
}
}
c.close();
}
String message = mContext.getResources().getQuantityString(R.plurals.NNNtracksdeleted,
list.length, Integer.valueOf(list.length));
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
// We deleted a number of tracks, which could affect any number of
// things
// in the media content domain, so update everything.
mContext.getContentResolver().notifyChange(Uri.parse("content://media"), null);
}
public String getAlbumName(long album_id, boolean default_name) {
String where = Audio.Albums._ID + "=" + album_id;
String[] cols = new String[] { Audio.Albums.ALBUM };
Uri uri = Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null);
if (cursor.getCount() <= 0) {
if (default_name)
return mContext.getString(R.string.unknown_album);
else
return MediaStore.UNKNOWN_STRING;
} else {
cursor.moveToFirst();
String name = cursor.getString(0);
cursor.close();
if (name == null || MediaStore.UNKNOWN_STRING.equals(name)) {
if (default_name)
return mContext.getString(R.string.unknown_album);
else
return MediaStore.UNKNOWN_STRING;
}
return name;
}
}
public long[] getAllSongs() {
Cursor c = query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media._ID },
MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);
try {
if (c == null || c.getCount() == 0) return null;
int len = c.getCount();
long[] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
return list;
} finally {
if (c != null) {
c.close();
}
}
}
public String getArtistName(long artist_id, boolean default_name) {
String where = Audio.Artists._ID + "=" + artist_id;
String[] cols = new String[] { Audio.Artists.ARTIST };
Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI;
Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null);
if (cursor.getCount() <= 0) {
if (default_name)
return mContext.getString(R.string.unknown_artist);
else
return MediaStore.UNKNOWN_STRING;
} else {
cursor.moveToFirst();
String name = cursor.getString(0);
cursor.close();
if (name == null || MediaStore.UNKNOWN_STRING.equals(name)) {
if (default_name)
return mContext.getString(R.string.unknown_artist);
else
return MediaStore.UNKNOWN_STRING;
}
return name;
}
}
/**
* Get album art for specified album. You should not pass in the album id
* for the "unknown" album here (use -1 instead) This method always returns
* the default album art icon when no album art is found.
*/
public Bitmap getArtwork(long song_id, long album_id) {
return getArtwork(song_id, album_id, true);
}
/**
* Get album art for specified album. You should not pass in the album id
* for the "unknown" album here (use -1 instead)
*/
public Bitmap getArtwork(long song_id, long album_id, boolean allowdefault) {
if (album_id < 0) {
// This is something that is not in the database, so get the album
// art directly
// from the file.
if (song_id >= 0) {
Bitmap bm = getArtworkFromFile(song_id, -1);
if (bm != null) return bm;
}
if (allowdefault) return getDefaultArtwork();
return null;
}
ContentResolver res = mContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(mArtworkUri, album_id);
if (uri != null) {
InputStream in = null;
try {
in = res.openInputStream(uri);
return BitmapFactory.decodeStream(in, null, mBitmapOptions);
} catch (FileNotFoundException ex) {
// The album art thumbnail does not actually exist. Maybe the
// user deleted it, or
// maybe it never existed to begin with.
Bitmap bm = getArtworkFromFile(song_id, album_id);
if (bm != null) {
if (bm.getConfig() == null) {
bm = bm.copy(Bitmap.Config.ARGB_8888, false);
if (bm == null && allowdefault) return getDefaultArtwork();
}
} else if (allowdefault) {
bm = getDefaultArtwork();
}
return bm;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
return null;
}
/**
* Get album art for specified album. This method will not try to fall back
* to getting artwork directly from the file, nor will it attempt to repair
* the database.
*
* @param mContext
* @param album_id
* @param w
* @param h
* @return
*/
public Bitmap getArtworkQuick(long album_id, int w, int h) {
/*
* NOTE: There is in fact a 1 pixel border on the right side in the
* ImageView used to display this drawable. Take it into account now, so
* we don't have to scale later.
*/
w -= 1;
ContentResolver res = mContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(mArtworkUri, album_id);
if (uri != null) {
ParcelFileDescriptor fd = null;
try {
fd = res.openFileDescriptor(uri, "r");
int sampleSize = 1;
// Compute the closest power-of-two scale factor
// and pass that to mBitmapOptionsCache.inSampleSize, which will
// result in faster decoding and better quality
mBitmapOptionsCache.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null,
mBitmapOptionsCache);
int nextWidth = mBitmapOptionsCache.outWidth >> 1;
int nextHeight = mBitmapOptionsCache.outHeight >> 1;
while (nextWidth > w && nextHeight > h) {
sampleSize <<= 1;
nextWidth >>= 1;
nextHeight >>= 1;
}
mBitmapOptionsCache.inSampleSize = sampleSize;
mBitmapOptionsCache.inJustDecodeBounds = false;
Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null,
mBitmapOptionsCache);
if (b != null) {
// finally rescale to exactly the size we need
if (mBitmapOptionsCache.outWidth != w || mBitmapOptionsCache.outHeight != h) {
int value = 0;
if (b.getHeight() <= b.getWidth()) {
value = b.getHeight();
} else {
value = b.getWidth();
}
Bitmap tmp = Bitmap.createBitmap(b, (b.getWidth() - value) / 2,
(b.getHeight() - value) / 2, value, value);
// Bitmap.createScaledBitmap() can return the same
// bitmap
if (tmp != b) {
b.recycle();
}
b = tmp;
}
}
return b;
} catch (FileNotFoundException e) {
} finally {
try {
if (fd != null) {
fd.close();
}
} catch (IOException e) {
}
}
}
return null;
}
public Uri getArtworkUri(long album_id) {
return getArtworkUri(-1, album_id);
}
public Uri getArtworkUri(long song_id, long album_id) {
if (album_id < 0) {
// This is something that is not in the database, so get the album
// art directly
// from the file.
if (song_id >= 0) return getArtworkUriFromFile(song_id, -1);
return null;
}
ContentResolver res = mContext.getContentResolver();
Uri uri = ContentUris.withAppendedId(mArtworkUri, album_id);
if (uri != null) {
InputStream in = null;
try {
in = res.openInputStream(uri);
return uri;
} catch (FileNotFoundException ex) {
// The album art thumbnail does not actually exist. Maybe the
// user deleted it, or
// maybe it never existed to begin with.
return getArtworkUriFromFile(song_id, album_id);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
return null;
}
public Drawable getBackgroundImage(Bitmap orig, int width, int height, float scale) {
if (orig == null) return null;
Bitmap result = Bitmap.createScaledBitmap(orig, (int) (width * scale),
(int) (height * scale), true);
orig.recycle();
orig = null;
Canvas c = new Canvas(result);
c.drawColor(0xD0000000, PorterDuff.Mode.DARKEN);
return new BitmapDrawable(mContext.getResources(), result);
// Paint paint = new Paint();
// paint.setAntiAlias(true);
// paint.setFilterBitmap(true);
// paint.setMaskFilter(new BlurMaskFilter(Math.min(width, height) *
// scale,
// BlurMaskFilter.Blur.NORMAL));
//
// Bitmap result = Bitmap.createBitmap(width, height,
// Bitmap.Config.ARGB_8888);
// Canvas c = new Canvas(result);
// Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height,
// true);
// bitmap1.recycle();
// bitmap1 = null;
// c.drawBitmap(bitmap2, 0, 0, paint);
// c.drawColor(0xD0000000, PorterDuff.Mode.DARKEN);
// bitmap2.recycle();
// bitmap2 = null;
// return new BitmapDrawable(mContext.getResources(), result);
}
public String getBetterGenresWhereClause() {
StringBuilder builder = new StringBuilder();
ContentResolver resolver = mContext.getContentResolver();
String[] genres_cols = new String[] { Audio.Genres._ID };
Uri genres_uri = Audio.Genres.EXTERNAL_CONTENT_URI;
Cursor genres_cursor = resolver.query(genres_uri, genres_cols, null, null, null);
if (genres_cursor != null) {
if (genres_cursor.getCount() <= 0) {
genres_cursor.close();
return null;
}
} else
return null;
builder.append(Audio.Genres._ID + " IN (");
genres_cursor.moveToFirst();
while (!genres_cursor.isAfterLast()) {
long genre_id = genres_cursor.getLong(0);
StringBuilder where = new StringBuilder();
where.append(Genres.Members.IS_MUSIC + "=1");
where.append(" AND " + Genres.Members.TITLE + "!=''");
String[] cols = new String[] { Genres.Members._ID };
Uri uri = Genres.Members.getContentUri(EXTERNAL_VOLUME, genre_id);
Cursor member_cursor = mContext.getContentResolver().query(uri, cols, where.toString(),
null, null);
if (member_cursor != null) {
if (member_cursor.getCount() > 0) {
builder.append(genre_id + ",");
}
member_cursor.close();
}
genres_cursor.moveToNext();
}
genres_cursor.close();
builder.deleteCharAt(builder.length() - 1);
builder.append(")");
return builder.toString();
}
public Drawable getCachedArtwork(long index, BitmapDrawable defaultArtwork) {
Drawable d = null;
synchronized (mArtCache) {
d = mArtCache.get(index);
}
if (d == null) {
d = defaultArtwork;
final Bitmap icon = defaultArtwork.getBitmap();
int w = icon.getWidth();
int h = icon.getHeight();
Bitmap b = getArtworkQuick(index, w, h);
if (b != null) {
d = new BitmapDrawable(b);
synchronized (mArtCache) {
// the cache may have changed since we checked
Drawable value = mArtCache.get(index);
if (value == null) {
mArtCache.put(index, d);
} else {
d = value;
}
}
}
}
return d;
}
public Bitmap getCachedArtworkBitmap(long index, int width, int height) {
Bitmap art = null;
synchronized (mArtBitmapCache) {
art = mArtBitmapCache.get(index);
}
if (art == null) {
art = getArtworkQuick(index, width, height);
if (art != null) {
synchronized (mArtBitmapCache) {
mArtBitmapCache.put(index, art);
}
}
}
return art;
}
public int getCardId() {
ContentResolver res = mContext.getContentResolver();
Cursor c = res.query(Uri.parse("content://media/external/fs_id"), null, null, null, null);
int id = -1;
if (c != null) {
c.moveToFirst();
id = c.getInt(0);
c.close();
}
return id;
}
public long getCurrentAlbumId() {
if (mService != null) {
try {
return mService.getAlbumId();
} catch (RemoteException ex) {
}
}
return -1;
}
public long getCurrentArtistId() {
if (MediaUtils.mService != null) {
try {
return mService.getArtistId();
} catch (RemoteException ex) {
}
}
return -1;
}
public long getCurrentAudioId() {
if (MediaUtils.mService != null) {
try {
return mService.getAudioId();
} catch (RemoteException ex) {
}
}
return -1;
}
public int getCurrentShuffleMode() {
int mode = SHUFFLE_NONE;
if (mService != null) {
try {
mode = mService.getShuffleMode();
} catch (RemoteException ex) {
}
}
return mode;
}
public long getFavoritesId() {
long favorites_id = -1;
String favorites_where = Audio.Playlists.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'";
String[] favorites_cols = new String[] { Audio.Playlists._ID };
Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor = query(favorites_uri, favorites_cols, favorites_where, null, null);
if (cursor.getCount() <= 0) {
favorites_id = createPlaylist(PLAYLIST_NAME_FAVORITES);
} else {
cursor.moveToFirst();
favorites_id = cursor.getLong(0);
cursor.close();
}
return favorites_id;
}
public String getGenreName(long genre_id, boolean default_name) {
String where = Audio.Genres._ID + "=" + genre_id;
String[] cols = new String[] { Audio.Genres.NAME };
Uri uri = Audio.Genres.EXTERNAL_CONTENT_URI;
Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null);
if (cursor.getCount() <= 0) {
if (default_name)
return mContext.getString(R.string.unknown_genre);
else
return MediaStore.UNKNOWN_STRING;
} else {
cursor.moveToFirst();
String name = cursor.getString(0);
cursor.close();
if (name == null || MediaStore.UNKNOWN_STRING.equals(name)) {
if (default_name)
return mContext.getString(R.string.unknown_genre);
else
return MediaStore.UNKNOWN_STRING;
}
return name;
}
}
public String getPlaylistName(long playlist_id) {
String where = Audio.Playlists._ID + "=" + playlist_id;
String[] cols = new String[] { Audio.Playlists.NAME };
Uri uri = Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null);
if (cursor.getCount() <= 0) return "";
cursor.moveToFirst();
String name = cursor.getString(0);
cursor.close();
return name;
}
public long[] getQueue() {
if (mService == null) return mEmptyList;
try {
return mService.getQueue();
} catch (RemoteException e) {
e.printStackTrace();
}
return mEmptyList;
}
public int getQueuePosition() {
if (mService == null) return 0;
try {
return mService.getQueuePosition();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public long getSleepTimerRemained() {
long remained = 0;
if (mService == null) return remained;
try {
remained = mService.getSleepTimerRemained();
} catch (Exception e) {
// do nothing
}
return remained;
}
public long[] getSongListForAlbum(long id) {
final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
String where = MediaStore.Audio.Media.ALBUM_ID + "=" + id + " AND "
+ MediaStore.Audio.Media.IS_MUSIC + "=1";
Cursor cursor = query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, ccols, where, null,
MediaStore.Audio.Media.TRACK);
if (cursor != null) {
long[] list = getSongListForCursor(cursor);
cursor.close();
return list;
}
return mEmptyList;
}
public long[] getSongListForArtist(long id) {
final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
String where = MediaStore.Audio.Media.ARTIST_ID + "=" + id + " AND "
+ MediaStore.Audio.Media.IS_MUSIC + "=1";
Cursor cursor = query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, ccols, where, null,
MediaStore.Audio.Media.ALBUM_KEY + "," + MediaStore.Audio.Media.TRACK);
if (cursor != null) {
long[] list = getSongListForCursor(cursor);
cursor.close();
return list;
}
return mEmptyList;
}
public long[] getSongListForCursor(Cursor cursor) {
if (cursor == null) return mEmptyList;
int len = cursor.getCount();
long[] list = new long[len];
cursor.moveToFirst();
int colidx = -1;
try {
colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
} catch (IllegalArgumentException ex) {
colidx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
}
for (int i = 0; i < len; i++) {
list[i] = cursor.getLong(colidx);
cursor.moveToNext();
}
return list;
}
public long[] getSongListForPlaylist(long plid) {
final String[] ccols = new String[] { MediaStore.Audio.Playlists.Members.AUDIO_ID };
Cursor cursor = query(Playlists.Members.getContentUri("external", plid), ccols, null, null,
Playlists.Members.DEFAULT_SORT_ORDER);
if (cursor != null) {
long[] list = getSongListForCursor(cursor);
cursor.close();
return list;
}
return mEmptyList;
}
public String getTrackName(long audio_id) {
String where = Audio.Media._ID + "=" + audio_id;
String[] cols = new String[] { Audio.Media.TITLE };
Uri uri = Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = mContext.getContentResolver().query(uri, cols, where, null, null);
if (cursor.getCount() <= 0) return "";
cursor.moveToFirst();
String name = cursor.getString(0);
cursor.close();
return name;
}
public void initAlbumArtCache() {
try {
int id = mService.getMediaMountedCount();
if (id != mArtCacheId) {
clearAlbumArtCache();
mArtCacheId = id;
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
public boolean isFavorite(long id) {
long favorites_id;
if (id < 0) {
// this shouldn't happen (the menuitems shouldn't be visible
// unless the selected item represents something playable
Log.e(LOGTAG_MUSICUTILS, "playlist id " + id + " is invalid.");
} else {
ContentResolver resolver = mContext.getContentResolver();
// need to determine the number of items currently in the playlist,
// so the play_order field can be maintained.
String favorites_where = Audio.Playlists.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'";
String[] favorites_cols = new String[] { Audio.Playlists._ID };
Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor = resolver.query(favorites_uri, favorites_cols, favorites_where, null,
null);
if (cursor.getCount() <= 0) {
favorites_id = createPlaylist(PLAYLIST_NAME_FAVORITES);
} else {
cursor.moveToFirst();
favorites_id = cursor.getLong(0);
cursor.close();
}
String[] cols = new String[] { Playlists.Members.AUDIO_ID };
Uri uri = Playlists.Members.getContentUri("external", favorites_id);
Cursor cur = resolver.query(uri, cols, null, null, null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
if (cur.getLong(0) == id) {
cur.close();
return true;
}
cur.moveToNext();
}
cur.close();
return false;
}
return false;
}
public boolean isMediaScannerScanning() {
boolean result = false;
Cursor cursor = query(MediaStore.getMediaScannerUri(),
new String[] { MediaStore.MEDIA_SCANNER_VOLUME }, null, null, null);
if (cursor != null) {
if (cursor.getCount() == 1) {
cursor.moveToFirst();
result = "external".equals(cursor.getString(0));
}
cursor.close();
}
return result;
}
public String makeAlbumsLabel(int numalbums, int numsongs, boolean isUnknown) {
// There are two formats for the albums/songs information:
// "N Song(s)" - used for unknown artist/album
// "N Album(s)" - used for known albums
StringBuilder songs_albums = new StringBuilder();
Resources r = mContext.getResources();
if (isUnknown) {
String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
sFormatBuilder.setLength(0);
sFormatter.format(f, Integer.valueOf(numsongs));
songs_albums.append(sFormatBuilder);
} else {
String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
sFormatBuilder.setLength(0);
sFormatter.format(f, Integer.valueOf(numalbums));
songs_albums.append(sFormatBuilder);
songs_albums.append("\n");
}
return songs_albums.toString();
}
/**
* This is now only used for the query screen
*/
public String makeAlbumsSongsLabel(int numalbums, int numsongs, boolean isUnknown) {
// There are several formats for the albums/songs information:
// "1 Song" - used if there is only 1 song
// "N Songs" - used for the "unknown artist" item
// "1 Album"/"N Songs"
// "N Album"/"M Songs"
// Depending on locale, these may need to be further subdivided
StringBuilder songs_albums = new StringBuilder();
Resources r = mContext.getResources();
if (!isUnknown) {
String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
sFormatBuilder.setLength(0);
sFormatter.format(f, Integer.valueOf(numalbums));
songs_albums.append(sFormatBuilder);
songs_albums.append("\n");
}
String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
sFormatBuilder.setLength(0);
sFormatter.format(f, Integer.valueOf(numsongs));
songs_albums.append(sFormatBuilder);
return songs_albums.toString();
}
public void makePlaylistList(boolean create_shortcut, List<Map<String, String>> list) {
Map<String, String> map;
String[] cols = new String[] { Audio.Playlists._ID, Audio.Playlists.NAME };
StringBuilder where = new StringBuilder();
ContentResolver resolver = mContext.getContentResolver();
if (resolver == null) {
System.out.println("resolver = null");
} else {
where.append(Audio.Playlists.NAME + " != ''");
where.append(" AND " + Audio.Playlists.NAME + " != '" + PLAYLIST_NAME_FAVORITES + "'");
Cursor cur = resolver.query(Audio.Playlists.EXTERNAL_CONTENT_URI, cols,
where.toString(), null, Audio.Playlists.NAME);
list.clear();
map = new HashMap<String, String>();
map.put(MAP_KEY_ID, String.valueOf(PLAYLIST_FAVORITES));
map.put(MAP_KEY_NAME, mContext.getString(R.string.favorites));
list.add(map);
if (create_shortcut) {
map = new HashMap<String, String>();
map.put(MAP_KEY_ID, String.valueOf(PLAYLIST_ALL_SONGS));
map.put(MAP_KEY_NAME, mContext.getString(R.string.play_all));
list.add(map);
map = new HashMap<String, String>();
map.put(MAP_KEY_ID, String.valueOf(PLAYLIST_RECENTLY_ADDED));
map.put(MAP_KEY_NAME, mContext.getString(R.string.recently_added));
list.add(map);
} else {
map = new HashMap<String, String>();
map.put(MAP_KEY_ID, String.valueOf(PLAYLIST_QUEUE));
map.put(MAP_KEY_NAME, mContext.getString(R.string.queue));
list.add(map);
map = new HashMap<String, String>();
map.put(MAP_KEY_ID, String.valueOf(PLAYLIST_NEW));
map.put(MAP_KEY_NAME, mContext.getString(R.string.new_playlist));
list.add(map);
}
if (cur != null && cur.getCount() > 0) {
cur.moveToFirst();
while (!cur.isAfterLast()) {
map = new HashMap<String, String>();
map.put(MAP_KEY_ID, String.valueOf(cur.getLong(0)));
map.put(MAP_KEY_NAME, cur.getString(1));
list.add(map);
cur.moveToNext();
}
}
if (cur != null) {
cur.close();
}
}
}
public String makeTimeString(long secs) {
String durationformat = mContext.getString(secs < 3600 ? R.string.durationformatshort
: R.string.durationformatlong);
/*
* Provide multiple arguments so the format can be changed easily by
* modifying the xml.
*/
sFormatBuilder.setLength(0);
final Object[] timeArgs = sTimeArgs;
timeArgs[0] = secs / 3600;
timeArgs[1] = secs / 60;
timeArgs[2] = secs / 60 % 60;
timeArgs[3] = secs;
timeArgs[4] = secs % 60;
return sFormatter.format(durationformat, timeArgs).toString();
}
public void movePlaylistItem(Cursor cursor, long playlist_id, int from, int to) {
if (from < 0) {
from = 0;
}
if (to < 0) {
to = 0;
}
ContentResolver resolver = mContext.getContentResolver();
cursor.moveToPosition(from);
long id = cursor.getLong(cursor.getColumnIndexOrThrow(Playlists.Members.AUDIO_ID));
Uri uri = Playlists.Members.getContentUri("external", playlist_id);
resolver.delete(uri, Playlists.Members.AUDIO_ID + "=" + id, null);
ContentValues values = new ContentValues();
values.put(Playlists.Members.AUDIO_ID, id);
values.put(Playlists.Members.PLAY_ORDER, to);
resolver.insert(uri, values);
}
public void moveQueueItem(int from, int to) {
if (mService == null) return;
try {
mService.moveQueueItem(from, to);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public String parseGenreName(String orig) {
int genre_id = -1;
if (orig == null || orig.trim().length() <= 0) return "Unknown";
try {
genre_id = Integer.parseInt(orig);
} catch (NumberFormatException e) {
// string is not a valid number, so return original value.
return orig;
}
if (genre_id >= 0 && genre_id < GENRES_DB.length)
return GENRES_DB[genre_id];
else
return "Unknown";
}
public void playAll() {
playAll(getAllSongs(), 0);
}
public void playAll(Cursor cursor) {
playAll(cursor, 0, false);
}
public void playAll(Cursor cursor, int position) {
playAll(cursor, position, false);
}
public void playAll(long[] list, int position) {
playAll(list, position, false);
}
public void playPlaylist(long plid) {
long[] list = getSongListForPlaylist(plid);
if (list != null) {
playAll(list, -1, false);
}
}
public void playRecentlyAdded() {
// do a query for all songs added in the last X weeks
int weekX = new PreferencesEditor(mContext).getIntPref(PREF_KEY_NUMWEEKS, 2) * 3600 * 24 * 7;
final String[] ccols = new String[] { MediaStore.Audio.Media._ID };
String where = MediaStore.MediaColumns.DATE_ADDED + ">"
+ (System.currentTimeMillis() / 1000 - weekX);
Cursor cursor = query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, ccols, where, null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor == null) // Todo: show a message
return;
try {
int len = cursor.getCount();
long[] list = new long[len];
for (int i = 0; i < len; i++) {
cursor.moveToNext();
list[i] = cursor.getLong(0);
}
playAll(list, 0);
} catch (SQLiteException ex) {
} finally {
cursor.close();
}
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
return query(uri, projection, selection, selectionArgs, sortOrder, 0);
}
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder, int limit) {
try {
ContentResolver resolver = mContext.getContentResolver();
if (resolver == null) return null;
if (limit > 0) {
uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
}
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (UnsupportedOperationException ex) {
return null;
}
}
public void reloadLyrics() {
if (mService == null) return;
try {
mService.reloadLyrics();
} catch (Exception e) {
// e.printStackTrace();
}
}
public void reloadSettings() {
if (mService == null) return;
try {
mService.reloadSettings();
} catch (Exception e) {
// e.printStackTrace();
}
}
public void removeFromFavorites(long id) {
long favorites_id;
if (id < 0) {
// this shouldn't happen (the menuitems shouldn't be visible
// unless the selected item represents something playable
Log.e(LOGTAG_MUSICUTILS, "playlist id " + id + " is invalid.");
} else {
ContentResolver resolver = mContext.getContentResolver();
// need to determine the number of items currently in the playlist,
// so the play_order field can be maintained.
String favorites_where = Audio.Playlists.NAME + "='" + PLAYLIST_NAME_FAVORITES + "'";
String[] favorites_cols = new String[] { Audio.Playlists._ID };
Uri favorites_uri = Audio.Playlists.EXTERNAL_CONTENT_URI;
Cursor cursor = resolver.query(favorites_uri, favorites_cols, favorites_where, null,
null);
if (cursor.getCount() <= 0) {
favorites_id = createPlaylist(PLAYLIST_NAME_FAVORITES);
} else {
cursor.moveToFirst();
favorites_id = cursor.getLong(0);
cursor.close();
}
Uri uri = Playlists.Members.getContentUri("external", favorites_id);
resolver.delete(uri, Playlists.Members.AUDIO_ID + "=" + id, null);
}
}
public int removeTrack(long id) {
if (mService == null) return 0;
try {
return mService.removeTrack(id);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int removeTracks(int first, int last) {
if (mService == null) return 0;
try {
return mService.removeTracks(first, last);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public void renamePlaylist(long id, String name) {
if (name != null && name.length() > 0) {
ContentResolver resolver = mContext.getContentResolver();
ContentValues values = new ContentValues(1);
values.put(MediaStore.Audio.Playlists.NAME, name);
resolver.update(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values,
MediaStore.Audio.Playlists._ID + "=?", new String[] { String.valueOf(id) });
Toast.makeText(mContext, R.string.playlist_renamed, Toast.LENGTH_SHORT).show();
}
}
public void setQueueId(long id) {
if (mService == null) return;
try {
mService.setQueueId(id);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void setQueuePosition(int index) {
if (mService == null) return;
try {
mService.setQueuePosition(index);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void shuffleAll() {
playAll(getAllSongs(), 0, true);
}
public void shuffleAll(Cursor cursor) {
playAll(cursor, 0, true);
}
public void startSleepTimer(long milliseconds, boolean gentle) {
if (mService == null) return;
try {
mService.startSleepTimer(milliseconds, gentle);
} catch (Exception e) {
// do nothing
}
}
public void stopSleepTimer() {
if (mService == null) return;
try {
mService.stopSleepTimer();
} catch (Exception e) {
// do nothing
}
}
public void unbindFromService(ServiceToken token) {
if (token == null) {
Log.e(LOGTAG_MUSICUTILS, "Trying to unbind with null token");
return;
}
ContextWrapper wrapper = token.mWrappedContext;
ServiceBinder binder = mConnectionMap.remove(wrapper);
if (binder == null) {
Log.e(LOGTAG_MUSICUTILS, "Trying to unbind for unknown Context");
return;
}
wrapper.unbindService(binder);
if (mConnectionMap.isEmpty()) {
// presumably there is nobody interested in the service at this
// point,
// so don't hang on to the ServiceConnection
mService = null;
}
}
/** get album art for specified file */
private Bitmap getArtworkFromFile(long songid, long albumid) {
Bitmap bm = null;
if (albumid < 0 && songid < 0)
throw new IllegalArgumentException("Must specify an album or a song id");
try {
if (albumid < 0) {
Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri,
"r");
if (pfd != null) {
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd);
}
} else {
Uri uri = ContentUris.withAppendedId(mArtworkUri, albumid);
ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri,
"r");
if (pfd != null) {
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd);
}
}
} catch (IllegalStateException ex) {
} catch (FileNotFoundException ex) {
}
return bm;
}
private Uri getArtworkUriFromFile(long songid, long albumid) {
if (albumid < 0 && songid < 0) return null;
try {
if (albumid < 0) {
Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri,
"r");
if (pfd != null) return uri;
} else {
Uri uri = ContentUris.withAppendedId(mArtworkUri, albumid);
ParcelFileDescriptor pfd = mContext.getContentResolver().openFileDescriptor(uri,
"r");
if (pfd != null) return uri;
}
} catch (FileNotFoundException ex) {
//
}
return null;
}
private Bitmap getDefaultArtwork() {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeStream(
mContext.getResources().openRawResource(R.drawable.ic_mp_albumart_unknown), null,
opts);
}
/**
* @param ids
* The source array containing all the ids to be added to the
* playlist
* @param offset
* Where in the 'ids' array we start reading
* @param len
* How many items to copy during this pass
* @param base
* The play order offset to use for this pass
*/
private void makeInsertItems(long[] ids, int offset, int len, int base) {
// adjust 'len' if would extend beyond the end of the source array
if (offset + len > ids.length) {
len = ids.length - offset;
}
// allocate the ContentValues array, or reallocate if it is the wrong
// size
if (sContentValuesCache == null || sContentValuesCache.length != len) {
sContentValuesCache = new ContentValues[len];
}
// fill in the ContentValues array with the right values for this pass
for (int i = 0; i < len; i++) {
if (sContentValuesCache[i] == null) {
sContentValuesCache[i] = new ContentValues();
}
sContentValuesCache[i].put(Playlists.Members.PLAY_ORDER, base + offset + i);
sContentValuesCache[i].put(Playlists.Members.AUDIO_ID, ids[offset + i]);
}
}
private void playAll(Cursor cursor, int position, boolean force_shuffle) {
long[] list = getSongListForCursor(cursor);
playAll(list, position, force_shuffle);
}
private void playAll(long[] list, int position, boolean force_shuffle) {
if (list == null || list.length == 0 || mService == null) {
Log.d(LOGTAG_MUSICUTILS, "attempt to play empty song list");
// Don't try to play empty playlists. Nothing good will come of it.
Toast.makeText(mContext, R.string.emptyplaylist, Toast.LENGTH_SHORT).show();
return;
}
try {
if (force_shuffle) {
mService.setShuffleMode(SHUFFLE_NORMAL);
}
long curid = mService.getAudioId();
int curpos = mService.getQueuePosition();
if (position != -1 && curpos == position && curid == list[position]) {
// The selected file is the file that's currently playing;
// figure out if we need to restart with a new playlist,
// or just launch the playback activity.
long[] playlist = mService.getQueue();
if (Arrays.equals(list, playlist)) {
// we don't need to set a new list, but we should resume
// playback if needed
mService.play();
return; // the 'finally' block will still run
}
}
if (position < 0) {
position = 0;
}
mService.open(list, force_shuffle ? -1 : position);
mService.play();
} catch (RemoteException ex) {
} finally {
Intent intent = new Intent(INTENT_PLAYBACK_VIEWER)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
protected Uri getContentURIForPath(String path) {
return Uri.fromFile(new File(path));
}
/*
* Returns true if a file is currently opened for playback (regardless of
* whether it's playing or paused).
*/
public static boolean isMusicLoaded() {
if (MediaUtils.mService != null) {
try {
return mService.getPath() != null;
} catch (RemoteException ex) {
}
}
return false;
}
private class ServiceBinder implements ServiceConnection {
ServiceConnection mCallback;
ServiceBinder(ServiceConnection callback) {
mCallback = callback;
}
@Override
public void onServiceConnected(ComponentName className, android.os.IBinder service) {
mService = IMusicPlaybackService.Stub.asInterface(service);
initAlbumArtCache();
if (mCallback != null) {
mCallback.onServiceConnected(className, service);
}
}
@Override
public void onServiceDisconnected(ComponentName className) {
if (mCallback != null) {
mCallback.onServiceDisconnected(className);
}
mService = null;
}
}
static class LogEntry {
Object item;
long time;
LogEntry(Object o) {
item = o;
time = System.currentTimeMillis();
}
void dump(PrintWriter out) {
mTime.set(time);
out.print(mTime.toString() + " : ");
if (item instanceof Exception) {
((Exception) item).printStackTrace(out);
} else {
out.println(item);
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/MediaUtils.java
|
Java
|
gpl3
| 48,650
|
package org.yammp.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import android.graphics.Bitmap;
import android.graphics.Color;
/**
*
* @author mariotaku
*
* Get the main color from a {@link Bitmap}<br>
* <br>
*
* <b>Important</b>: I recommand using this method in different thread.
* Or it will make your application laggy or unresponceable.
*/
public class ColorAnalyser {
/**
*
* Get the main color from a {@link Bitmap}.<br>
*
* @param bitmap
* The {@link Bitmap} to analyse
* @return The rgb {@link Color} in integer (no alpha)
*/
public static int analyse(Bitmap bitmap) {
return analyse(bitmap, 18, 28);
}
/**
*
* Get the main color from a {@link Bitmap}.<br>
*
* @param bitmap
* The {@link Bitmap} to analyse
* @param width
* The desired width of scaled bitmap
* @param height
* The desired height of scaled bitmap
* @return The rgb {@link Color} in integer (no alpha)
*/
public static int analyse(Bitmap bitmap, int width, int height) {
if (bitmap == null) return Color.WHITE;
int color = 0;
HashMap<Float, Integer> colorsMap = new HashMap<Float, Integer>();
ArrayList<Float> colorsScore = new ArrayList<Float>();
Bitmap resized = Bitmap.createScaledBitmap(bitmap, width, height, false);
for (int y = 0; y < resized.getHeight(); y++) {
for (int x = 0; x < resized.getWidth(); x++) {
int temp_color = resized.getPixel(x, y);
color = Color.argb(0xFF, Color.red(temp_color), Color.green(temp_color),
Color.blue(temp_color));
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
float score = (hsv[1] * hsv[1] + 0.001f) * (hsv[2] * hsv[2]);
colorsMap.put(score, color);
colorsScore.add(score);
}
}
Collections.sort(colorsScore);
bitmap.recycle();
resized.recycle();
return colorsMap.get(colorsScore.get(colorsScore.size() - 1));
}
/**
*
* Get the main color from a {@link Bitmap}.<br>
*
* @param bitmap
* The {@link Bitmap} to analyse
* @param width
* The desired width of scaled bitmap
* @param height
* The desired height of scaled bitmap
* @param def
* The default color returned, if bitmap is null
* @return The rgb {@link Color} in integer (no alpha)
*/
public static int analyse(Bitmap bitmap, int width, int height, int def) {
if (bitmap == null) return def;
int color = 0;
HashMap<Float, Integer> colorsMap = new HashMap<Float, Integer>();
ArrayList<Float> colorsScore = new ArrayList<Float>();
Bitmap resized = Bitmap.createScaledBitmap(bitmap, width, height, false);
for (int y = 0; y < resized.getHeight(); y++) {
for (int x = 0; x < resized.getWidth(); x++) {
int temp_color = resized.getPixel(x, y);
color = Color.argb(0xFF, Color.red(temp_color), Color.green(temp_color),
Color.blue(temp_color));
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
float score = (hsv[1] * hsv[1] + 0.001f) * (hsv[2] * hsv[2]);
colorsMap.put(score, color);
colorsScore.add(score);
}
}
Collections.sort(colorsScore);
bitmap.recycle();
resized.recycle();
return colorsMap.get(colorsScore.get(colorsScore.size() - 1));
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/ColorAnalyser.java
|
Java
|
gpl3
| 3,327
|
package org.yammp.util;
import org.yammp.Constants;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class PreferencesEditor implements Constants {
private Context context;
public PreferencesEditor(Context context) {
this.context = context;
}
public boolean getBooleanPref(String name, boolean def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
return prefs.getBoolean(name, def);
}
public boolean getBooleanState(String name, boolean def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
return prefs.getBoolean(name, def);
}
public short getEqualizerSetting(short band, short def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_EQUALIZER,
Context.MODE_PRIVATE);
return Short.valueOf(prefs.getString(String.valueOf(band), String.valueOf(def)));
}
public float getFloatPref(String name, float def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
return prefs.getFloat(name, def);
}
public int getIntPref(String name, int def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
return prefs.getInt(name, def);
}
public int getIntState(String name, int def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
return prefs.getInt(name, def);
}
public long getLongState(String name, long def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
return prefs.getLong(name, def);
}
public String getStringPref(String name, String def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
return prefs.getString(name, def);
}
public String getStringState(String name, String def) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
return prefs.getString(name, def);
}
public void setBooleanPref(String name, boolean value) {
SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putBoolean(name, value);
editor.commit();
}
public void setBooleanState(String name, boolean value) {
SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putBoolean(name, value);
editor.commit();
}
public void setEqualizerSetting(short band, short value) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_EQUALIZER,
Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putString(String.valueOf(band), String.valueOf(value));
ed.commit();
}
public void setFloatPref(String name, float value) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putFloat(name, value);
ed.commit();
}
public void setIntPref(String name, int value) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putInt(name, value);
ed.commit();
}
public void setIntState(String name, int value) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putInt(name, value);
ed.commit();
}
public void setLongState(String name, long value) {
SharedPreferences prefs = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
Editor ed = prefs.edit();
ed.putLong(name, value);
ed.commit();
}
public void setStringPref(String name, String value) {
SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFS_PREFERENCES,
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString(name, value);
editor.commit();
}
public void setStringState(String name, String value) {
SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFS_STATES,
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString(name, value);
editor.commit();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/PreferencesEditor.java
|
Java
|
gpl3
| 4,474
|
package org.yammp.util;
import java.util.ArrayList;
import java.util.List;
import org.yammp.Constants;
import org.yammp.IMusicPlaybackService;
import org.yammp.YAMMPApplication;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
public class ServiceInterface implements Constants {
private IMusicPlaybackService mService;
private Context mContext;
private BroadcastReceiver mMediaStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_META_CHANGED.equals(action)) {
for (MediaStateListener listener : mMediaListeners) {
listener.onMetaChanged();
}
} else if (BROADCAST_PLAYSTATE_CHANGED.equals(action)) {
for (MediaStateListener listener : mMediaListeners) {
listener.onPlayStateChanged();
}
} else if (BROADCAST_FAVORITESTATE_CHANGED.equals(action)) {
for (MediaStateListener listener : mMediaListeners) {
listener.onFavoriteStateChanged();
}
} else if (BROADCAST_SHUFFLEMODE_CHANGED.equals(action)) {
for (MediaStateListener listener : mMediaListeners) {
listener.onShuffleModeChanged();
}
} else if (BROADCAST_REPEATMODE_CHANGED.equals(action)) {
for (MediaStateListener listener : mMediaListeners) {
listener.onRepeatModeChanged();
}
} else if (BROADCAST_QUEUE_CHANGED.equals(action)) {
for (MediaStateListener listener : mMediaListeners) {
listener.onQueueChanged();
}
}
}
};
private BroadcastReceiver mLyricsStatusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_NEW_LYRICS_LOADED.equals(action)) {
for (LyricsStateListener listener : mLyricsListeners) {
listener.onNewLyricsLoaded();
}
} else if (BROADCAST_LYRICS_REFRESHED.equals(action)) {
for (LyricsStateListener listener : mLyricsListeners) {
listener.onLyricsRefreshed();
}
}
}
};
private List<MediaStateListener> mMediaListeners = new ArrayList<MediaStateListener>();
private List<LyricsStateListener> mLyricsListeners = new ArrayList<LyricsStateListener>();
private ServiceConnection mConntecion = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName service, IBinder obj) {
mService = IMusicPlaybackService.Stub.asInterface(obj);
IntentFilter filter = new IntentFilter() {
{
addAction(BROADCAST_PLAYSTATE_CHANGED);
addAction(BROADCAST_META_CHANGED);
addAction(BROADCAST_FAVORITESTATE_CHANGED);
addAction(BROADCAST_SHUFFLEMODE_CHANGED);
addAction(BROADCAST_REPEATMODE_CHANGED);
addAction(BROADCAST_QUEUE_CHANGED);
}
};
mContext.registerReceiver(mMediaStatusReceiver, filter);
filter = new IntentFilter() {
{
addAction(BROADCAST_NEW_LYRICS_LOADED);
addAction(BROADCAST_LYRICS_REFRESHED);
}
};
mContext.registerReceiver(mLyricsStatusReceiver, filter);
}
@Override
public void onServiceDisconnected(ComponentName service) {
mService = null;
}
};
public ServiceInterface(Context context) {
((YAMMPApplication) context.getApplicationContext()).getMediaUtils().bindToService(
mConntecion);
mContext = context;
}
public void addLyricsStateListener(LyricsStateListener listener) {
if (listener != null) {
mLyricsListeners.add(listener);
listener.onNewLyricsLoaded();
listener.onLyricsRefreshed();
}
}
public void addMediaStateListener(MediaStateListener listener) {
if (listener != null) {
mMediaListeners.add(listener);
listener.onFavoriteStateChanged();
listener.onMetaChanged();
listener.onPlayStateChanged();
listener.onQueueChanged();
listener.onRepeatModeChanged();
listener.onShuffleModeChanged();
}
}
public void addToFavorites(long id) {
if (mService == null) return;
try {
mService.addToFavorites(id);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public long duration() {
if (mService == null) return 0;
try {
return mService.duration();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public void enqueue(long[] list, int action) {
if (mService == null) return;
try {
mService.enqueue(list, action);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public int eqGetBand(int frequency) {
if (mService == null) return 0;
try {
return mService.eqGetBand(frequency);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int[] eqGetBandFreqRange(int band) {
if (mService == null) return null;
try {
return mService.eqGetBandFreqRange((short) band);
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public int eqGetBandLevel(int band) {
if (mService == null) return 0;
try {
return mService.eqGetBandLevel(band);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int[] eqGetBandLevelRange() {
if (mService == null) return null;
try {
return mService.eqGetBandLevelRange();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public int eqGetCenterFreq(int band) {
if (mService == null) return 0;
try {
return mService.eqGetCenterFreq((short) band);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int eqGetCurrentPreset() {
if (mService == null) return 0;
try {
return mService.eqGetCurrentPreset();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int eqGetNumberOfBands() {
if (mService == null) return 0;
try {
return mService.eqGetNumberOfBands();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int eqGetNumberOfPresets() {
if (mService == null) return 0;
try {
return mService.eqGetNumberOfPresets();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public String eqGetPresetName(int preset) {
if (mService == null) return null;
try {
return mService.eqGetPresetName((short) preset);
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public void eqRelease() {
if (mService == null) return;
try {
mService.eqRelease();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void eqReset() {
if (mService == null) return;
try {
mService.eqReset();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void eqSetBandLevel(int band, int level) {
if (mService == null) return;
try {
mService.eqSetBandLevel((short) band, (short) level);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public int eqSetEnabled(boolean enabled) {
if (mService == null) return 0;
try {
return mService.eqSetEnabled(enabled);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public void eqUsePreset(int preset) {
if (mService == null) return;
try {
mService.eqUsePreset((short) preset);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public long getAlbumId() {
if (mService == null) return 0;
try {
return mService.getAlbumId();
} catch (RemoteException e) {
e.printStackTrace();
}
return -1;
}
public String getAlbumName() {
if (mService == null) return null;
try {
return mService.getAlbumName();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public long getArtistId() {
if (mService == null) return 0;
try {
return mService.getArtistId();
} catch (RemoteException e) {
e.printStackTrace();
}
return -1;
}
public String getArtistName() {
if (mService == null) return null;
try {
return mService.getArtistName();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public Uri getArtworkUri() {
if (mService == null) return null;
try {
return mService.getArtworkUri();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public long getAudioId() {
if (mService == null) return 0;
try {
return mService.getAudioId();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int getAudioSessionId() {
if (mService == null) return 0;
try {
return mService.getAudioSessionId();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int getCurrentLyricsId() {
if (mService == null) return 0;
try {
return mService.getCurrentLyricsId();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public String[] getLyrics() {
if (mService == null) return null;
try {
return mService.getLyrics();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public int getLyricsStatus() {
if (mService == null) return 0;
try {
return mService.getLyricsStatus();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int getMediaMountedCount() {
if (mService == null) return 0;
try {
return mService.getMediaMountedCount();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public String getMediaPath() {
if (mService == null) return null;
try {
return mService.getMediaPath();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public String getPath() {
if (mService == null) return null;
try {
return mService.getPath();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public long getPositionByLyricsId(int id) {
if (mService == null) return 0;
try {
return mService.getPositionByLyricsId(id);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public long[] getQueue() {
if (mService == null) return null;
try {
return mService.getQueue();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public int getQueuePosition() {
if (mService == null) return 0;
try {
return mService.getQueuePosition();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int getRepeatMode() {
if (mService == null) return 0;
try {
return mService.getRepeatMode();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int getShuffleMode() {
if (mService == null) return 0;
try {
return mService.getShuffleMode();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public long getSleepTimerRemained() {
if (mService == null) return 0;
try {
return mService.getSleepTimerRemained();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public String getTrackName() {
if (mService == null) return null;
try {
return mService.getTrackName();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
public boolean isFavorite(long id) {
if (mService == null) return false;
try {
return mService.isFavorite(id);
} catch (RemoteException e) {
e.printStackTrace();
}
return false;
}
public boolean isPlaying() {
if (mService == null) return false;
try {
return mService.isPlaying();
} catch (RemoteException e) {
e.printStackTrace();
}
return false;
}
public void moveQueueItem(int from, int to) {
if (mService == null) return;
try {
mService.moveQueueItem(from, to);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void next() {
if (mService == null) return;
try {
mService.next();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void open(long[] list, int position) {
if (mService == null) return;
try {
mService.open(list, position);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void openFile(String path) {
if (mService == null) return;
try {
mService.openFile(path);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void pause() {
if (mService == null) return;
try {
mService.pause();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void play() {
if (mService == null) return;
try {
mService.play();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public long position() {
if (mService == null) return 0;
try {
return mService.position();
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public void prev() {
if (mService == null) return;
try {
mService.prev();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void refreshLyrics() {
if (mService == null) return;
try {
mService.refreshLyrics();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void reloadEqualizer() {
if (mService == null) return;
try {
mService.reloadEqualizer();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void reloadLyrics() {
if (mService == null) return;
try {
mService.reloadLyrics();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void reloadSettings() {
if (mService == null) return;
try {
mService.reloadSettings();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void removeFromFavorites(long id) {
if (mService == null) return;
try {
mService.removeFromFavorites(id);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void removeLyricsStateListener(LyricsStateListener listener) {
if (listener != null) {
mLyricsListeners.remove(listener);
}
}
public void removeMediaStateListener(MediaStateListener listener) {
if (listener != null) {
mMediaListeners.remove(listener);
}
}
public int removeTrack(long id) {
if (mService == null) return 0;
try {
return mService.removeTrack(id);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public int removeTracks(int first, int last) {
if (mService == null) return 0;
try {
return mService.removeTracks(first, last);
} catch (RemoteException e) {
e.printStackTrace();
}
return 0;
}
public long seek(long pos) {
if (mService == null) return pos;
try {
return mService.seek(pos);
} catch (RemoteException e) {
e.printStackTrace();
}
return pos;
}
public void setQueueId(long id) {
if (mService == null) return;
try {
mService.setQueueId(id);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void setQueuePosition(int index) {
if (mService == null) return;
try {
mService.setQueuePosition(index);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void setRepeatMode(int repeatmode) {
if (mService == null) return;
try {
mService.setRepeatMode(repeatmode);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void setShuffleMode(int shufflemode) {
if (mService == null) return;
try {
mService.setShuffleMode(shufflemode);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void startSleepTimer(long milliseconds, boolean gentle) {
if (mService == null) return;
try {
mService.startSleepTimer(milliseconds, gentle);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void stop() {
if (mService == null) return;
try {
mService.stop();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void stopSleepTimer() {
if (mService == null) return;
try {
mService.stopSleepTimer();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void toggleFavorite() {
if (mService == null) return;
try {
mService.toggleFavorite();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public boolean togglePause() {
if (mService == null) return false;
try {
return mService.togglePause();
} catch (RemoteException e) {
e.printStackTrace();
}
return false;
}
public void toggleRepeat() {
if (mService == null) return;
try {
mService.toggleRepeat();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void toggleShuffle() {
if (mService == null) return;
try {
mService.toggleShuffle();
} catch (RemoteException e) {
e.printStackTrace();
}
}
public interface LyricsStateListener {
void onLyricsRefreshed();
void onNewLyricsLoaded();
}
public interface MediaStateListener {
void onFavoriteStateChanged();
void onMetaChanged();
void onPlayStateChanged();
void onQueueChanged();
void onRepeatModeChanged();
void onShuffleModeChanged();
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/ServiceInterface.java
|
Java
|
gpl3
| 16,902
|
package org.yammp.util;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;
import org.yammp.util.VisualizerWrapper.OnDataChangedListener;
import android.os.Handler;
import android.os.Message;
public class VisualizerCompatScoop extends VisualizerCompat {
private OnDataChangedListener mListener;
private boolean mWaveEnabled, mFftEnabled;
private boolean mVisualizerEnabled;
private Timer mTimer;
private Handler mVisualizerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case WAVE_CHANGED:
if (mListener != null) {
short[] wave_data = (short[]) ((Object[]) msg.obj)[0];
int len = (Integer) ((Object[]) msg.obj)[1];
mListener.onWaveDataChanged(transform(wave_data, 128),
(int) (len * accuracy), true);
}
break;
case FFT_CHANGED:
if (mListener != null) {
short[] fft_data = (short[]) ((Object[]) msg.obj)[0];
int len = (Integer) ((Object[]) msg.obj)[1];
mListener.onFftDataChanged(transform(fft_data, 32), (int) (len * accuracy));
}
break;
}
}
};
public VisualizerCompatScoop(int audioSessionId, int fps) {
super(audioSessionId, fps);
duration = 1000 / fps;
mTimer = new Timer();
}
@Override
public boolean getEnabled() {
return mVisualizerEnabled;
}
@Override
public void release() {
}
@Override
public void setAccuracy(float accuracy) {
if (accuracy > 1.0f || accuracy <= 0.0f)
throw new IllegalArgumentException(
"Invalid accuracy value! Allowed value range is \"0 < accuracy <= 1.0\"!");
this.accuracy = accuracy;
}
@Override
public void setEnabled(boolean enabled) {
if (mTimer != null) {
if (enabled) {
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new VisualizerTimer(), 0, duration);
} else {
mTimer.cancel();
}
}
mVisualizerEnabled = enabled;
}
@Override
public void setFftEnabled(boolean fft) {
mFftEnabled = fft;
}
@Override
public void setOnDataChangedListener(OnDataChangedListener listener) {
mListener = listener;
}
@Override
public void setWaveFormEnabled(boolean wave) {
mWaveEnabled = wave;
}
private int snoop(short[] outData, int kind) {
try {
Method m = Class.forName("android.media.MediaPlayer").getMethod("snoop",
outData.getClass(), Integer.TYPE);
m.setAccessible(true);
return (Integer) m.invoke(Class.forName("android.media.MediaPlayer"), outData, kind);
} catch (Exception e) {
return 0;
}
}
private byte[] transform(short[] orig, int divider) {
byte[] result = new byte[orig.length];
for (int i = 0; i < orig.length; i++) {
short temp = (short) (orig[i] / divider);
if (temp > Byte.MAX_VALUE) {
temp = Byte.MAX_VALUE;
}
if (temp < Byte.MIN_VALUE) {
temp = Byte.MIN_VALUE;
}
result[i] = (byte) temp;
}
return result;
}
private class VisualizerTimer extends TimerTask {
@Override
public void run() {
short[] wave_data = new short[1024];
short[] fft_data = new short[1024];
if (mWaveEnabled) {
int len = snoop(wave_data, 0);
if (len != 0) {
Message msg = new Message();
msg.what = WAVE_CHANGED;
msg.obj = new Object[] { wave_data, len };
mVisualizerHandler.sendMessage(msg);
}
}
if (mFftEnabled) {
int len = snoop(fft_data, 1);
if (len != 0) {
Message msg = new Message();
msg.what = FFT_CHANGED;
msg.obj = new Object[] { fft_data, len };
mVisualizerHandler.sendMessage(msg);
}
}
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/VisualizerCompatScoop.java
|
Java
|
gpl3
| 3,552
|
package org.yammp.util;
import org.yammp.util.VisualizerWrapper.OnDataChangedListener;
public abstract class VisualizerCompat {
public final static int WAVE_CHANGED = 0;
public final static int FFT_CHANGED = 1;
public float accuracy = 1.0f;
public long duration = 50;
public VisualizerCompat(int audioSessionId, int fps) {
}
public abstract boolean getEnabled();
public abstract void release();
public abstract void setAccuracy(float accuracy);
public abstract void setEnabled(boolean enabled);
public abstract void setFftEnabled(boolean fft);
public abstract void setOnDataChangedListener(OnDataChangedListener listener);
public abstract void setWaveFormEnabled(boolean wave);
}
|
061304011116lyj-yammp
|
src/org/yammp/util/VisualizerCompat.java
|
Java
|
gpl3
| 706
|
package org.yammp.util;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
public class PluginInfo {
public Drawable icon;
public CharSequence name;
public CharSequence description;
public String pname;
public PluginInfo(ResolveInfo resolveInfo, PackageManager pm) {
ApplicationInfo info = resolveInfo.activityInfo.applicationInfo;
icon = info.loadIcon(pm);
name = info.loadLabel(pm);
pname = info.packageName;
description = info.loadDescription(pm);
if (description == null) {
description = "";
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/PluginInfo.java
|
Java
|
gpl3
| 644
|
/*
* Copyright (C) 2011 The MusicMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yammp.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mozilla.universalchardet.UniversalDetector;
import org.yammp.Constants;
public class LyricsParser implements Constants {
private HashMap<Long, String> lyricsMap = new HashMap<Long, String>();
private ArrayList<Long> mTimestampList = new ArrayList<Long>();
private ArrayList<String> mLyricsList = new ArrayList<String>();
private long offset = 0;
public LyricsParser() {
}
public ArrayList<String> getAllLyrics() {
return mLyricsList;
}
public ArrayList<Long> getAllTimestamp() {
return mTimestampList;
}
public int getId(long timestamp) {
for (int i = mTimestampList.size() - 1; i >= 0; i--) {
if (mTimestampList.get(i) <= timestamp) return i;
}
return 0;
}
public long getTimestamp(int id) {
if (mTimestampList.size() > 0) {
if (id >= mTimestampList.size()) return mTimestampList.get(mTimestampList.size() - 1);
if (id < 0) return 0;
return mTimestampList.get(id);
}
return 0;
}
public int parseLyrics(File file) {
lyricsMap = new HashMap<Long, String>();
mTimestampList = new ArrayList<Long>();
mLyricsList = new ArrayList<String>();
if (!file.exists()) return LYRICS_STATUS_NOT_FOUND;
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
byte[] content = out.toByteArray();
String encoding;
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(content, 0, content.length);
detector.dataEnd();
encoding = detector.getDetectedCharset();
if (encoding == null) {
encoding = "UTF-8";
}
parseLyricsString(new String(content, 0, content.length, encoding));
} catch (IOException e) {
e.printStackTrace();
return LYRICS_STATUS_INVALID;
}
if (lyricsMap.size() == 0) return LYRICS_STATUS_INVALID;
return LYRICS_STATUS_OK;
}
public int parseLyrics(String path) {
return parseLyrics(new File(path));
}
private void parseLyricsString(String lyrics) {
Pattern pattern, patternOffset, patternTimestamp;
// lyrics offset tag
patternOffset = Pattern.compile("\\[offset:(\\d+)\\]", Pattern.CASE_INSENSITIVE);
Matcher matcherOffset = patternOffset.matcher(lyrics);
if (matcherOffset.find()) {
offset = Long.valueOf(matcherOffset.group(1));
}
// lyrics timestamp tag
pattern = Pattern.compile("^(\\[[0-9:\\.\\[\\]]+\\])+(.*)$", Pattern.MULTILINE);
// split each timestamp tag
patternTimestamp = Pattern.compile("\\[(\\d+):([0-9\\.]+)\\]");
Matcher matcher = pattern.matcher(lyrics);
while (matcher.find()) {
Matcher matcherTimestamp = patternTimestamp.matcher(matcher.group(1));
while (matcherTimestamp.find()) {
String content = matcher.group(2).trim();
if (content.length() == 0) {
continue;
}
long timestamp = Long.valueOf(matcherTimestamp.group(1)) * 60000
+ (long) (Float.valueOf(matcherTimestamp.group(2)) * 1000) + offset;
mTimestampList.add(timestamp);
lyricsMap.put(timestamp, content);
}
}
// Sort timestamp tag
Collections.sort(mTimestampList);
for (int i = 0; i < mTimestampList.size(); i++) {
mLyricsList.add(lyricsMap.get(mTimestampList.get(i)));
}
}
}
|
061304011116lyj-yammp
|
src/org/yammp/util/LyricsParser.java
|
Java
|
gpl3
| 4,454
|
<?php
require_once('include/header.php');
require_once('dao/ImagenesDAO.php');
require_once('logic/ImagenesLogic.php');
require_once('search/ImagenesSearchCriteria.php');
$logic = new ImagenesLogic($_POST);
// obtener action
$action = $_GET['action'];
if ($action == null){
$action = $_POST['action'];
}
// obtengo ID del registro
$iditem = $_GET[iditem];
if ($iditem == "")
$iditem = $_POST[iditem];
// obtengo table
$table = $_GET[t];
if ($table == "")
$table = $_POST[t];
switch ($action) {
case "add":
$result = $logic->save($_POST, $_FILES);
if ($result == 'error') {
$result = "error";
} else {
$result = "ok";
}
header( 'Location: imagenes.php?iditem=' . $iditem . '&t=' . $table );
break;
case "update":
$result = $logic->update($_POST);
if ($result == 'error') {
$result = "error";
} else {
$result = "ok";
}
header( 'Location: imagenes.php?iditem=' . $iditem . '&t=' . $table );
break;
case "delete":
$result = $logic->delete($_POST);
if ($result == 'error'){$smarty->assign('error', "Error al borrar la imagen");}
header( 'Location: imagenes.php?iditem=' . $iditem . '&t=' . $table );
break;
}
// obtengo todas las imagenes
$imageSearchCriteria = new ImagenesSearchCriteria();
$imageSearchCriteria->setIditem($iditem);
$imageSearchCriteria->setTable($table);
$images = $logic->find($imageSearchCriteria);
$entidad = $logic->getEntidad($table, $iditem);
$smarty->assign('iditem',$iditem);
$smarty->assign('t',$table);
$smarty->assign('images',$images);
$smarty->assign('entidad',$entidad);
$smarty->assign("detailPage", "imagenes.tpl");
$smarty->display("admin_generic.tpl");
|
0admin
|
trunk/imagenes.php
|
PHP
|
oos
| 1,732
|
<?php
require_once('search/SearchCriteria.php');
Class ImageSearchCriteria extends SearchCriteria{
private $idItem;
private $fecha;
private $table;
function getIdItem() { return $this->idItem; }
function getFecha() { return $this->fecha; }
function getTable() { return $this->table; }
function setIdItem($x) { $this->idItem = $x; }
function setFecha($x) { $this->fecha = $x; }
function setTable($x) { $this->table = $x; }
}
?>
|
0admin
|
trunk/search/ImageSearchCriteria.php
|
PHP
|
oos
| 469
|
<?php
require_once('search/SearchCriteria.php');
Class AvisosSearchCriteria extends SearchCriteria{
private $fecha = null;
private $search = null;
public function getFecha(){
return $this->fecha;
}
public function setFecha($fecha){
$this->fecha = $fecha;
}
public function getSearch(){
return $this->search;
}
public function setSearch($search){
$this->search = $search;
}
}
?>
|
0admin
|
trunk/search/AvisosSearchCriteria.php
|
PHP
|
oos
| 434
|
<?php
Class SearchCriteria{
private $id;
private $inicio = 1;
private $fin;
private $activo;
private $borrado = 0;
private $orderby;
private $order;
function getId(){
return $this->id;
}
function setId($id){
$this->id = $id;
}
function getInicio(){
return $this->inicio;
}
function setInicio($inicio){
$this->inicio = $inicio;
}
function getFin(){
return $this->fin;
}
function setFin($fin){
$this->fin = $fin;
}
function getActivo(){
return $this->activo;
}
function setActivo($activo){
$this->activo = $activo;
}
function getBorrado(){
if ($this->borrado == null || $this->borrado == "" ){
return 0;
}
return $this->borrado;
}
function setBorrado($borrado){
$this->borrado = $borrado;
}
function getOrderby(){
return $this->orderby;
}
function setOrderby($orderby){
$this->orderby = $orderby;
}
function getOrder(){
return $this->order;
}
function setOrder($order){
$this->order = $order;
}
}
?>
|
0admin
|
trunk/search/SearchCriteria.php
|
PHP
|
oos
| 1,060
|
<?php
require_once('search/SearchCriteria.php');
require_once('plugin/UtilsPlugin.php');
class NoticiasSearchCriteria extends SearchCriteria {
private $titulo = null;
private $tags = null;
private $fechaFrom = null;
private $fechaTo = null;
private $categoria = null;
private $seccion = null;
private $orden = null;
private $visitas = null;
public function getTitulo(){
return $this->titulo;
}
public function setTitulo($titulo){
$this->titulo = $titulo;
}
public function getTags(){
return $this->tags;
}
public function setTags($tags){
$this->tags = $tags;
}
public function getFechaFrom(){
return $this->fechaFrom;
}
public function setFechaFrom($fechaFrom){
$this->fechaFrom = Utils::getDateForDB($fechaFrom);
}
public function getFechaTo(){
return $this->fechaTo;
}
public function setFechaTo($fechaTo){
$this->fechaTo = Utils::getDateForDB($fechaTo);
}
public function getCategoria(){
return $this->categoria;
}
public function setCategoria($categoria){
$this->categoria = $categoria;
}
public function getSeccion(){
return $this->seccion;
}
public function setSeccion($seccion){
$this->seccion = $seccion;
}
public function getOrden(){
return $this->orden;
}
public function setOrden($seccion){
$this->order = $orden;
}
public function getVisitas(){
return $this->visitas;
}
public function setVisitas($visitas){
$this->visitas = $visitas;
}
}
?>
|
0admin
|
trunk/search/NoticiasSearchCriteria.php
|
PHP
|
oos
| 1,530
|
<?php
require_once('search/SearchCriteria.php');
Class ClientesSearchCriteria extends SearchCriteria{
private $nombre = null;
private $ciudad = null;
private $active = null;
private $fecha = null;
private $search = null;
public function getNombre(){
return $this->nombre;
}
public function setNombre($nombre){
$this->nombre = $nombre;
}
public function getCiudad(){
return $this->ciudad;
}
public function setCiudad($ciudad){
$this->ciudad = $ciudad;
}
public function getActive(){
return $this->active;
}
public function setActive($active){
$this->active = $active;
}
public function getFecha(){
return $this->fecha;
}
public function setFecha($fecha){
$this->fecha = $fecha;
}
public function getSearch(){
return $this->search;
}
public function setSearch($search){
$this->search = $search;
}
}
|
0admin
|
trunk/search/ClientesSearchCriteria.php
|
PHP
|
oos
| 911
|
<?php
require_once('search/SearchCriteria.php');
Class UsuarioSearchCriteria extends SearchCriteria{
private $username = null;
private $rol = null;
public function getUsername(){
return $this->username;
}
public function setUsername($username){
$this->username = $username;
}
public function getRol(){
return $this->rol;
}
public function setRol($rol){
$this->rol = $rol;
}
}
?>
|
0admin
|
trunk/search/UsuarioSearchCriteria.php
|
PHP
|
oos
| 432
|