From 13f5c961d2901c80e79416aa542a1956969983e2 Mon Sep 17 00:00:00 2001 From: xperia64 Date: Sat, 12 Dec 2015 11:51:49 -0500 Subject: [PATCH 01/20] Some refactoring --- .project | 2 +- jni/helper/.gitignore | 0 res/values/strings.xml | 1 + .../xperia64/timidityae/DummyActivity.java | 4 +- .../timidityae/FileBrowserFragment.java | 464 ---- src/com/xperia64/timidityae/JNIHandler.java | 627 ++--- src/com/xperia64/timidityae/MusicService.java | 557 ++--- .../xperia64/timidityae/ObjectSerializer.java | 93 +- .../xperia64/timidityae/SettingsActivity.java | 1205 +++++----- .../xperia64/timidityae/TimidityActivity.java | 2050 +++++++---------- .../xperia64/timidityae/TrackFragment.java | 295 --- .../{ => gui}/TimidityAEWidgetProvider.java | 8 +- .../{ => gui/dialogs}/FileBrowserDialog.java | 83 +- .../dialogs}/SoundfontArrayAdapter.java | 70 +- .../{ => gui/dialogs}/SoundfontDialog.java | 185 +- .../{ => gui/fragments}/ArtFragment.java | 29 +- .../gui/fragments/FileBrowserFragment.java | 218 ++ .../{ => gui/fragments}/LyricFragment.java | 25 +- .../{ => gui/fragments}/PlayerFragment.java | 14 +- .../{ => gui/fragments}/PlaylistFragment.java | 20 +- .../gui/fragments/TrackFragment.java | 282 +++ .../xperia64/timidityae/util/ConfigSaver.java | 211 ++ .../timidityae/{ => util}/FileComparator.java | 30 +- .../timidityae/{ => util}/Globals.java | 43 +- .../timidityae/util/SettingsStorage.java | 5 + .../xperia64/timidityae/util/WavSaver.java | 232 ++ .../xperia64/timidityae/util/WavWriter.java | 124 + 27 files changed, 3262 insertions(+), 3615 deletions(-) mode change 100644 => 100755 jni/helper/.gitignore delete mode 100755 src/com/xperia64/timidityae/FileBrowserFragment.java delete mode 100755 src/com/xperia64/timidityae/TrackFragment.java rename src/com/xperia64/timidityae/{ => gui}/TimidityAEWidgetProvider.java (94%) rename src/com/xperia64/timidityae/{ => gui/dialogs}/FileBrowserDialog.java (68%) rename src/com/xperia64/timidityae/{ => gui/dialogs}/SoundfontArrayAdapter.java (53%) rename src/com/xperia64/timidityae/{ => gui/dialogs}/SoundfontDialog.java (61%) rename src/com/xperia64/timidityae/{ => gui/fragments}/ArtFragment.java (82%) create mode 100755 src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java rename src/com/xperia64/timidityae/{ => gui/fragments}/LyricFragment.java (83%) rename src/com/xperia64/timidityae/{ => gui/fragments}/PlayerFragment.java (95%) rename src/com/xperia64/timidityae/{ => gui/fragments}/PlaylistFragment.java (95%) create mode 100755 src/com/xperia64/timidityae/gui/fragments/TrackFragment.java create mode 100755 src/com/xperia64/timidityae/util/ConfigSaver.java rename src/com/xperia64/timidityae/{ => util}/FileComparator.java (56%) rename src/com/xperia64/timidityae/{ => util}/Globals.java (96%) create mode 100755 src/com/xperia64/timidityae/util/SettingsStorage.java create mode 100755 src/com/xperia64/timidityae/util/WavSaver.java create mode 100755 src/com/xperia64/timidityae/util/WavWriter.java diff --git a/.project b/.project index ba3919f..a9d601a 100755 --- a/.project +++ b/.project @@ -1,6 +1,6 @@ - TimidityAE2.0 + TimidityAE3.0 diff --git a/jni/helper/.gitignore b/jni/helper/.gitignore old mode 100644 new mode 100755 diff --git a/res/values/strings.xml b/res/values/strings.xml index a60f2b5..3939be2 100755 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -383,6 +383,7 @@ 127. Applause 128. Gunshot + 35. Acoustic Bass Drum 36. Bass Drum 1 diff --git a/src/com/xperia64/timidityae/DummyActivity.java b/src/com/xperia64/timidityae/DummyActivity.java index d6f5dd9..9e62774 100755 --- a/src/com/xperia64/timidityae/DummyActivity.java +++ b/src/com/xperia64/timidityae/DummyActivity.java @@ -10,6 +10,8 @@ public void onCreate( Bundle potato ) { // Really Google? This bug is still present in Lollipop. // I should not have to create an Activity just to keep my service alive. super.onCreate( potato ); - this.finish(); //With and without this something breaks. With, it closes the task manager. Without, volume buttons break and lag occurs. + this.finish(); // With and without this something breaks. With, it + // closes the task manager. Without, volume buttons + // break and lag occurs. } } \ No newline at end of file diff --git a/src/com/xperia64/timidityae/FileBrowserFragment.java b/src/com/xperia64/timidityae/FileBrowserFragment.java deleted file mode 100755 index df03a87..0000000 --- a/src/com/xperia64/timidityae/FileBrowserFragment.java +++ /dev/null @@ -1,464 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014 xperia64 - * - * Copyright (C) 1999-2008 Masanao Izumo - * - * Copyright (C) 1995 Tuukka Toivonen - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - ******************************************************************************/ -package com.xperia64.timidityae; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import com.xperia64.timidityae.R; - -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.os.Environment; -import android.support.v4.app.ListFragment; -import android.text.InputFilter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemLongClickListener; -import android.widget.ArrayAdapter; -import android.widget.EditText; -import android.widget.ListView; -import android.widget.Toast; -import android.text.Spanned; - -public class FileBrowserFragment extends ListFragment { - String currPath; - List path; - List fname; - boolean gotDir = false; - ActionFileBackListener mCallback; - public boolean localfinished=false; - public interface ActionFileBackListener { - public void needFileBackCallback(boolean yes); - } - - public static FileBrowserFragment create(String fold) - { - Bundle args = new Bundle(); - args.putString(Globals.currFoldKey, fold); - FileBrowserFragment fragment = new FileBrowserFragment(); - fragment.setArguments(args); - return fragment; - } - - @Override - public void onCreate(Bundle savedInstanceState) - { - super.onCreate(savedInstanceState); - if (getArguments() != null) - currPath = getArguments().getString(Globals.currFoldKey); - if (currPath == null) - currPath = Environment.getExternalStorageDirectory().getAbsolutePath(); - else if(!new File(currPath).exists()) - currPath = Environment.getExternalStorageDirectory().getAbsolutePath(); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) - { - View v = inflater.inflate(R.layout.list, container, false); - return v; - } - - @Override - public void onViewCreated(View view, Bundle savedInstanceState) - { - super.onViewCreated(view, savedInstanceState); - if (!gotDir) - { - gotDir = true; - getDir(currPath); - } - } - - @Override - public void onAttach(Context activity) - { - super.onAttach(activity); - try - { - mCallback = (ActionFileBackListener) activity; - } catch (ClassCastException e) - { - throw new ClassCastException(activity.toString() - + " must implement ActionFileBackListener"); - } - if (Globals.shouldRestore) - { - Intent new_intent = new Intent(); - new_intent.setAction(getActivity().getResources().getString( - R.string.msrv_rec)); - new_intent.putExtra( - getActivity().getResources().getString(R.string.msrv_cmd), - 10); - getActivity().sendBroadcast(new_intent); - } - } - - public void getDir(String dirPath) - { - currPath = dirPath; - fname = new ArrayList(); - path = new ArrayList(); - if (currPath != null) - { - File f = new File(currPath); - if (f.exists()) - { - File[] files = f.listFiles(); - if (files != null&&files.length > 0) - { - - Arrays.sort(files, new FileComparator()); - - // System.out.println(currPath); - if (!currPath.matches("[/]+")) - { - fname.add("../"); - path.add(f.getParent() + "/"); - mCallback.needFileBackCallback(true); - } else - { - mCallback.needFileBackCallback(false); - } - for (int i = 0; i < files.length; i++) - { - File file = files[i]; - if ((!file.getName().startsWith(".") && !Globals.showHiddenFiles) - || Globals.showHiddenFiles) - { - if (file.isFile()) - { - int dotPosition = file.getName().lastIndexOf("."); - String extension = ""; - if (dotPosition != -1) - { - extension = (file.getName() - .substring(dotPosition)) - .toLowerCase(Locale.US); - if (extension != null) - { - - if ((Globals.showVideos ? Globals.musicVideoFiles - : Globals.musicFiles) - .contains("*" + extension + "*")) - { - - path.add(file.getAbsolutePath()); - fname.add(file.getName()); - } - } else if (file.getName().endsWith("/")) - { - path.add(file.getAbsolutePath() + "/"); - fname.add(file.getName() + "/"); - } - } - } else - { - path.add(file.getAbsolutePath() + "/"); - fname.add(file.getName() + "/"); - } - } - } - } else - { - if (!currPath.matches("[/]+")) - { - fname.add("../"); - path.add(f.getParent() + "/"); - - } - } - ArrayAdapter fileList = new ArrayAdapter( - getActivity(), R.layout.row, fname); - getListView().setFastScrollEnabled(true); - getListView().setOnItemLongClickListener(new OnItemLongClickListener() - { - - @Override - public boolean onItemLongClick(AdapterView l, View v, final int position, long id) - { - localfinished=false; - if(new File(path.get(position)).isFile()&& Globals.isMidi(path.get(position))) - { - - - AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); - - alert.setTitle("Convert to WAV File"); - alert.setMessage("Exports the MIDI/MOD file to WAV.\nNative Midi must be disabled in settings.\nWarning: WAV files are large."); - InputFilter filter = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, - Spanned dest, int dstart, int dend) { - for (int i = start; i < end; i++) { - String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; - if (IC.contains("*"+source.charAt(i)+"*")) { - return ""; - } - } - return null; - } - }; - // Set an EditText view to get user input - final EditText input = new EditText(getActivity()); - input.setFilters(new InputFilter[]{filter}); - alert.setView(input); - - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - if(!value.toLowerCase(Locale.US).endsWith(".wav")) - value+=".wav"; - String parent=path.get(position).substring(0,path.get(position).lastIndexOf('/')+1); - boolean aWrite=true; - boolean alreadyExists = new File(parent+value).exists(); - String needRename = null; - String probablyTheRoot = ""; - String probablyTheDirectory = ""; - try{ - new FileOutputStream(parent+value,true).close(); - }catch(FileNotFoundException e) - { - aWrite=false; - } catch (IOException e) - { - e.printStackTrace(); - } - if(!alreadyExists&&aWrite) - new File(parent+value).delete(); - if(aWrite&&new File(parent).canWrite()) - { - value=parent+value; - }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null) - { - // Write the file to getExternalFilesDir, then move it with the Uri - // We need to tell JNIHandler that movement is needed. - - String[] tmp = Globals.getDocFilePaths(getActivity(),parent); - probablyTheDirectory = tmp[0]; - probablyTheRoot = tmp[1]; - if(probablyTheDirectory.length()>1) - { - needRename = parent.substring(parent.indexOf(probablyTheRoot)+probablyTheRoot.length())+value; - value = probablyTheDirectory+'/'+value; - }else{ - value=Environment.getExternalStorageDirectory().getAbsolutePath()+'/'+value; - } - }else{ - value=Environment.getExternalStorageDirectory().getAbsolutePath()+'/'+value; - } - final boolean canWrite = aWrite; - final String finalval = value; - final String needToRename = needRename; - final String probRoot = probablyTheRoot; - if(new File(finalval).exists()||(new File(probRoot+needRename).exists()&&needToRename!=null)) - { - AlertDialog dialog2 = new AlertDialog.Builder(getActivity()).create(); - dialog2.setTitle("Warning"); - dialog2.setMessage("Overwrite WAV file?"); - dialog2.setCancelable(false); - dialog2.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - if(!canWrite&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - if(needToRename!=null) - { - Globals.tryToDeleteFile(getActivity(), probRoot+needToRename); - Globals.tryToDeleteFile(getActivity(), finalval); - }else{ - Globals.tryToDeleteFile(getActivity(), finalval); - } - }else{ - new File(finalval).delete(); - } - - saveWavPart2(position, finalval, needToRename); - - } - - - }); - dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - - } - }); - dialog2.show(); - }else{ - saveWavPart2(position, finalval, needToRename); - } - - } - }); - - alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - // Canceled. - } - }); - - alert.show(); - - return true; - }else{ - - } - return false; - } - - }); - setListAdapter(fileList); - } - } - } - - - public void saveWavPart2(final int position, final String finalval, final String needToRename) - { - ((TimidityActivity)getActivity()).writeFile(path.get(position), finalval); - final ProgressDialog prog; - prog = new ProgressDialog(getActivity()); - prog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - prog.setTitle("Converting to WAV"); - prog.setMessage("Converting..."); - prog.setIndeterminate(false); - prog.setCancelable(false); - prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - prog.show(); - new Thread(new Runnable() { - @Override - public void run() { - while(!localfinished&&prog.isShowing()){ - - prog.setMax(JNIHandler.maxTime); - prog.setProgress(JNIHandler.currTime); - try {Thread.sleep(25);} catch (InterruptedException e){}} - if(!localfinished) - { - JNIHandler.stop(); - getActivity().runOnUiThread(new Runnable() { - public void run() { - Toast.makeText( getActivity(), "Conversion canceled", Toast.LENGTH_SHORT).show(); - if(!Globals.keepWav) - { - if(new File(finalval).exists()) - new File(finalval).delete(); - }else{ - getDir(currPath); - } - } - }); - - - }else{ - getActivity().runOnUiThread(new Runnable() { - public void run() { - String trueName = finalval; - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null&&needToRename!=null) - { - if(Globals.renameDocumentFile(getActivity(), finalval, needToRename)) - { - trueName=needToRename; - }else{ - trueName="Error"; - } - } - Toast.makeText( getActivity(), "Wrote "+trueName, Toast.LENGTH_SHORT).show(); - prog.dismiss(); - getDir(currPath); - } - }); - } - } - }).start(); - } - - - @Override - public void onListItemClick(ListView l, View v, int position, long id) - { - File file = new File(path.get(position)); - if (file.isDirectory()) - { - if (file.canRead()) - { - getDir(path.get(position)); - } else - { - new AlertDialog.Builder(getActivity()) - .setIcon(R.drawable.ic_launcher) - .setTitle( - "[" - + file.getName() - + "] " - + (getActivity().getResources() - .getString(R.string.fb_cread))) - .setPositiveButton( - getActivity().getResources().getString( - android.R.string.ok), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, - int which) - { - } - }).show(); - } - } else - { - if (file.canRead()) - { - ArrayList files = new ArrayList(); - int firstFile = -1; - for (int i = 0; i < path.size(); i++) - { - if (!path.get(i).endsWith("/")) - { - files.add(path.get(i)); - if (firstFile == -1) - { - firstFile = i; - } - } - } - ((TimidityActivity) getActivity()).selectedSong(files, position - - firstFile, true, false, false); - } - } - } - - @Override - public void onSaveInstanceState(Bundle outState) - { - super.onSaveInstanceState(outState); - outState.putString(Globals.currFoldKey, currPath); - } -} diff --git a/src/com/xperia64/timidityae/JNIHandler.java b/src/com/xperia64/timidityae/JNIHandler.java index 7f7ba97..6b50d2b 100755 --- a/src/com/xperia64/timidityae/JNIHandler.java +++ b/src/com/xperia64/timidityae/JNIHandler.java @@ -11,34 +11,29 @@ ******************************************************************************/ package com.xperia64.timidityae; -import java.io.BufferedOutputStream; -import java.io.DataOutputStream; import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; -import java.io.RandomAccessFile; import java.util.ArrayList; +import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.WavWriter; + import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.media.MediaPlayer; - //import android.util.Log; public class JNIHandler { - - // config folder, config file, mono, resampling algorithm, bits, preserve // silence public static native int loadLib(String libPath); + public static native int unloadLib(); - private static native int prepareTimidity(String config, String config2, - int jmono, int jcustResamp, int jsixteen, int jPresSil, int jreloading, int jfreeInsts); + + private static native int prepareTimidity(String config, String config2, int jmono, int jcustResamp, int jsixteen, int jPresSil, int jreloading, int jfreeInsts); private static native int loadSongTimidity(String filename); @@ -55,7 +50,8 @@ private static native int prepareTimidity(String config, String config2, public static native int setResampleTimidity(int jcustResamp); public static native int decompressSFArk(String from, String to); - public static DataOutputStream outFile; + + // public static DataOutputStream outFile; public static AudioTrack mAudioTrack; public static MediaPlayer mMediaPlayer; public static int maxTime = 0; @@ -81,17 +77,12 @@ private static native int prepareTimidity(String config, String config2, public static int exceptional = 0; public static int ttr; public static int tt; - public static int tb=0; + public static int tb = 0; public static int voice; - public static int maxvoice=256; - public static int koffset=0; - //public static boolean breakLoops = false; - // file output things - public static boolean writeToFile = false; - public static long filesize=0; - public static String fileToWrite=""; - public static boolean finishedWriting=false; - public static boolean dataWritten=false; + public static int maxvoice = 256; + public static int koffset = 0; + // public static boolean breakLoops = false; + public static boolean dataWritten = false; public static boolean shouldPlayNow = true; public static int ultSafetyCheck = 1; @@ -100,315 +91,160 @@ private static native int prepareTimidity(String config, String config2, static boolean prepared = false; + public static WavWriter currentWavWriter = null; + public static void pause() // or unpause. { - if (Globals.isPlaying == 0) - { - if (paused) - { + if (Globals.isPlaying == 0) { + if (paused) { paused = false; - if (type) - { + if (type) { mMediaPlayer.start(); - } else - { + } else { controlTimidity(7, 0); - if(!(writeToFile&&!finishedWriting)&&mAudioTrack!=null) - { - try - { - mAudioTrack.play(); - } catch (Exception e) - { - e.printStackTrace(); - } + if (!(currentWavWriter != null && !currentWavWriter.finishedWriting) && mAudioTrack != null) { + try { + mAudioTrack.play(); + } catch (Exception e) { + e.printStackTrace(); + } } } - } else - { + } else { paused = true; - if (type) - { + if (type) { mMediaPlayer.pause(); - } else - { + } else { controlTimidity(7, 0); - if(!(writeToFile&&!finishedWriting)&&mAudioTrack!=null) - { - try - { - mAudioTrack.pause(); - } catch (Exception e) - { - e.printStackTrace(); - } + if (!(currentWavWriter != null && !currentWavWriter.finishedWriting) && mAudioTrack != null) { + try { + mAudioTrack.pause(); + } catch (Exception e) { + e.printStackTrace(); + } } } } } } - public static void stop() - { - if (type) - { + public static void stop() { + if (type) { mMediaPlayer.setOnCompletionListener(null); - try - { + try { mMediaPlayer.stop(); - } catch (IllegalStateException e) - { + } catch (IllegalStateException e) { } Globals.isPlaying = 1; ultSafetyCheck = 1; alternativeCheck = 555555; - } else - { + } else { controlTimidity(30, 0); } } - public static void seekTo(int time) - { - if (type) - { + public static void seekTo(int time) { + if (type) { mMediaPlayer.seekTo(time); - } else - { + } else { controlTimidity(6, time); waitUntilReady(); } } - private static byte[] intToByteArray(int i) - { - byte[] b = new byte[4]; - b[0] = (byte) (i & 0xFF); - b[1] = (byte) ((i >> 8) & 0xFF); - b[2] = (byte) ((i >> 16) & 0xFF); - b[3] = (byte) ((i >> 24) & 0xFF); - return b; - } - - public static void waitUntilReady() - { + + public static void waitUntilReady() { waitUntilReady(10); } - public static void waitUntilReady(int interval) - { - while(!JNIHandler.timidityReady()) - { - try {Thread.sleep(interval);} catch (InterruptedException e){} + + public static void waitUntilReady(int interval) { + while (!JNIHandler.timidityReady()) { + try { + Thread.sleep(interval); + } catch (InterruptedException e) { + } } } - public static void waitForStop() - { + + public static void waitForStop() { waitForStop(10); } - public static void waitForStop(int interval) - { - while(Globals.isPlaying==0||alternativeCheck == 333333||ultSafetyCheck == 0) - { - try {Thread.sleep(interval);} catch (InterruptedException e){} - } - } - public static byte[] shortToByteArray(short data) - { - return new byte[]{(byte)(data & 0xff),(byte)((data >>> 8) & 0xff)}; - } - public static void setupOutputFile(String filename) - { - if(Globals.isPlaying==0) - { - mAudioTrack.stop(); - mAudioTrack.release(); - } - writeToFile=true; - finishedWriting=false; - fileToWrite=filename; - filesize=0; - try { - long mySubChunk1Size = 16; - int myBitsPerSample= (bits?16:8); - int myFormat = 1; - long myChannels = ((monoop<2)?1:2); - long mySampleRate = rate; - long myByteRate = mySampleRate * myChannels * myBitsPerSample/8; - int myBlockAlign = (int) (myChannels * myBitsPerSample/8); - - //byte[] clipData = getBytesFromFile(fileToConvert); - - //long myDataSize = clipData.length; // this changes - //long myChunk2Size = myDataSize * myChannels * myBitsPerSample/8; - //long myChunkSize = 36 + myChunk2Size; - - OutputStream os; - os = new FileOutputStream(new File(fileToWrite)); - BufferedOutputStream bos = new BufferedOutputStream(os); - outFile = new DataOutputStream(bos); - - outFile.writeBytes("RIFF"); // 00 - RIFF - outFile.write(intToByteArray(0/*(int)myChunkSize*/), 0, 4); // 04 - how big is the rest of this file? - outFile.writeBytes("WAVE"); // 08 - WAVE - outFile.writeBytes("fmt "); // 12 - fmt - outFile.write(intToByteArray((int)mySubChunk1Size), 0, 4); // 16 - size of this chunk - outFile.write(shortToByteArray((short)myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation - outFile.write(shortToByteArray((short)myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???) - outFile.write(intToByteArray((int)mySampleRate), 0, 4); // 24 - samples per second (numbers per second) - outFile.write(intToByteArray((int)myByteRate), 0, 4); // 28 - bytes per second - outFile.write(shortToByteArray((short)myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels - outFile.write(shortToByteArray((short)myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24 - outFile.writeBytes("data"); // 36 - data - outFile.write(intToByteArray(0/*(int)myChunkSize*/), 0, 4); // 40 - how big is this data chunk - //outFile.write(clipData); // 44 - the actual data itself - just a long string of numbers - - //outFile.flush(); - //outFile.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static void finishOutput() - { - if(writeToFile&&!finishedWriting) - { - try - { - outFile.flush(); - outFile.close(); - } catch (IOException e1) - { - e1.printStackTrace(); - } - finishedWriting=true; - long myDataSize = filesize; // this changes - int myBitsPerSample= (bits?16:8); - long myChannels = ((monoop<2)?1:2); - long myChunk2Size = myDataSize * myChannels * myBitsPerSample/8; - long myChunkSize = 36 + myChunk2Size; - - RandomAccessFile raf = null; - try - { - raf = new RandomAccessFile(fileToWrite, "rw"); - } catch (FileNotFoundException e) - { - e.printStackTrace(); - } - - try - { - raf.seek(04); - raf.write(intToByteArray((int)myChunkSize)); - raf.seek(40); - raf.write(intToByteArray((int)myDataSize)); - raf.close(); - } catch (Exception e) - { - e.printStackTrace(); + + public static void waitForStop(int interval) { + while (Globals.isPlaying == 0 || alternativeCheck == 333333 || ultSafetyCheck == 0) { + try { + Thread.sleep(interval); + } catch (InterruptedException e) { } } } - public static void buffit(byte[] data, int length) - { - dataWritten=true; - if(shouldPlayNow) - { - if(writeToFile&&!finishedWriting) - { - if(monoop==0) - { - byte[] mono = new byte[length/2]; - if(bits) - { - for (int i = 0 ; i < mono.length/2; ++i){ - int HI = 1; int LO = 0; - int left = (data[i * 4 + HI] << 8) | (data[i * 4 + LO] & 0xff); - int right = (data[i * 4 + 2 + HI] << 8) | (data[i * 4 + 2 + LO] & 0xff); - int avg = (left + right) / 2; - mono[i * 2 + HI] = (byte)((avg >> 8) & 0xff); - mono[i * 2 + LO] = (byte)(avg & 0xff); - } - }else{ - for (int i = 0 ; i < mono.length; ++i){ - int left = (data[i * 2])&0xff; - int right = (data[i * 2 + 1])&0xff; - int avg = (left + right) / 2; - mono[i] = (byte)(avg); - } + + public static void setupOutputFile(String filename) { + currentWavWriter = new WavWriter(); + currentWavWriter.setupOutputFile(filename, bits, (monoop < 2), rate); + } + + public static void buffit(byte[] data, int length) { + dataWritten = true; + if (shouldPlayNow) { + + if (monoop == 0) { + byte[] mono = new byte[length / 2]; + if (bits) { + for (int i = 0; i < mono.length / 2; ++i) { + int HI = 1; + int LO = 0; + int left = (data[i * 4 + HI] << 8) | (data[i * 4 + LO] & 0xff); + int right = (data[i * 4 + 2 + HI] << 8) | (data[i * 4 + 2 + LO] & 0xff); + int avg = (left + right) / 2; + mono[i * 2 + HI] = (byte) ((avg >> 8) & 0xff); + mono[i * 2 + LO] = (byte) (avg & 0xff); } - try - { - filesize+=mono.length; - outFile.write(mono, 0, mono.length); - } catch (IOException e) - { - e.printStackTrace(); + } else { + for (int i = 0; i < mono.length; ++i) { + int left = (data[i * 2]) & 0xff; + int right = (data[i * 2 + 1]) & 0xff; + int avg = (left + right) / 2; + mono[i] = (byte) (avg); } - }else{ - try - { - filesize+=length; - outFile.write(data, 0, length); - } catch (IOException e) - { + } + if (currentWavWriter != null && !currentWavWriter.finishedWriting) { + try { + currentWavWriter.write(data, 0, length); + } catch (IOException e) { + // TODO Auto-generated catch block e.printStackTrace(); } + } else { + try { + mAudioTrack.write(mono, 0, mono.length); + } catch (IllegalStateException e) { + } } - - }else{ - if(monoop==0) - { - byte[] mono = new byte[length/2]; - if(bits) - { - for (int i = 0 ; i < mono.length/2; ++i){ - int HI = 1; int LO = 0; - int left = (data[i * 4 + HI] << 8) | (data[i * 4 + LO] & 0xff); - int right = (data[i * 4 + 2 + HI] << 8) | (data[i * 4 + 2 + LO] & 0xff); - int avg = (left + right) / 2; - mono[i * 2 + HI] = (byte)((avg >> 8) & 0xff); - mono[i * 2 + LO] = (byte)(avg & 0xff); - } - }else{ - for (int i = 0 ; i < mono.length; ++i){ - int left = (data[i * 2])&0xff; - int right = (data[i * 2 + 1])&0xff; - int avg = (left + right) / 2; - mono[i] = (byte)(avg); - } + } else { + if (currentWavWriter != null && !currentWavWriter.finishedWriting) { + try { + currentWavWriter.write(data, 0, length); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - try - { - mAudioTrack.write(mono, 0, mono.length); - } catch (IllegalStateException e) - {} - }else{ - try - { + } else { + try { mAudioTrack.write(data, 0, length); - } catch (IllegalStateException e) - {} + } catch (IllegalStateException e) { + } } - } } - } - public static int init(String path, String file,int mono, int resamp, boolean sixteen, int b, int r, boolean preserveSilence, boolean reloading, boolean freeInsts) - { - if (!prepared) - { - - System.out.println(String.format("Opening Timidity: Path: %s cfgFile: %s resample: %s mono: %s sixteenBit: %s buffer: %d rate: %d", - path, file, - Globals.sampls[resamp],((mono==1)?"true":"false"),(sixteen?"true":"false"),b,r)); - System.out.println("Max channels: "+MAX_CHANNELS); - for (int i = 0; i < MAX_CHANNELS; i++) - { + public static int init(String path, String file, int mono, int resamp, boolean sixteen, int b, int r, boolean preserveSilence, boolean reloading, boolean freeInsts) { + if (!prepared) { + + System.out.println(String.format("Opening Timidity: Path: %s cfgFile: %s resample: %s mono: %s sixteenBit: %s buffer: %d rate: %d", path, file, Globals.sampls[resamp], ((mono == 1) ? "true" : "false"), (sixteen ? "true" : "false"), b, r)); + System.out.println("Max channels: " + MAX_CHANNELS); + for (int i = 0; i < MAX_CHANNELS; i++) { volumes.add(75); // Assuming not XG programs.add(0); drums.add(i == 9); @@ -419,116 +255,91 @@ public static int init(String path, String file,int mono, int resamp, boolean si bits = sixteen; rate = r; buffer = b; - if(mMediaPlayer == null) + if (mMediaPlayer == null) mMediaPlayer = new MediaPlayer(); prepared = true; - return prepareTimidity(path, path + file, (monoop==1) ? 1 : 0, resamp, - bits ? 1 : 0, preserveSilence ? 1 : 0, reloading ? 1:0, freeInsts ? 1:0); - } else - { + return prepareTimidity(path, path + file, (monoop == 1) ? 1 : 0, resamp, bits ? 1 : 0, preserveSilence ? 1 : 0, reloading ? 1 : 0, freeInsts ? 1 : 0); + } else { // Log.w("Warning", "Attempt to prepare again cancelled."); return -99; } } - static Thread t; - public static int play(final String songTitle) - { - if (new File(songTitle).exists()) - { - if (alternativeCheck == 555555) - { - koffset=0; - tb=0; + public static int play(final String songTitle) { + if (new File(songTitle).exists()) { + + if (alternativeCheck == 555555) { + koffset = 0; + tb = 0; currentLyric = ""; overwriteLyricAt = 0; Globals.isPlaying = 0; ultSafetyCheck = 0; type = false; paused = false; - dataWritten=false; - shouldPlayNow=true; - for (int i = 0; i < MAX_CHANNELS; i++) - { - custInst.set(i,false); - custVol.set(i,false); + dataWritten = false; + shouldPlayNow = true; + for (int i = 0; i < MAX_CHANNELS; i++) { + custInst.set(i, false); + custVol.set(i, false); } - if (!Globals.isMidi(songTitle)) - { + if (!Globals.isMidi(songTitle)) { type = true; - try - { + try { mMediaPlayer.setOnCompletionListener(null); mMediaPlayer.reset(); - mMediaPlayer - .setAudioStreamType(AudioManager.STREAM_MUSIC); + mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setVolume(100, 100); mMediaPlayer.setDataSource(songTitle); - mMediaPlayer - .setOnPreparedListener(new MediaPlayer.OnPreparedListener() { - public void onPrepared(MediaPlayer arg0) - { - initSeeker(arg0.getDuration()); - } - }); + mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { + public void onPrepared(MediaPlayer arg0) { + initSeeker(arg0.getDuration()); + } + }); mMediaPlayer.prepare(); mMediaPlayer.start(); alternativeCheck = 333333; - mMediaPlayer - .setOnCompletionListener(new MediaPlayer.OnCompletionListener() { - @Override - public void onCompletion(MediaPlayer arg0) - { - arg0.setOnCompletionListener(null); - - Globals.isPlaying = 1; - ultSafetyCheck = 1; - alternativeCheck = 555555; - } - }); - - } catch (Exception e) - { + mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { + @Override + public void onCompletion(MediaPlayer arg0) { + arg0.setOnCompletionListener(null); + + Globals.isPlaying = 1; + ultSafetyCheck = 1; + alternativeCheck = 555555; + } + }); + + } catch (Exception e) { e.printStackTrace(); } - - } else - { + } else { // Reset the audio track every time. // The audiotrack should be in the same thread as the // timidity stuff for black midi. t = new Thread(new Runnable() { - public void run() - { + public void run() { alternativeCheck = 333333; - mAudioTrack = new AudioTrack( - AudioManager.STREAM_MUSIC, rate, - (monoop==2) ? AudioFormat.CHANNEL_OUT_STEREO - : AudioFormat.CHANNEL_OUT_MONO, - (bits) ? AudioFormat.ENCODING_PCM_16BIT - : AudioFormat.ENCODING_PCM_8BIT, - buffer, AudioTrack.MODE_STREAM); - - if(!(writeToFile&&!finishedWriting)) - try - { + mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, rate, (monoop == 2) ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO, (bits) ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT, buffer, AudioTrack.MODE_STREAM); + + if (!(currentWavWriter != null && !currentWavWriter.finishedWriting)) + try { mAudioTrack.play(); - } catch (Exception e) - { + } catch (Exception e) { exceptional |= 1; } - - alternativeCheck=loadSongTimidity(songTitle); + + alternativeCheck = loadSongTimidity(songTitle); alternativeCheck = 555555; - - if(writeToFile&&!finishedWriting) - finishOutput(); + + if (currentWavWriter != null && !currentWavWriter.finishedWriting) + currentWavWriter.finishOutput(); } }); t.setPriority(Thread.MAX_PRIORITY); @@ -537,8 +348,7 @@ public void run() } // } return 0; - } else - { + } else { return -9; } @@ -546,8 +356,7 @@ public void run() return -1; } - public static void controlMe(int y) - { + public static void controlMe(int y) { /* * String[] control = { "PM_REQ_MIDI", * @@ -579,83 +388,71 @@ public static void controlMe(int y) * * "PM_REQ_DIVISIONS" }; */ - if (y == 10) - { - - //Globals.isPlaying = 1; // Wait until all is unloaded. - if (mAudioTrack != null) - { - try - { + if (y == 10) { + + // Globals.isPlaying = 1; // Wait until all is unloaded. + if (mAudioTrack != null) { + try { mAudioTrack.stop(); - } catch (IllegalStateException e) - { + } catch (IllegalStateException e) { } } mAudioTrack.release(); - } /*else if (y == 10) - { - // TODO something here to tell that timidity is ready - }*/ + } /* + * else if (y == 10) { // TODO something here to tell that timidity + * is ready } + */ } - public static int bufferSize() - { - if(writeToFile&&!finishedWriting) - { + public static int bufferSize() { + if (currentWavWriter != null && !currentWavWriter.finishedWriting) { return 0; } - try - { - - return (((int) (mAudioTrack.getPlaybackHeadPosition() - * mAudioTrack.getChannelCount() * (2 - (mAudioTrack - .getAudioFormat() & 1))))); // # of frames *4 = comparison - // factor - } catch (IllegalStateException e) - { + try { + + return (((int) (mAudioTrack.getPlaybackHeadPosition() * mAudioTrack.getChannelCount() * (2 - (mAudioTrack.getAudioFormat() & 1))))); // # + // of + // frames + // *4 + // = + // comparison + // factor + } catch (IllegalStateException e) { return 0; } } - public static void finishIt() - { + public static void finishIt() { ultSafetyCheck = 1; Globals.isPlaying = 1; } - public static void flushIt() - { + public static void flushIt() { mAudioTrack.flush(); } - public static void initSeeker(int seeker) - { + public static void initSeeker(int seeker) { maxTime = seeker; } - public static void updateSeeker(int seekIt, int voices) - { + public static void updateSeeker(int seekIt, int voices) { currTime = seekIt; - voice=voices; + voice = voices; } - public static int getRate() - { + public static int getRate() { return mAudioTrack.getSampleRate(); } - public static void updateLyrics(byte[] b) - { + public static void updateLyrics(byte[] b) { final StringBuilder stb = new StringBuilder(currentLyric); final StringBuilder tmpBuild = new StringBuilder(); boolean isNormalLyric = b[0] == 'L'; boolean isNewline = b[0] == 'N'; boolean isComment = b[0] == 'Q'; - for (int i = 2; i < b.length; i++) - { + for (int i = 2; i < b.length; i++) { if (b[i] == 0) break; tmpBuild.append((char) b[i]); @@ -665,16 +462,13 @@ public static void updateLyrics(byte[] b) stb.append(tmpBuild); stb.append('\n'); overwriteLyricAt = stb.length(); - } else if (isNewline || isNormalLyric) - { - if (isNewline) - { + } else if (isNewline || isNormalLyric) { + if (isNewline) { stb.append('\n'); overwriteLyricAt = stb.length(); } stb.replace(overwriteLyricAt, stb.length(), tmpBuild.toString()); - } else - { // A marker or something + } else { // A marker or something stb.append(tmpBuild); stb.append("\n"); overwriteLyricAt = stb.length(); @@ -682,43 +476,38 @@ public static void updateLyrics(byte[] b) currentLyric = stb.toString(); } - public static void updateMaxChannels(int val) - { + public static void updateMaxChannels(int val) { MAX_CHANNELS = val; } - public static void updateProgramInfo(int ch, int prog) - { + public static void updateProgramInfo(int ch, int prog) { if (ch < MAX_CHANNELS) programs.set(ch, prog); } - public static void updateVolInfo(int ch, int vol) - { + public static void updateVolInfo(int ch, int vol) { if (ch < MAX_CHANNELS) volumes.set(ch, vol); } - public static void updateDrumInfo(int ch, int isDrum) - { + public static void updateDrumInfo(int ch, int isDrum) { if (ch < MAX_CHANNELS) drums.set(ch, (isDrum != 0)); } - public static void updateTempo(int t, int tr) - { - tt=t; - ttr=tr; + public static void updateTempo(int t, int tr) { + tt = t; + ttr = tr; // TODO something // int x = (int) (500000 / (double) t * 120 * (double) tr / 100 + 0.5); // System.out.println("T: "+t+ " TR: "+tr+" X: "+x); } - public static void updateMaxVoice(int vvv) - { - maxvoice=vvv; + + public static void updateMaxVoice(int vvv) { + maxvoice = vvv; } - public static void updateKey(int k) - { - koffset=k; + + public static void updateKey(int k) { + koffset = k; } } diff --git a/src/com/xperia64/timidityae/MusicService.java b/src/com/xperia64/timidityae/MusicService.java index 71846f6..c02eb63 100755 --- a/src/com/xperia64/timidityae/MusicService.java +++ b/src/com/xperia64/timidityae/MusicService.java @@ -29,6 +29,8 @@ import java.util.zip.GZIPOutputStream; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.gui.TimidityAEWidgetProvider; +import com.xperia64.timidityae.util.Globals; import android.annotation.SuppressLint; import android.app.Notification; @@ -64,7 +66,7 @@ public class MusicService extends Service{ public ArrayList playList; public SparseIntArray shuffledIndices; - public SparseIntArray reverseShuffledIndices; + public SparseIntArray reverseShuffledIndices; // HashMap public int currSongNumber=-1; public int realSongNumber=-1; public boolean shouldStart; @@ -80,24 +82,26 @@ public class MusicService extends Service{ boolean phonepause=false; PowerManager.WakeLock wl; boolean shouldDoWidget=true; - int[] ids; + int[] widgetIds; String currTitle; - Notification n; - Notification q; + Notification mainNotification; PowerManager pm; RemoteViews remoteViews; Random random = new Random(System.currentTimeMillis()); private final IBinder musicBind = new MusicBinder(); @Override - public IBinder onBind(Intent arg0) { + public IBinder onBind(Intent arg0) + { return musicBind; } - public class MusicBinder extends Binder { - MusicService getService() { - return MusicService.this; - } + public class MusicBinder extends Binder + { + MusicService getService() + { + return MusicService.this; } + } private Handler handler; @@ -120,7 +124,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { public void onCallStateChanged(int state, String incomingNumber) { if (state == TelephonyManager.CALL_STATE_RINGING) { //Incoming call: Pause music - if(Globals.isPlaying==0&&!JNIHandler.paused&&!phonepause&&!(JNIHandler.writeToFile&&!JNIHandler.finishedWriting)) + if(Globals.isPlaying==0&&!JNIHandler.paused&&!phonepause&&!(JNIHandler.currentWavWriter!=null&&!JNIHandler.currentWavWriter.finishedWriting)) { phonepause=true; pause(); @@ -138,8 +142,7 @@ public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); } }; - - // onHandleIntent ... + public void genShuffledPlist() { shuffledIndices = new SparseIntArray(); @@ -162,36 +165,37 @@ public void genShuffledPlist() @SuppressWarnings("unchecked") @Override public void onReceive(Context context, Intent intent) { - if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { + if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) + { KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); - if (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()||KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE == event.getKeyCode()) { - if(Globals.isPlaying==0) - { - pause(); - }else{ - play(); - } - }else if(KeyEvent.KEYCODE_MEDIA_NEXT == event.getKeyCode()) - { - shouldAdvance=false; - next(); - }else if(KeyEvent.KEYCODE_MEDIA_PREVIOUS == event.getKeyCode()) - { - shouldAdvance=false; - previous(); - }else if(KeyEvent.KEYCODE_MEDIA_PAUSE == event.getKeyCode()) + if(event.getAction() == KeyEvent.ACTION_DOWN) { - if(Globals.isPlaying==0) - { - pause(); - }else{ - play(); - } - }else if(KeyEvent.KEYCODE_MEDIA_STOP == event.getKeyCode()) - { - fullStop=true; - shouldAdvance=false; - stop(); + switch(event.getKeyCode()) + { + case KeyEvent.KEYCODE_MEDIA_PLAY: + case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: + case KeyEvent.KEYCODE_MEDIA_PAUSE: + if(Globals.isPlaying==0) + { + pause(); + }else{ + play(); + } + break; + case KeyEvent.KEYCODE_MEDIA_NEXT: + shouldAdvance=false; + next(); + break; + case KeyEvent.KEYCODE_MEDIA_PREVIOUS: + shouldAdvance=false; + previous(); + break; + case KeyEvent.KEYCODE_MEDIA_STOP: + fullStop=true; + shouldAdvance=false; + stop(); + break; + } } }else if(Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) { @@ -210,38 +214,44 @@ public void onReceive(Context context, Intent intent) { //System.out.println("Cmd received: "+cmd); // Sigh. Here we go: + Intent outgoingIntent = new Intent(); switch(cmd) { case 0: // We have a new playlist. Load it and the immediate song to load. death=true; ArrayList tmpList = Globals.plist; if(tmpList==null) + { break; + } int tmpNum = intent.getIntExtra(getResources().getString(R.string.msrv_songnum), -1); if(tmpNum<=-1) + { break; + } boolean shouldNotLoadPlist = intent.getBooleanExtra(getResources().getString(R.string.msrv_dlplist), false); - - if(!shouldNotLoadPlist) // mmm. Double negatives. + if(shouldNotLoadPlist) { - currSongNumber=realSongNumber=tmpNum; - playList=tmpList; - genShuffledPlist(); - - }else{ currSongNumber = tmpNum; if(shuffleMode == 1) + { realSongNumber = shuffledIndices.get(tmpNum); + } + }else{ + currSongNumber=realSongNumber=tmpNum; + playList=tmpList; + genShuffledPlist(); } Globals.plist=null; tmpList=null; currFold=intent.getStringExtra(getResources().getString(R.string.msrv_currfold)); if(shuffleMode == 1 && !shouldNotLoadPlist) + { currSongNumber = reverseShuffledIndices.get(realSongNumber); - Intent new_intent20 = new Intent(); // I should name these properly at some point. I could use a more global intent variable I guess. - new_intent20.setAction(getResources().getString(R.string.ta_rec)); - new_intent20.putExtra(getResources().getString(R.string.ta_cmd), 4); + } + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 4); if(shuffleMode == 1) { Globals.tmpplist=new ArrayList(); @@ -252,7 +262,7 @@ public void onReceive(Context context, Intent intent) { }else{ Globals.tmpplist=playList; } - sendBroadcast(new_intent20); + sendBroadcast(outgoingIntent); //if(shouldStart=intent.getBooleanExtra(getResources().getString(R.string.msrv_begin),false)||true) // { play(); @@ -302,9 +312,8 @@ public void onReceive(Context context, Intent intent) { fixedShuffle = true; } } - Intent new_intent19 = new Intent(); - new_intent19.setAction(getResources().getString(R.string.ta_rec)); - new_intent19.putExtra(getResources().getString(R.string.ta_cmd), 4); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 4); if(shuffleMode == 1) { Globals.tmpplist=new ArrayList(); @@ -315,7 +324,7 @@ public void onReceive(Context context, Intent intent) { }else{ Globals.tmpplist=playList; } - sendBroadcast(new_intent19); + sendBroadcast(outgoingIntent); break; case 8: // Request seekBar times break; @@ -323,34 +332,31 @@ public void onReceive(Context context, Intent intent) { JNIHandler.seekTo(intent.getIntExtra(getResources().getString(R.string.msrv_seektime), 1)); break; case 10: // Request current folder - Intent new_intent10 = new Intent(); - new_intent10.setAction(getResources().getString(R.string.ta_rec)); - new_intent10.putExtra(getResources().getString(R.string.ta_cmd), 2); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 2); - new_intent10.putExtra(getResources().getString(R.string.ta_currpath), currFold); - sendBroadcast(new_intent10); + outgoingIntent.putExtra(getResources().getString(R.string.ta_currpath), currFold); + sendBroadcast(outgoingIntent); break; case 11: // Request player info - Intent new_intent11 = new Intent(); - new_intent11.setAction(getResources().getString(R.string.ta_rec)); - new_intent11.putExtra(getResources().getString(R.string.ta_cmd), 3); - new_intent11.putExtra(getResources().getString(R.string.ta_startt),JNIHandler.maxTime); - new_intent11.putExtra(getResources().getString(R.string.ta_shufmode), shuffleMode); - new_intent11.putExtra(getResources().getString(R.string.ta_loopmode), loopMode); - new_intent11.putExtra(getResources().getString(R.string.ta_songttl),currTitle); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 3); + outgoingIntent.putExtra(getResources().getString(R.string.ta_startt),JNIHandler.maxTime); + outgoingIntent.putExtra(getResources().getString(R.string.ta_shufmode), shuffleMode); + outgoingIntent.putExtra(getResources().getString(R.string.ta_loopmode), loopMode); + outgoingIntent.putExtra(getResources().getString(R.string.ta_songttl),currTitle); if(shuffleMode == 1) { - new_intent11.putExtra(getResources().getString(R.string.ta_filename),playList.get(shuffledIndices.get(currSongNumber))); + outgoingIntent.putExtra(getResources().getString(R.string.ta_filename),playList.get(shuffledIndices.get(currSongNumber))); }else{ - new_intent11.putExtra(getResources().getString(R.string.ta_filename),playList.get(currSongNumber)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_filename),playList.get(currSongNumber)); } - sendBroadcast(new_intent11); + sendBroadcast(outgoingIntent); break; case 12: // Request player info - Intent new_intent12 = new Intent(); - new_intent12.setAction(getResources().getString(R.string.ta_rec)); - new_intent12.putExtra(getResources().getString(R.string.ta_cmd), 4); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 4); if(shuffleMode == 1) { Globals.tmpplist=new ArrayList(); @@ -361,7 +367,7 @@ public void onReceive(Context context, Intent intent) { }else{ Globals.tmpplist=playList; } - sendBroadcast(new_intent12); + sendBroadcast(outgoingIntent); break; case 13: if(Globals.isPlaying==0) @@ -372,6 +378,7 @@ public void onReceive(Context context, Intent intent) { } break; case 14: // We want to write an output file + System.out.println("Hello there"); fullStop=true; shouldAdvance=false; Globals.hardStop=true; @@ -391,55 +398,58 @@ public void onReceive(Context context, Intent intent) { JNIHandler.setupOutputFile(output); JNIHandler.play(input); } - - new Thread(new Runnable(){ @Override public void run() { - while(!death&&((Globals.isPlaying==1))){ + while(!death&&((Globals.isPlaying==1))) + { if(JNIHandler.alternativeCheck==555555) - death=true; - try {Thread.sleep(10);} catch (InterruptedException e){}} - if(new File(input+".def.tcf").exists() || new File(input+".def.tzf").exists()) - { - String suffix; - if(new File(input+".def.tcf").exists() && new File(input+".def.tzf").exists()) - { - suffix = (Globals.compressCfg?".def.tzf":".def.tcf"); - }else if(new File(input+".def.tcf").exists()){ - suffix = ".def.tcf"; - }else{ - suffix = ".def.tzf"; - } - JNIHandler.shouldPlayNow=false; - JNIHandler.currTime=0; - while(Globals.isPlaying==0&&!death&&!JNIHandler.dataWritten) - { - try - { - Thread.sleep(25); - } catch (InterruptedException e) - { - e.printStackTrace(); - } - } - Intent new_intent = new Intent(); // silly, but should be done async. I think. - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17); - new_intent.putExtra(getResources().getString(R.string.msrv_infile),input+suffix); - new_intent.putExtra(getResources().getString(R.string.msrv_reset),true); - sendBroadcast(new_intent); - } - - while(((Globals.isPlaying==0))){ - try {Thread.sleep(25);} catch (InterruptedException e){}} - Intent new_intent14 = new Intent(); - new_intent14.setAction(getResources().getString(R.string.ta_rec)); - new_intent14.putExtra(getResources().getString(R.string.ta_cmd), 7); - sendBroadcast(new_intent14); - death=false; + { + death=true; + } + try {Thread.sleep(10);} catch (InterruptedException e){}} + if(new File(input+".def.tcf").exists() || new File(input+".def.tzf").exists()) + { + String suffix; + if(new File(input+".def.tcf").exists() && new File(input+".def.tzf").exists()) + { + suffix = (Globals.compressCfg?".def.tzf":".def.tcf"); + }else if(new File(input+".def.tcf").exists()){ + suffix = ".def.tcf"; + }else{ + suffix = ".def.tzf"; + } + JNIHandler.shouldPlayNow=false; + JNIHandler.currTime=0; + while(Globals.isPlaying==0&&!death&&!JNIHandler.dataWritten) + { + try + { + Thread.sleep(25); + } catch (InterruptedException e){ + e.printStackTrace(); + } + } + Intent outgoingIntent = new Intent(); // silly, but should be done async. I think. + outgoingIntent.setAction(getResources().getString(R.string.msrv_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.msrv_cmd), 17); + outgoingIntent.putExtra(getResources().getString(R.string.msrv_infile),input+suffix); + outgoingIntent.putExtra(getResources().getString(R.string.msrv_reset),true); + sendBroadcast(outgoingIntent); + } + while(((Globals.isPlaying==0))) + { + try {Thread.sleep(25);} catch (InterruptedException e){} + } + + System.out.println("Finished playing"); + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 8); + sendBroadcast(outgoingIntent); + death=false; } }).start(); //play(); @@ -462,22 +472,25 @@ public void run() JNIHandler.pause(); } new Thread(new Runnable(){ - @Override public void run() { - while(((Globals.isPlaying==1))){ - try {Thread.sleep(10);} catch (InterruptedException e){}} - while(((Globals.isPlaying==0))){ - try {Thread.sleep(25);} catch (InterruptedException e){}} - Intent new_intent14 = new Intent(); - new_intent14.setAction(getResources().getString(R.string.ta_rec)); - new_intent14.putExtra(getResources().getString(R.string.ta_cmd), 8); - sendBroadcast(new_intent14); - new_intent14.setAction(getResources().getString(R.string.ta_rec)); - new_intent14.putExtra(getResources().getString(R.string.ta_cmd), 5); - new_intent14.putExtra(getResources().getString(R.string.ta_pause), false); - sendBroadcast(new_intent14); + while(((Globals.isPlaying==1))) + { + try {Thread.sleep(10);} catch (InterruptedException e){} + } + while(((Globals.isPlaying==0))) + { + try {Thread.sleep(25);} catch (InterruptedException e){} + } + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 8); + sendBroadcast(outgoingIntent); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 5); + outgoingIntent.putExtra(getResources().getString(R.string.ta_pause), false); + sendBroadcast(outgoingIntent); } }).start(); break; @@ -549,10 +562,10 @@ public void run() JNIHandler.pause(); JNIHandler.waitUntilReady(50); } - Intent new_intent15 = new Intent(); - new_intent15.setAction(getResources().getString(R.string.ta_rec)); - new_intent15.putExtra(getResources().getString(R.string.ta_cmd), 8); - sendBroadcast(new_intent15); + Intent outgoingIntent15 = new Intent(); + outgoingIntent15.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent15.putExtra(getResources().getString(R.string.ta_cmd), 8); + sendBroadcast(outgoingIntent15); break; case 17: // load midi settings if(JNIHandler.paused) @@ -704,10 +717,10 @@ public void onCreate() { wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Timidity AE"); wl.setReferenceCounted(false); if(shouldDoWidget) - ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); + widgetIds = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if(mgr != null) { + if(mgr != null && Globals.phoneState) { mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } //foreground=false; @@ -745,82 +758,36 @@ public void play() if(!death) { - MediaMetadataRetriever mmr = new MediaMetadataRetriever(); - String tmpTitle; - Globals.currArt=null; - final int songIndex; - if(shuffleMode == 1) - { - songIndex = realSongNumber = shuffledIndices.get(currSongNumber); - }else{ - songIndex = realSongNumber = currSongNumber; - } - try{ - mmr.setDataSource(playList.get(songIndex)); - tmpTitle = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); - if(tmpTitle!=null) - { - if(TextUtils.isEmpty(tmpTitle)) - tmpTitle=playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/')+1); - }else{ - tmpTitle=playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/')+1); - } - - }catch (RuntimeException e) - { - tmpTitle=playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/')+1); - } - boolean goodart=false; - if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) // Please work - { - try{ - - byte[] art = mmr.getEmbeddedPicture(); - if(art!=null) + final int songIndex; + if(shuffleMode == 1) { - Globals.currArt=BitmapFactory.decodeByteArray(art, 0, art.length); - goodart=Globals.currArt!=null; + songIndex = realSongNumber = shuffledIndices.get(currSongNumber); + }else{ + songIndex = realSongNumber = currSongNumber; } - }catch (Exception e){} - } - if(!goodart) - { - String goodPath=playList.get(songIndex).substring(0,playList.get(songIndex).lastIndexOf('/')+1)+"folder.jpg"; - if(new File(goodPath).exists()) + MediaMetadataRetriever mmr = new MediaMetadataRetriever(); + + String tmpTitle; + String fileName = playList.get(songIndex); + try{ + mmr.setDataSource(fileName); + tmpTitle = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); + }catch (RuntimeException e) { - try{ - Globals.currArt=BitmapFactory.decodeFile(goodPath); - }catch (RuntimeException e){} + tmpTitle=fileName.substring(playList.get(songIndex).lastIndexOf('/')+1); + } + if(tmpTitle!=null) + { + if(TextUtils.isEmpty(tmpTitle)) + tmpTitle=fileName.substring(fileName.lastIndexOf('/')+1); }else{ - // Try albumart.jpg - goodPath=playList.get(songIndex).substring(0,playList.get(songIndex).lastIndexOf('/')+1)+"AlbumArt.jpg"; - if(new File(goodPath).exists()) - { - try{ - Globals.currArt=BitmapFactory.decodeFile(goodPath); - }catch (RuntimeException e) - { - // - } - } + tmpTitle=fileName.substring(fileName.lastIndexOf('/')+1); } - } - if(shouldDoWidget) - { - Intent intent = new Intent(this,TimidityAEWidgetProvider.class); - intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, - // since it seems the onUpdate() is only fired on that: - ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); - - //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); - sendBroadcast(intent); - } - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.ta_rec)); - new_intent.putExtra(getResources().getString(R.string.ta_cmd), 6); - sendBroadcast(new_intent); + setupMediaArtAndWidget(fileName, mmr); + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 6); + sendBroadcast(outgoingIntent); currTitle=tmpTitle; shouldAdvance=true; @@ -885,14 +852,14 @@ public void run() try {Thread.sleep(10);} catch (InterruptedException e){}} if(!death) { - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.ta_rec)); - new_intent.putExtra(getResources().getString(R.string.ta_cmd), 0); - new_intent.putExtra(getResources().getString(R.string.ta_startt),JNIHandler.maxTime); - new_intent.putExtra(getResources().getString(R.string.ta_songttl),currTitle); - new_intent.putExtra(getResources().getString(R.string.ta_filename),playList.get(songIndex)); - new_intent.putExtra("stupidNumber",songIndex); - sendBroadcast(new_intent); + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 0); + outgoingIntent.putExtra(getResources().getString(R.string.ta_startt),JNIHandler.maxTime); + outgoingIntent.putExtra(getResources().getString(R.string.ta_songttl),currTitle); + outgoingIntent.putExtra(getResources().getString(R.string.ta_filename),playList.get(songIndex)); + outgoingIntent.putExtra("stupidNumber",songIndex); + sendBroadcast(outgoingIntent); } if(new File(playList.get(songIndex)+".def.tcf").exists()||new File(playList.get(songIndex)+".def.tzf").exists()) { @@ -910,7 +877,7 @@ public void run() JNIHandler.currTime=0; while(Globals.isPlaying==0&&!death&&shouldAdvance&&!JNIHandler.dataWritten) { - try + try { Thread.sleep(25); } catch (InterruptedException e) @@ -918,12 +885,12 @@ public void run() e.printStackTrace(); } } - Intent new_intent = new Intent(); // silly, but should be done async. I think. - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17); - new_intent.putExtra(getResources().getString(R.string.msrv_infile),playList.get(songIndex)+suffix); - new_intent.putExtra(getResources().getString(R.string.msrv_reset),true); - sendBroadcast(new_intent); + Intent outgoingIntent = new Intent(); // silly, but should be done async. I think. + outgoingIntent.setAction(getResources().getString(R.string.msrv_rec)); + outgoingIntent.putExtra(getResources().getString(R.string.msrv_cmd), 17); + outgoingIntent.putExtra(getResources().getString(R.string.msrv_infile),playList.get(songIndex)+suffix); + outgoingIntent.putExtra(getResources().getString(R.string.msrv_reset),true); + sendBroadcast(outgoingIntent); } while(!death&&(((Globals.isPlaying==0||JNIHandler.alternativeCheck==333333)&&shouldAdvance))){ try {Thread.sleep(25);} catch (InterruptedException e){}} @@ -1019,11 +986,11 @@ public void stop() { death=true; - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.ta_rec)); - new_intent.putExtra(getResources().getString(R.string.ta_cmd), 5); - new_intent.putExtra(getResources().getString(R.string.ta_pause), false); - sendBroadcast(new_intent); + Intent stop_intent = new Intent(); + stop_intent.setAction(getResources().getString(R.string.ta_rec)); + stop_intent.putExtra(getResources().getString(R.string.ta_cmd), 5); + stop_intent.putExtra(getResources().getString(R.string.ta_pause), false); + sendBroadcast(stop_intent); Globals.shouldRestore=false; @@ -1031,7 +998,7 @@ public void stop() if(fullStop) { TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if(mgr != null) { + if(mgr != null && Globals.phoneState) { mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); } Globals.shouldRestore=false; @@ -1042,15 +1009,15 @@ public void stop() // Fix the widget if(shouldDoWidget) { - new_intent = new Intent(this, TimidityAEWidgetProvider.class); - new_intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids); - new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", true); - new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", ""); - new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", false); - new_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.death", true); - sendBroadcast(new_intent); + stop_intent = new Intent(this, TimidityAEWidgetProvider.class); + stop_intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + //stop_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + stop_intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,widgetIds); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", true); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", ""); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", false); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.death", true); + sendBroadcast(stop_intent); }else{ Globals.nukedWidgets=true; } @@ -1106,45 +1073,105 @@ public void updateNotification(String title, boolean paused) .setContentIntent(pendingIntent) .setContent(remoteViews); if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) + { mBuilder.setSmallIcon(R.drawable.ic_lol); - else + }else{ mBuilder.setSmallIcon(R.drawable.ic_launcher); - n=mBuilder.build(); - n.flags|=Notification.FLAG_ONLY_ALERT_ONCE|Notification.FLAG_ONGOING_EVENT; + } + mainNotification=mBuilder.build(); + mainNotification.flags|=Notification.FLAG_ONLY_ALERT_ONCE|Notification.FLAG_ONGOING_EVENT; if(!foreground) { - foreground=true; - startForeground(13901858, n); - if(!wl.isHeld()) - wl.acquire(); - - - TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if(mgr != null) { - mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); - } - }else{ + foreground=true; + // Dear Google, + // Your terrible Marshmallow power management had better not break this. + // If it does, I am using REQUEST_IGNORE_BATTERY_OPTIMIZATIONS. + // If you ban me for using it, there will be consequences. + startForeground(Globals.NOTIFICATION_ID, mainNotification); if(!wl.isHeld()) + { wl.acquire(); - NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - mNotificationManager.notify(13901858, n); + } + + TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); + if(mgr != null && Globals.phoneState) + { + mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); + } + }else{ + if(!wl.isHeld()) + { + wl.acquire(); + } + NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + mNotificationManager.notify(Globals.NOTIFICATION_ID, mainNotification); } if(shouldDoWidget) { - Intent intent = new Intent(this, TimidityAEWidgetProvider.class); - //Intent intent = new Intent("Ilikepotatoes"); - intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, - // since it seems the onUpdate() is only fired on that: - //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", paused); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", currTitle); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); - sendBroadcast(intent); - } + Intent intent = new Intent(this, TimidityAEWidgetProvider.class); + intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, + // since it seems the onUpdate() is only fired on that: + //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,widgetIds); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", paused); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", currTitle); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); + sendBroadcast(intent); } + } + @SuppressLint("NewApi") + public void setupMediaArtAndWidget(String fileName, MediaMetadataRetriever mmr) + { + Globals.currArt=null; + boolean goodart=false; + if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) // Please work + { + try{ + + byte[] art = mmr.getEmbeddedPicture(); + if(art!=null) + { + Globals.currArt=BitmapFactory.decodeByteArray(art, 0, art.length); + goodart=Globals.currArt!=null; + } + }catch (Exception e){} + } + if(!goodart) + { + String goodPath=fileName.substring(0,fileName.lastIndexOf('/')+1)+"folder.jpg"; + if(new File(goodPath).exists()) + { + try{ + Globals.currArt=BitmapFactory.decodeFile(goodPath); + }catch (RuntimeException e){} + }else{ + // Try albumart.jpg + goodPath=fileName.substring(0,fileName.lastIndexOf('/')+1)+"AlbumArt.jpg"; + if(new File(goodPath).exists()) + { + try{ + Globals.currArt=BitmapFactory.decodeFile(goodPath); + }catch (RuntimeException e){ + // + } + } + } + } + if(shouldDoWidget) + { + Intent intent = new Intent(this,TimidityAEWidgetProvider.class); + intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, + // since it seems the onUpdate() is only fired on that: + widgetIds = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); + + //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); + sendBroadcast(intent); + } } +} diff --git a/src/com/xperia64/timidityae/ObjectSerializer.java b/src/com/xperia64/timidityae/ObjectSerializer.java index 44a8f4e..cc29ccd 100755 --- a/src/com/xperia64/timidityae/ObjectSerializer.java +++ b/src/com/xperia64/timidityae/ObjectSerializer.java @@ -25,55 +25,54 @@ import java.io.ObjectOutputStream; import java.io.Serializable; +public class ObjectSerializer { + public static String serialize(Serializable obj) throws IOException { + if (obj == null) + return ""; + try { + ByteArrayOutputStream serialObj = new ByteArrayOutputStream(); + ObjectOutputStream objStream = new ObjectOutputStream(serialObj); + objStream.writeObject(obj); + objStream.close(); + return encodeBytes(serialObj.toByteArray()); + } catch (Exception e) { + throw (IOException) e; + } + } -public class ObjectSerializer { + public static Object deserialize(String str) throws IOException { + if (str == null || str.length() == 0) + return null; + try { + ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str)); + ObjectInputStream objStream = new ObjectInputStream(serialObj); + return objStream.readObject(); + } catch (Exception e) { + throw (IOException) e; + } + } + + public static String encodeBytes(byte[] bytes) { + StringBuffer strBuf = new StringBuffer(); + + for (int i = 0; i < bytes.length; i++) { + strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a'))); + strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a'))); + } + + return strBuf.toString(); + } - - public static String serialize(Serializable obj) throws IOException { - if (obj == null) return ""; - try { - ByteArrayOutputStream serialObj = new ByteArrayOutputStream(); - ObjectOutputStream objStream = new ObjectOutputStream(serialObj); - objStream.writeObject(obj); - objStream.close(); - return encodeBytes(serialObj.toByteArray()); - } catch (Exception e) { - throw (IOException) e; - } - } - - public static Object deserialize(String str) throws IOException { - if (str == null || str.length() == 0) return null; - try { - ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str)); - ObjectInputStream objStream = new ObjectInputStream(serialObj); - return objStream.readObject(); - } catch (Exception e) { - throw (IOException) e; - } - } - - public static String encodeBytes(byte[] bytes) { - StringBuffer strBuf = new StringBuffer(); - - for (int i = 0; i < bytes.length; i++) { - strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a'))); - strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a'))); - } - - return strBuf.toString(); - } - - public static byte[] decodeBytes(String str) { - byte[] bytes = new byte[str.length() / 2]; - for (int i = 0; i < str.length(); i+=2) { - char c = str.charAt(i); - bytes[i/2] = (byte) ((c - 'a') << 4); - c = str.charAt(i+1); - bytes[i/2] += (c - 'a'); - } - return bytes; - } + public static byte[] decodeBytes(String str) { + byte[] bytes = new byte[str.length() / 2]; + for (int i = 0; i < str.length(); i += 2) { + char c = str.charAt(i); + bytes[i / 2] = (byte) ((c - 'a') << 4); + c = str.charAt(i + 1); + bytes[i / 2] += (c - 'a'); + } + return bytes; + } } diff --git a/src/com/xperia64/timidityae/SettingsActivity.java b/src/com/xperia64/timidityae/SettingsActivity.java index c47ccde..4038784 100755 --- a/src/com/xperia64/timidityae/SettingsActivity.java +++ b/src/com/xperia64/timidityae/SettingsActivity.java @@ -15,9 +15,12 @@ import java.util.ArrayList; import java.util.List; -import com.xperia64.timidityae.FileBrowserDialog.FileBrowserDialogListener; -import com.xperia64.timidityae.SoundfontDialog.SoundfontDialogListener; +import com.xperia64.timidityae.util.Globals; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog; +import com.xperia64.timidityae.gui.dialogs.SoundfontDialog; +import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog.FileBrowserDialogListener; +import com.xperia64.timidityae.gui.dialogs.SoundfontDialog.SoundfontDialogListener; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; @@ -60,13 +63,13 @@ @SuppressLint("NewApi") public class SettingsActivity extends AppCompatActivity implements FileBrowserDialogListener, SoundfontDialogListener { - + public static SettingsActivity mInstance = null; private ArrayList tmpSounds; - //private int buffSize; - private boolean needRestart=false; - private boolean needUpdateSf=false; - + // private int buffSize; + private boolean needRestart = false; + private boolean needUpdateSf = false; + private ListPreference themePref; private CheckBoxPreference hiddenFold; private CheckBoxPreference showVids; @@ -74,652 +77,604 @@ public class SettingsActivity extends AppCompatActivity implements FileBrowserDi private Preference reinstallSoundfont; private Preference lolPref; private EditTextPreference manHomeFolder; - // -- needs restart below -- + // -- needs restart below -- private CheckBoxPreference manTcfg; private Preference sfPref; private CheckBoxPreference psilence; private CheckBoxPreference unload; private ListPreference resampMode; private ListPreference stereoMode; - //private ListPreference bitMode; + // private ListPreference bitMode; private ListPreference rates; private EditTextPreference bufferSize; private Preference dataFoldPreference; private EditTextPreference manDataFolder; - //private PreferenceScreen ds; + // private PreferenceScreen ds; private PreferenceScreen tplus; - // -- needs restart above -- + // -- needs restart above -- private CheckBoxPreference nativeMidi; private CheckBoxPreference keepWav; private SharedPreferences prefs; private TimidityPrefsFragment pf; private float abElevation; - - @SuppressLint("InlinedApi") - @Override - protected void onCreate(Bundle savedInstanceState) { - - mInstance = this; - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR&&Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) - { - this.setTheme(android.support.v7.appcompat.R.style.Theme_AppCompat); - }else{ - this.setTheme((Globals.theme==1)?android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar:android.support.v7.appcompat.R.style.Theme_AppCompat); - } - super.onCreate(savedInstanceState); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - // Display the fragment as the main content. - FragmentManager mFragmentManager = getSupportFragmentManager(); - FragmentTransaction mFragmentTransaction = mFragmentManager - .beginTransaction(); - pf = new TimidityPrefsFragment(); - mFragmentTransaction.replace(android.R.id.content, pf); - mFragmentTransaction.commit(); - abElevation = getSupportActionBar().getElevation(); - } - - public void setUpNestedScreen(PreferenceScreen preferenceScreen) { - final Dialog dialog = preferenceScreen.getDialog(); - - Toolbar bar; - - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) - { - LinearLayout root = (LinearLayout) dialog.findViewById(android.R.id.list).getParent(); - bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); - bar.setElevation(abElevation); - root.addView(bar,0); - } - else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - LinearLayout root = (LinearLayout) dialog.findViewById(android.R.id.list).getParent(); - bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); - root.addView(bar, 0); // insert at top - } else { - ViewGroup root = (ViewGroup) dialog.findViewById(android.R.id.content); - ListView content = (ListView) root.getChildAt(0); - - root.removeAllViews(); - - bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); - - int height; - TypedValue tv = new TypedValue(); - if (getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) { - height = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); - }else{ - height = bar.getHeight(); - } - - content.setPadding(0, height, 0, 0); - - root.addView(content); - root.addView(bar); - } - - bar.setTitle(preferenceScreen.getTitle()); - - bar.setNavigationOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dialog.dismiss(); - } - }); - } - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - onBackPressed(); - return true; - } - return false; - } - @Override - public void onBackPressed() { - // Store the soundfonts - try { - prefs.edit().putString("tplusSoundfonts", ObjectSerializer.serialize(tmpSounds)).commit(); - } catch (IOException e) { - e.printStackTrace(); - } - if(needUpdateSf) - { - Globals.writeCfg(SettingsActivity.this,Globals.dataFolder+"/timidity/timidity.cfg", tmpSounds); // TODO ?? - } - - Globals.reloadSettings(this, this.getAssets()); - if(needRestart) - { - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 18); - sendBroadcast(new_intent); - } - Intent returnIntent = new Intent(); - setResult(3, returnIntent); - this.finish(); - - - } - - + + @SuppressLint("InlinedApi") + @Override + protected void onCreate(Bundle savedInstanceState) { + + mInstance = this; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR && Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + this.setTheme(android.support.v7.appcompat.R.style.Theme_AppCompat); + } else { + this.setTheme((Globals.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); + } + super.onCreate(savedInstanceState); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // Display the fragment as the main content. + FragmentManager mFragmentManager = getSupportFragmentManager(); + FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction(); + pf = new TimidityPrefsFragment(); + mFragmentTransaction.replace(android.R.id.content, pf); + mFragmentTransaction.commit(); + abElevation = getSupportActionBar().getElevation(); + } + + public void setUpNestedScreen(PreferenceScreen preferenceScreen) { + final Dialog dialog = preferenceScreen.getDialog(); + + Toolbar bar; + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + LinearLayout root = (LinearLayout) dialog.findViewById(android.R.id.list).getParent(); + bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); + bar.setElevation(abElevation); + root.addView(bar, 0); + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + LinearLayout root = (LinearLayout) dialog.findViewById(android.R.id.list).getParent(); + bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); + root.addView(bar, 0); // insert at top + } else { + ViewGroup root = (ViewGroup) dialog.findViewById(android.R.id.content); + ListView content = (ListView) root.getChildAt(0); + + root.removeAllViews(); + + bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); + + int height; + TypedValue tv = new TypedValue(); + if (getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) { + height = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); + } else { + height = bar.getHeight(); + } + + content.setPadding(0, height, 0, 0); + + root.addView(content); + root.addView(bar); + } + + bar.setTitle(preferenceScreen.getTitle()); + + bar.setNavigationOnClickListener(new View.OnClickListener() { @Override - public void setItem(String path, int type) { - if(path!=null) - { - if(!TextUtils.isEmpty(path)) - { - switch(type) - { - case 3: - prefs.edit().putString("defaultPath", path).commit(); - manHomeFolder.setText(path); - Globals.defaultFolder=path; - ((BaseAdapter)pf.getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); - break; - case 4: - prefs.edit().putString("dataDir", path).commit(); - manDataFolder.setText(path); - ((BaseAdapter)pf.getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); - break; - case 5: - //soundfont fun - break; + public void onClick(View v) { + dialog.dismiss(); + } + }); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == android.R.id.home) { + onBackPressed(); + return true; + } + return false; + } + + @Override + public void onBackPressed() { + // Store the soundfonts + try { + prefs.edit().putString("tplusSoundfonts", ObjectSerializer.serialize(tmpSounds)).commit(); + } catch (IOException e) { + e.printStackTrace(); + } + if (needUpdateSf) { + Globals.writeCfg(SettingsActivity.this, Globals.dataFolder + "/timidity/timidity.cfg", tmpSounds); // TODO + // ?? + } + + Globals.reloadSettings(this, this.getAssets()); + if (needRestart) { + Intent new_intent = new Intent(); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 18); + sendBroadcast(new_intent); + } + Intent returnIntent = new Intent(); + setResult(3, returnIntent); + this.finish(); + + } + + @Override + public void setItem(String path, int type) { + if (path != null) { + if (!TextUtils.isEmpty(path)) { + switch (type) { + case 3: + prefs.edit().putString("defaultPath", path).commit(); + manHomeFolder.setText(path); + Globals.defaultFolder = path; + ((BaseAdapter) pf.getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); + break; + case 4: + prefs.edit().putString("dataDir", path).commit(); + manDataFolder.setText(path); + ((BaseAdapter) pf.getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); + break; + case 5: + // soundfont fun + break; + } + return; + } + } + Toast.makeText(this, getResources().getString(R.string.invalidfold), Toast.LENGTH_SHORT).show(); + } + + @SuppressLint("NewApi") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // Check which request we're responding to + if (requestCode == 42) { + if (resultCode == RESULT_OK) { + Uri treeUri = data.getData(); + getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + Globals.theFold = treeUri; + } else { + Globals.theFold = null; + } + + } + } + + @Override + public void write() { + } + + @Override + public void ignore() { + } + + @Override + public void writeSoundfonts(ArrayList l) { + if (l.size() == tmpSounds.size()) { + for (int i = 0; i < l.size(); i++) { + if (!l.get(i).equals(tmpSounds.get(i))) { + needRestart = true; + needUpdateSf = true; + break; + } + } + } else { + needRestart = true; + needUpdateSf = true; + } + if (needUpdateSf) { + tmpSounds.clear(); + for (String foo : l) { + tmpSounds.add(foo); + } + } + } + + public static class TimidityPrefsFragment extends PreferenceFragment { + + SettingsActivity s; + + @SuppressWarnings("unchecked") + @Override + public void onCreate(Bundle savedInstanceState) { + + super.onCreate(savedInstanceState); + s = (SettingsActivity) getActivity(); + // Load the preferences from an XML resource + addPreferencesFromResource(R.xml.settings); + s.prefs = PreferenceManager.getDefaultSharedPreferences(s.getBaseContext()); + s.themePref = (ListPreference) findPreference("fbTheme"); + s.hiddenFold = (CheckBoxPreference) findPreference("hiddenSwitch"); + s.showVids = (CheckBoxPreference) findPreference("videoSwitch"); + s.defaultFoldPreference = findPreference("defFold"); + s.reinstallSoundfont = findPreference("reSF"); + s.manHomeFolder = (EditTextPreference) findPreference("defaultPath"); + s.dataFoldPreference = findPreference("defData"); + s.manDataFolder = (EditTextPreference) findPreference("dataDir"); + s.manTcfg = (CheckBoxPreference) findPreference("manualConfig"); + s.sfPref = findPreference("sfConfig"); + s.resampMode = (ListPreference) findPreference("tplusResamp"); + s.stereoMode = (ListPreference) findPreference("sdlChanValue"); + // s.bitMode = (ListPreference) findPreference("tplusBits"); + s.rates = (ListPreference) findPreference("tplusRate"); + s.bufferSize = (EditTextPreference) findPreference("tplusBuff"); + // nativeMidi = (CheckBoxPreference) + // findPreference("nativeMidiSwitch"); + // ds = (PreferenceScreen) findPreference("dsKey"); + s.tplus = (PreferenceScreen) findPreference("tplusKey"); + s.nativeMidi = (CheckBoxPreference) findPreference("nativeMidiSwitch"); + s.keepWav = (CheckBoxPreference) findPreference("keepPartialWav"); + s.sfPref.setEnabled(!s.manTcfg.isChecked()); + s.lolPref = findPreference("lolWrite"); + s.psilence = (CheckBoxPreference) findPreference("tplusSilKey"); + s.unload = (CheckBoxPreference) findPreference("tplusUnload"); + + s.hiddenFold.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + Globals.showHiddenFiles = (Boolean) arg1; + return true; + } + + }); + s.showVids.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + Globals.showVideos = (Boolean) arg1; + return true; + } + + }); + s.nativeMidi.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + if (!Globals.onlyNative) + Globals.nativeMidi = (Boolean) arg1; + else + Globals.nativeMidi = true; + return true; + } + + }); + s.keepWav.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + Globals.keepWav = (Boolean) arg1; + return true; + } + + }); + s.defaultFoldPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + // dialog code here + + new FileBrowserDialog().create(3, null, s, s, s.getLayoutInflater(), true, s.prefs.getString("defaultPath", Environment.getExternalStorageDirectory().getAbsolutePath()), getResources().getString(R.string.fb_add)); + return true; + } + }); + if (s.lolPref != null) + s.lolPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @SuppressLint("NewApi") + public boolean onPreferenceClick(Preference preference) { + // dialog code here + List permissions = s.getContentResolver().getPersistedUriPermissions(); + if (!(permissions == null || permissions.isEmpty())) { + for (UriPermission p : permissions) { + s.getContentResolver().releasePersistableUriPermission(p.getUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + } } - return; + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); + startActivityForResult(intent, 42); + return true; } - } - Toast.makeText(this, getResources().getString(R.string.invalidfold), Toast.LENGTH_SHORT).show(); - } - @SuppressLint("NewApi") - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - // Check which request we're responding to - if(requestCode==42) - { - if (resultCode == RESULT_OK) { - Uri treeUri = data.getData(); - getContentResolver().takePersistableUriPermission(treeUri, - Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - Globals.theFold = treeUri; - }else{ - Globals.theFold = null; - } - - } + }); + s.reinstallSoundfont.setOnPreferenceClickListener(new OnPreferenceClickListener() { + + @Override + public boolean onPreferenceClick(Preference arg0) { + AlertDialog dialog = new AlertDialog.Builder(getActivity()).create(); + dialog.setTitle(getResources().getString(R.string.sett_resf_q)); + dialog.setMessage(getResources().getString(R.string.sett_resf_q_sum)); + dialog.setCancelable(true); + dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + AsyncTask task = new AsyncTask() { + + ProgressDialog pd; + + @Override + protected void onPreExecute() { + pd = new ProgressDialog(s); + pd.setTitle(getResources().getString(R.string.extract)); + pd.setMessage(getResources().getString(R.string.extract_sum)); + pd.setCancelable(false); + pd.setIndeterminate(true); + pd.show(); + } + + @Override + protected Integer doInBackground(Void... arg0) { + + return Globals.extract8Rock(s); + } + + @Override + protected void onPostExecute(Integer result) { + + if (pd != null) { + pd.dismiss(); + if (result != 777) { + Toast.makeText(s, getResources().getString(R.string.sett_resf_err), Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(s, getResources().getString(R.string.extract_def), Toast.LENGTH_LONG).show(); + } + } + } + + }; + task.execute((Void[]) null); + } + }); + dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + + } + }); + dialog.show(); + return true; + + } + + }); + s.dataFoldPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + // dialog code here + s.needRestart = true; + new FileBrowserDialog().create(4, null, s, s, s.getLayoutInflater(), true, s.prefs.getString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath()), getResources().getString(R.string.fb_add)); + return true; + } + }); + + try { + s.tmpSounds = (ArrayList) ObjectSerializer.deserialize(s.prefs.getString("tplusSoundfonts", ObjectSerializer.serialize(new ArrayList()))); + for (int i = 0; i < s.tmpSounds.size(); i++) { + if (s.tmpSounds.get(i) == null) + s.tmpSounds.remove(i); + } + } catch (IOException e) { + e.printStackTrace(); } - @Override - public void write() {} - @Override - public void ignore() {} + s.rates.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { - @Override - public void writeSoundfonts(ArrayList l) { - if(l.size() == tmpSounds.size()) - { - for(int i = 0; i(); + s.manTcfg.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + s.sfPref.setEnabled(!(Boolean) arg1); + return true; + } + + }); + + s.psilence.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + s.needRestart = true; + return true; + } + + }); + s.unload.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference arg0, Object arg1) { + s.needRestart = true; + return true; + } + + }); + s.sfPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { + + @Override + public boolean onPreferenceClick(Preference preference) { + new SoundfontDialog().create(s.tmpSounds, s, s, s.getLayoutInflater(), s.prefs.getString("defaultPath", Environment.getExternalStorageDirectory().getPath())); + return true; + } + + }); + s.resampMode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (!((String) s.resampMode.getValue()).equals((String) newValue)) { + s.needRestart = true; + } + return true; } - if(needUpdateSf) - { - tmpSounds.clear(); - for (String foo : l) { - tmpSounds.add(foo); + + }); + s.manDataFolder.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (!((String) s.manDataFolder.getText()).equals((String) newValue)) { + s.needRestart = true; } + return true; } + }); + // buffSize = Integer.parseInt(prefs.getString("tplusBuff", + // "192000")); + // System.out.println("Buffsize is: "+buffSize); + Globals.updateBuffers(Globals.updateRates()); + int[] values = Globals.updateRates(); + if (values != null) { + CharSequence[] hz = new CharSequence[values.length]; + CharSequence[] hzItems = new CharSequence[values.length]; + for (int i = 0; i < values.length; i++) { + hz[i] = Integer.toString(values[i]) + "Hz"; + hzItems[i] = Integer.toString(values[i]); + } + s.rates.setEntries(hz); + s.rates.setEntryValues(hzItems); + s.rates.setDefaultValue(Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))); + s.rates.setValue(s.prefs.getString("tplusRate", Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM)))); } - public static class TimidityPrefsFragment extends PreferenceFragment { - - SettingsActivity s; - @SuppressWarnings("unchecked") + s.bufferSize.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override - public void onCreate(Bundle savedInstanceState) { - - super.onCreate(savedInstanceState); - s = (SettingsActivity) getActivity(); - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.settings); - s.prefs = PreferenceManager - .getDefaultSharedPreferences(s.getBaseContext()); - s.themePref = (ListPreference) findPreference("fbTheme"); - s.hiddenFold = (CheckBoxPreference) findPreference("hiddenSwitch"); - s.showVids = (CheckBoxPreference) findPreference("videoSwitch"); - s.defaultFoldPreference = findPreference("defFold"); - s.reinstallSoundfont = findPreference("reSF"); - s.manHomeFolder = (EditTextPreference) findPreference("defaultPath"); - s.dataFoldPreference = findPreference("defData"); - s.manDataFolder = (EditTextPreference) findPreference("dataDir"); - s.manTcfg = (CheckBoxPreference) findPreference("manualConfig"); - s.sfPref = findPreference("sfConfig"); - s.resampMode = (ListPreference) findPreference("tplusResamp"); - s.stereoMode = (ListPreference) findPreference("sdlChanValue"); - //s.bitMode = (ListPreference) findPreference("tplusBits"); - s.rates = (ListPreference) findPreference("tplusRate"); - s.bufferSize = (EditTextPreference) findPreference("tplusBuff"); - //nativeMidi = (CheckBoxPreference) findPreference("nativeMidiSwitch"); - // ds = (PreferenceScreen) findPreference("dsKey"); - s.tplus = (PreferenceScreen) findPreference("tplusKey"); - s.nativeMidi = (CheckBoxPreference) findPreference("nativeMidiSwitch"); - s.keepWav = (CheckBoxPreference) findPreference("keepPartialWav"); - s.sfPref.setEnabled(!s.manTcfg.isChecked()); - s.lolPref = findPreference("lolWrite"); - s.psilence = (CheckBoxPreference) findPreference("tplusSilKey"); - s.unload = (CheckBoxPreference) findPreference("tplusUnload"); - - s.hiddenFold.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - Globals.showHiddenFiles=(Boolean)arg1; - return true; - } - - }); - s.showVids.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - Globals.showVideos=(Boolean)arg1; - return true; - } - - }); - s.nativeMidi.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - if(!Globals.onlyNative) - Globals.nativeMidi=(Boolean)arg1; - else - Globals.nativeMidi=true; - return true; - } - - }); - s.keepWav.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - Globals.keepWav=(Boolean)arg1; - return true; - } - - }); - s.defaultFoldPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) { - // dialog code here - - new FileBrowserDialog().create(3, null, s, s, s.getLayoutInflater(), true, s.prefs.getString("defaultPath", Environment.getExternalStorageDirectory().getAbsolutePath()), getResources().getString(R.string.fb_add)); - return true; - } - }); - if(s.lolPref!=null) - s.lolPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { - @SuppressLint("NewApi") - public boolean onPreferenceClick(Preference preference) { - // dialog code here - List permissions = s.getContentResolver().getPersistedUriPermissions(); - if(!(permissions==null||permissions.isEmpty())) - { - for(UriPermission p : permissions) - { - s.getContentResolver().releasePersistableUriPermission(p.getUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - } - } - Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); - startActivityForResult(intent, 42); - return true; - } - }); - s.reinstallSoundfont.setOnPreferenceClickListener(new OnPreferenceClickListener(){ - - @Override - public boolean onPreferenceClick(Preference arg0) { - AlertDialog dialog = new AlertDialog.Builder(getActivity()).create(); - dialog.setTitle(getResources().getString(R.string.sett_resf_q)); - dialog.setMessage(getResources().getString(R.string.sett_resf_q_sum)); - dialog.setCancelable(true); - dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - AsyncTask task = new AsyncTask() { - - ProgressDialog pd; - @Override - protected void onPreExecute() { - pd = new ProgressDialog(s); - pd.setTitle(getResources().getString(R.string.extract)); - pd.setMessage(getResources().getString(R.string.extract_sum)); - pd.setCancelable(false); - pd.setIndeterminate(true); - pd.show(); - } - - @Override - protected Integer doInBackground(Void... arg0) { - - return Globals.extract8Rock(s); - } - - @Override - protected void onPostExecute(Integer result) { - - if (pd!=null) { - pd.dismiss(); - if(result!=777) - { - Toast.makeText(s, getResources().getString(R.string.sett_resf_err), Toast.LENGTH_SHORT).show(); - }else{ - Toast.makeText(s,getResources().getString(R.string.extract_def),Toast.LENGTH_LONG).show(); - } - } - } - - }; - task.execute((Void[])null); - } - }); - dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - - } - }); - dialog.show(); - return true; - - - } - - }); - s.dataFoldPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - public boolean onPreferenceClick(Preference preference) { - // dialog code here - s.needRestart=true; - new FileBrowserDialog().create(4, null, s, s, s.getLayoutInflater(), true, s.prefs.getString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath()), getResources().getString(R.string.fb_add)); - return true; - } - }); - - try { - s.tmpSounds = (ArrayList) ObjectSerializer.deserialize(s.prefs.getString("tplusSoundfonts", ObjectSerializer.serialize(new ArrayList()))); - for(int i = 0; i(); - s.manTcfg.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - s.sfPref.setEnabled(!(Boolean)arg1); - return true; - } - - }); - - s.psilence.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - s.needRestart = true; - return true; - } - - }); - s.unload.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange(Preference arg0, - Object arg1) { - s.needRestart = true; - return true; - } - - }); - s.sfPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){ - - @Override - public boolean onPreferenceClick(Preference preference) { - new SoundfontDialog().create(s.tmpSounds, s, s, s.getLayoutInflater(), s.prefs.getString("defaultPath", - Environment.getExternalStorageDirectory().getPath())); - return true; - } - - }); - s.resampMode.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - - @Override - public boolean onPreferenceChange( - Preference preference, Object newValue) { - if(!((String)s.resampMode.getValue()).equals((String) newValue)) - { - s.needRestart=true; - } - return true; - } - - }); - s.manDataFolder.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){ - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - if(!((String)s.manDataFolder.getText()).equals((String) newValue)) - { - s.needRestart=true; - } - return true; - } - }); - // buffSize = Integer.parseInt(prefs.getString("tplusBuff", "192000")); - //System.out.println("Buffsize is: "+buffSize); - Globals.updateBuffers(Globals.updateRates()); - int[] values = Globals.updateRates(); - if(values!=null) - { - CharSequence[] hz = new CharSequence[values.length]; - CharSequence[] hzItems = new CharSequence[values.length]; - for(int i = 0; i= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){ - - - if (preference instanceof PreferenceScreen) { - s.setTheme((Globals.theme==1)?android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar:android.support.v7.appcompat.R.style.Theme_AppCompat); - s.setUpNestedScreen((PreferenceScreen) preference); - } - } - return false; - } - } - + } + return true; + } + } + return false; + } + return true; + } + + }); + s.stereoMode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if (!((String) s.stereoMode.getValue()).equals((String) newValue)) { + s.needRestart = true; + String stereo = (String) newValue; + String sixteen = "16"; // s.bitMode.getValue(); + boolean sb = (stereo != null) ? stereo.equals("2") : true; + boolean sxb = (sixteen != null) ? sixteen.equals("16") : true; + SparseIntArray mmm = Globals.validBuffers(Globals.validRates(sb, sxb), sb, sxb); + if (mmm != null) { + + int minBuff = mmm.get(Integer.parseInt(s.rates.getValue())); + + int buff = Integer.parseInt(s.bufferSize.getText()); + if (buff < minBuff) { + s.prefs.edit().putString("tplusBuff", Integer.toString(minBuff)).commit(); + s.bufferSize.setText(Integer.toString(minBuff)); + Toast.makeText(s, getResources().getString(R.string.invalidbuff), Toast.LENGTH_SHORT).show(); + ((BaseAdapter) s.tplus.getRootAdapter()).notifyDataSetChanged(); + ((BaseAdapter) s.tplus.getRootAdapter()).notifyDataSetInvalidated(); + } + } + + } + return true; + } + }); + /* + * s.bitMode.setOnPreferenceChangeListener(new + * OnPreferenceChangeListener(){ + * + * @Override public boolean onPreferenceChange( Preference + * preference, Object newValue) { + * if(!((String)s.bitMode.getValue()).equals((String) newValue)) { + * s.needRestart=true; String stereo = s.stereoMode.getValue(); + * String sixteen = (String) newValue; boolean + * sb=(stereo!=null)?stereo.equals("2"):true; boolean + * sxb=(sixteen!=null)?sixteen.equals("16"):true; SparseIntArray mmm + * = Globals.validBuffers(Globals.validRates(sb,sxb),sb,sxb); + * if(mmm!=null) { + * + * int minBuff = mmm.get(Integer.parseInt(s.rates.getValue())); + * + * int buff = Integer.parseInt(s.bufferSize.getText()); + * if(buff= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + + if (preference instanceof PreferenceScreen) { + s.setTheme((Globals.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); + s.setUpNestedScreen((PreferenceScreen) preference); + } + } + return false; + } + } + } diff --git a/src/com/xperia64/timidityae/TimidityActivity.java b/src/com/xperia64/timidityae/TimidityActivity.java index 8d5d7e4..e3a884f 100755 --- a/src/com/xperia64/timidityae/TimidityActivity.java +++ b/src/com/xperia64/timidityae/TimidityActivity.java @@ -12,7 +12,6 @@ package com.xperia64.timidityae; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -28,13 +27,13 @@ import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; -import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; +//import android.content.SharedPreferences; import android.content.UriPermission; import android.content.pm.PackageManager; import android.database.Cursor; @@ -42,6 +41,7 @@ import android.os.Build; import android.os.Bundle; import android.os.Environment; +//import android.preference.PreferenceManager; import android.provider.OpenableColumns; //import com.actionbarsherlock.app.SherlockFragment; @@ -52,911 +52,826 @@ import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v7.app.AppCompatActivity; -import android.text.InputFilter; -import android.text.Spanned; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; -import android.widget.EditText; import android.widget.Toast; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog; +import com.xperia64.timidityae.gui.fragments.FileBrowserFragment; +import com.xperia64.timidityae.gui.fragments.PlayerFragment; +import com.xperia64.timidityae.gui.fragments.PlaylistFragment; +import com.xperia64.timidityae.util.ConfigSaver; +import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.WavSaver; // Eclipse Stahp @SuppressLint("NewApi") public class TimidityActivity extends AppCompatActivity implements FileBrowserFragment.ActionFileBackListener, PlaylistFragment.ActionPlaylistBackListener, FileBrowserDialog.FileBrowserDialogListener { - //public static TimidityActivity staticthis; + // public static TimidityActivity staticthis; private MenuItem menuButton; private MenuItem menuButton2; - private int mode=0; + private int mode = 0; private FileBrowserFragment fileFrag; private PlayerFragment playFrag; private PlaylistFragment plistFrag; ViewPager viewPager; - boolean needFileBack=false; - boolean needPlaylistBack=false; - boolean fromPlaylist=false; - boolean needService=true; - String currSongName; - boolean needInit=false; - boolean fromIntent=false; - boolean deadlyDeath=false; - public boolean localfinished; + boolean needFileBack = false; + boolean needPlaylistBack = false; + boolean fromPlaylist = false; + boolean needService = true; + public String currSongName; + boolean needInit = false; + boolean fromIntent = false; + boolean deadlyDeath = false; + // public boolean localfinished; int oldTheme; - AlertDialog alerty; + // AlertDialog alerty; + + public interface SpecialAction { + public AlertDialog getAlertDialog(); + + public void setLocalFinished(boolean finished); + } + + SpecialAction special; private BroadcastReceiver activityReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - int cmd = intent.getIntExtra(getResources().getString(R.string.ta_cmd), -5); // -V - switch(cmd) - { - case -5: - break; - case 0: - currSongName=intent.getStringExtra(getResources().getString(R.string.ta_filename)); - if(viewPager.getCurrentItem()==1) - { - menuButton.setIcon(R.drawable.ic_menu_agenda); - menuButton.setTitle(getResources().getString(R.string.view)); - menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton.setEnabled((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton2.setIcon(R.drawable.ic_menu_info_details); - menuButton2.setTitle(getResources().getString(R.string.playback)); - menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton2.setEnabled((!JNIHandler.type)&&Globals.isPlaying==0); - } - playFrag.play(intent.getIntExtra(getResources().getString(R.string.ta_startt),0), intent.getStringExtra(getResources().getString(R.string.ta_songttl))); - if(plistFrag!=null) - { - plistFrag.highlightMe = intent.getIntExtra("stupidNumber", -1); - try{ - - int x = plistFrag.getListView().getFirstVisiblePosition(); - plistFrag.getPlaylists(plistFrag.mode?plistFrag.plistName:null); - plistFrag.getListView().setSelection(x); - }catch(Exception e) - { - - } - - } - - break; - case 1: - break; - case 2: - try{ - fileFrag.getDir(intent.getStringExtra(getResources().getString(R.string.ta_currpath))); - }catch(IllegalStateException e){ - - } - break; - case 3: - currSongName=intent.getStringExtra(getResources().getString(R.string.ta_filename)); - if(viewPager.getCurrentItem()==1) - { - menuButton.setIcon(R.drawable.ic_menu_agenda); - menuButton.setTitle(getResources().getString(R.string.view)); - menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton.setEnabled((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton2.setIcon(R.drawable.ic_menu_info_details); - menuButton2.setTitle(getResources().getString(R.string.playback)); - menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton2.setEnabled((!JNIHandler.type)&&Globals.isPlaying==0); - } - playFrag.play(intent.getIntExtra(getResources().getString(R.string.ta_startt),0), - intent.getStringExtra(getResources().getString(R.string.ta_songttl)), - intent.getIntExtra(getResources().getString(R.string.ta_shufmode), 0), - intent.getIntExtra(getResources().getString(R.string.ta_loopmode),1)); - break; - case 4: - plistFrag.currPlist=Globals.tmpplist; - Globals.tmpplist=null; - break; - case 5: // Notifiy pause/stop - if(!intent.getBooleanExtra(getResources().getString(R.string.ta_pause), false)&&Globals.hardStop) - { - Globals.hardStop=false; - if(viewPager.getCurrentItem()==1) - { - menuButton.setIcon(R.drawable.ic_menu_agenda); - menuButton.setTitle(getResources().getString(R.string.view)); - menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible(false); - menuButton.setEnabled(false); - menuButton2.setIcon(R.drawable.ic_menu_info_details); - menuButton2.setTitle(getResources().getString(R.string.playback)); - menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible(false); - menuButton2.setEnabled(false); - } - playFrag.setInterface(0); - TimidityActivity.this.runOnUiThread(new Runnable() { - public void run() { - if(playFrag.ddd!=null) - { - if(playFrag.ddd.isShowing()) - { - playFrag.ddd.dismiss(); - playFrag.ddd=null; - } - } - if(alerty!=null) - { - if(alerty.isShowing()) - { - alerty.dismiss(); - alerty=null; - } - } - } - }); - } - playFrag.pauseStop(intent.getBooleanExtra(getResources().getString(R.string.ta_pause), false), - intent.getBooleanExtra(getResources().getString(R.string.ta_pausea),false)); - break; - case 6: // notify art - //currSongName = intent.getStringExtra(getResources().getString(R.string.ta_filename)); - if(playFrag!=null) - playFrag.setArt(); - break; - case 7: - fileFrag.localfinished=true; - break; - case 8: - localfinished=true; - break; - - - } - } - }; - - /* @Override - protected void onPause() - { - - } - - */@Override - protected void onResume() - { - deadlyDeath=false; - super.onResume(); - } - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - handleIntentData(intent); - } - - final int PERMISSION_REQUEST=177; - final int NUM_PERMISSIONS = 3; - public void requestPermissions() - { - if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED - ||ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED - ||ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){ - - // Should we show an explanation? - if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) - ||ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) - ||ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { - - new AlertDialog.Builder(this).setTitle("Permissions") - .setMessage("Timidity AE needs to be able to:\n" - + "Read your storage to play music files\n\n" - + "Write to your storage to save configuration files\n\n" - + "Read phone state to auto-pause music during a phone call\n" - + "Timidity will not make phone calls or do anything besides checking if your device is receiving a call") - - .setPositiveButton("OK", new OnClickListener(){ + @Override + public void onReceive(Context context, Intent intent) { + int cmd = intent.getIntExtra(getResources().getString(R.string.ta_cmd), -5); // -V + switch (cmd) { + case -5: + break; + case 0: + currSongName = intent.getStringExtra(getResources().getString(R.string.ta_filename)); + if (viewPager.getCurrentItem() == 1) { + menuButton.setIcon(R.drawable.ic_menu_agenda); + menuButton.setTitle(getResources().getString(R.string.view)); + menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); + menuButton.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setIcon(R.drawable.ic_menu_info_details); + menuButton2.setTitle(getResources().getString(R.string.playback)); + menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); + menuButton2.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + } + playFrag.play(intent.getIntExtra(getResources().getString(R.string.ta_startt), 0), intent.getStringExtra(getResources().getString(R.string.ta_songttl))); + if (plistFrag != null) { + plistFrag.highlightMe = intent.getIntExtra("stupidNumber", -1); + try { + + int x = plistFrag.getListView().getFirstVisiblePosition(); + plistFrag.getPlaylists(plistFrag.mode ? plistFrag.plistName : null); + plistFrag.getListView().setSelection(x); + } catch (Exception e) { - @Override - public void onClick(DialogInterface dialog, - int which) { - actuallyRequestPermissions(); - + } + + } + + break; + case 1: + fileFrag.getDir(fileFrag.currPath); + break; + case 2: + try { + fileFrag.getDir(intent.getStringExtra(getResources().getString(R.string.ta_currpath))); + } catch (IllegalStateException e) { + + } + break; + case 3: + currSongName = intent.getStringExtra(getResources().getString(R.string.ta_filename)); + if (viewPager.getCurrentItem() == 1) { + menuButton.setIcon(R.drawable.ic_menu_agenda); + menuButton.setTitle(getResources().getString(R.string.view)); + menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); + menuButton.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setIcon(R.drawable.ic_menu_info_details); + menuButton2.setTitle(getResources().getString(R.string.playback)); + menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); + menuButton2.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + } + playFrag.play(intent.getIntExtra(getResources().getString(R.string.ta_startt), 0), intent.getStringExtra(getResources().getString(R.string.ta_songttl)), intent.getIntExtra(getResources().getString(R.string.ta_shufmode), 0), intent.getIntExtra(getResources().getString(R.string.ta_loopmode), 1)); + break; + case 4: + plistFrag.currPlist = Globals.tmpplist; + Globals.tmpplist = null; + break; + case 5: // Notifiy pause/stop + if (!intent.getBooleanExtra(getResources().getString(R.string.ta_pause), false) && Globals.hardStop) { + Globals.hardStop = false; + if (viewPager.getCurrentItem() == 1) { + menuButton.setIcon(R.drawable.ic_menu_agenda); + menuButton.setTitle(getResources().getString(R.string.view)); + menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); + menuButton.setVisible(false); + menuButton.setEnabled(false); + menuButton2.setIcon(R.drawable.ic_menu_info_details); + menuButton2.setTitle(getResources().getString(R.string.playback)); + menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); + menuButton2.setVisible(false); + menuButton2.setEnabled(false); + } + playFrag.setInterface(0); + TimidityActivity.this.runOnUiThread(new Runnable() { + public void run() { + if (playFrag.ddd != null) { + if (playFrag.ddd.isShowing()) { + playFrag.ddd.dismiss(); + playFrag.ddd = null; + } } - - }).setNegativeButton("Cancel", new OnClickListener(){ + if (special != null && special.getAlertDialog() != null) { + AlertDialog alerty = special.getAlertDialog(); + if (alerty.isShowing()) { + alerty.dismiss(); + alerty = null; + } + } + } + }); + } + playFrag.pauseStop(intent.getBooleanExtra(getResources().getString(R.string.ta_pause), false), intent.getBooleanExtra(getResources().getString(R.string.ta_pausea), false)); + break; + case 6: // notify art + // currSongName = + // intent.getStringExtra(getResources().getString(R.string.ta_filename)); + if (playFrag != null) + playFrag.setArt(); + break; + // case 7: + // fileFrag.localfinished=true; + // break; + case 8: + if (special != null) { + special.setLocalFinished(true); + } + break; + + } + } + }; + + /* + * @Override protected void onPause() { + * + * } + */ + @Override + protected void onResume() { + deadlyDeath = false; + super.onResume(); + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + handleIntentData(intent); + } + + final int PERMISSION_REQUEST = 177; + final int NUM_PERMISSIONS = 3; + + public void requestPermissions() { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED + /* + * ||ContextCompat.checkSelfPermission(this, + * Manifest.permission.READ_PHONE_STATE) != + * PackageManager.PERMISSION_GRANTED + */) { + + // Should we show an explanation? + if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) { + + new AlertDialog.Builder(this).setTitle("Permissions").setMessage("Timidity AE needs to be able to:\n" + "Read your storage to play music files\n\n" + "Write to your storage to save configuration files\n\n" + "Read phone state to auto-pause music during a phone call\n" + "Timidity will not make phone calls or do anything besides checking if your device is receiving a call") + + .setPositiveButton("OK", new OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + actuallyRequestPermissions(); + + } + + }).setNegativeButton("Cancel", new OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + new AlertDialog.Builder(TimidityActivity.this).setTitle("Error").setMessage("Timidity AE cannot proceed without these permissions").setPositiveButton("OK", new OnClickListener() { @Override - public void onClick(DialogInterface dialog, - int which) { - new AlertDialog.Builder(TimidityActivity.this).setTitle("Error") - .setMessage("Timidity AE cannot proceed without these permissions") - .setPositiveButton("OK", new OnClickListener(){ - - @Override - public void onClick(DialogInterface dialog, - int which) { - TimidityActivity.this.finish(); - } - - }).setCancelable(false).show(); - + public void onClick(DialogInterface dialog, int which) { + TimidityActivity.this.finish(); } - - }).setCancelable(false).show(); - - // Show an expanation to the user *asynchronously* -- don't block - // this thread waiting for the user's response! After the user - // sees the explanation, try again to request the permission. - - } else { - - // No explanation needed, we can request the permission. - actuallyRequestPermissions(); - - - // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an - // app-defined int constant. The callback method gets the - // result of the request. - } - }else{ - yetAnotherInit(); - } - } - - public void actuallyRequestPermissions() - { - ActivityCompat.requestPermissions(this, - new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.READ_EXTERNAL_STORAGE, - Manifest.permission.WRITE_EXTERNAL_STORAGE - }, - PERMISSION_REQUEST); - } - public void yetAnotherInit() - { - needInit=Globals.initialize(TimidityActivity.this); - } - - - @Override - public void onRequestPermissionsResult(int requestCode, - String permissions[], int[] grantResults) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults); - switch (requestCode) { - case PERMISSION_REQUEST: { - // If request is cancelled, the result arrays are empty. - boolean good = true; - if(permissions.length != NUM_PERMISSIONS || grantResults.length != NUM_PERMISSIONS) - { - good = false; - } - - for(int i = 0; i=Build.VERSION_CODES.M) - { - // Uggh. - requestPermissions(); - }else{ - yetAnotherInit(); - } - - }else{ - Log.i("Timidity","Resuming..."); - needService=!isMyServiceRunning(MusicService.class); - Fragment tmp = getSupportFragmentManager().getFragment(savedInstanceState,"playfrag"); - if(tmp!=null) - playFrag = (PlayerFragment) tmp; - - tmp = getSupportFragmentManager().getFragment(savedInstanceState,"plfrag"); - if(tmp!=null) - plistFrag = (PlaylistFragment) tmp; - tmp = getSupportFragmentManager().getFragment(savedInstanceState,"fffrag"); - if(tmp!=null) - fileFrag = (FileBrowserFragment) tmp; - if(!isMyServiceRunning(MusicService.class)) - { - Globals.reloadSettings(this, getAssets()); - initCallback2(); - if(viewPager!=null) - { - if(viewPager.getCurrentItem()==1) - { - viewPager.setCurrentItem(0); + this.setTheme((Globals.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); + super.onCreate(savedInstanceState); + if (savedInstanceState == null) { + Log.i("Timidity", "Initializing"); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + // Uggh. + requestPermissions(); + } else { + yetAnotherInit(); + } + + } else { + Log.i("Timidity", "Resuming..."); + needService = !isMyServiceRunning(MusicService.class); + Fragment tmp = getSupportFragmentManager().getFragment(savedInstanceState, "playfrag"); + if (tmp != null) + playFrag = (PlayerFragment) tmp; + + tmp = getSupportFragmentManager().getFragment(savedInstanceState, "plfrag"); + if (tmp != null) + plistFrag = (PlaylistFragment) tmp; + tmp = getSupportFragmentManager().getFragment(savedInstanceState, "fffrag"); + if (tmp != null) + fileFrag = (FileBrowserFragment) tmp; + if (!isMyServiceRunning(MusicService.class)) { + Globals.reloadSettings(this, getAssets()); + initCallback2(); + if (viewPager != null) { + if (viewPager.getCurrentItem() == 1) { + viewPager.setCurrentItem(0); + } } } + /* + * if(!savedInstanceState.getBoolean("justtheme", false)) { + * Globals.reloadSettings(this, getAssets()); } + */ + } - /*if(!savedInstanceState.getBoolean("justtheme", false)) - { - Globals.reloadSettings(this, getAssets()); - }*/ - - } - /*IntentFilter filter = new IntentFilter(); - filter.addAction("com.xperia64.timidityae20.ACTION_STOP"); - filter.addAction("com.xperia64.timidityae20.ACTION_PAUSE"); - filter.addAction("com.xperia64.timidityae20.ACTION_NEXT"); - filter.addAction("com.xperia64.timidityae20.ACTION_PREV");*/ - //registerReceiver(receiver, filter); - - setContentView(R.layout.main); - - - if (activityReceiver != null) { - //Create an intent filter to listen to the broadcast sent with the action "ACTION_STRING_ACTIVITY" - IntentFilter intentFilter = new IntentFilter(getResources().getString(R.string.ta_rec)); - //Map the intent filter to the receiver - registerReceiver(activityReceiver, intentFilter); - } - - //Start the service on launching the application - if(needService) - { - needService=false; - Globals.probablyFresh=0; - //System.out.println("Starting service"); - startService(new Intent(this, MusicService.class)); - } - - viewPager = (ViewPager) findViewById(R.id.vp_main); - viewPager.setAdapter(new TimidityFragmentPagerAdapter()); - viewPager.addOnPageChangeListener(new OnPageChangeListener() { - - @Override - public void onPageSelected(int index) { - mode=index; - switch(index) - { - case 0: - fromPlaylist=false; - if(getSupportActionBar()!=null) - { - if(menuButton!=null) - { - menuButton.setIcon(R.drawable.ic_menu_refresh); - menuButton.setVisible(true); - menuButton.setEnabled(true); - menuButton.setTitle(getResources().getString(R.string.refreshfld)); - menuButton.setTitleCondensed(getResources().getString(R.string.refreshcon)); - } - if(menuButton2!=null) - { - menuButton2.setIcon(R.drawable.ic_menu_home); - menuButton2.setTitle(getResources().getString(R.string.homefld)); - menuButton2.setTitleCondensed(getResources().getString(R.string.homecon)); - menuButton2.setVisible(true); - menuButton2.setEnabled(true); - } - getSupportActionBar().setDisplayHomeAsUpEnabled(needFileBack); - }else{ - getSupportActionBar().setDisplayHomeAsUpEnabled(false); - getSupportActionBar().setHomeButtonEnabled(false); - } - if(fileFrag!=null) - if(fileFrag.getListView()!=null) - fileFrag.getListView().setFastScrollEnabled(true); - break; - case 1: - if(getSupportActionBar()!=null) - { - if(menuButton!=null) - { - menuButton.setIcon(R.drawable.ic_menu_agenda); - menuButton.setTitle(getResources().getString(R.string.view)); - menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton.setEnabled((!JNIHandler.type)&&Globals.isPlaying==0); - } - if(menuButton2!=null) - { - menuButton2.setIcon(R.drawable.ic_menu_info_details); - menuButton2.setTitle(getResources().getString(R.string.playback)); - menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible((!JNIHandler.type)&&Globals.isPlaying==0); - menuButton2.setEnabled((!JNIHandler.type)&&Globals.isPlaying==0); - } - getSupportActionBar().setDisplayHomeAsUpEnabled(false); - getSupportActionBar().setHomeButtonEnabled(false); - } - break; - case 2: - fromPlaylist=true; - if(getSupportActionBar()!=null) - { - if(menuButton!=null) - { - menuButton.setIcon(R.drawable.ic_menu_refresh); - menuButton.setTitle(getResources().getString(R.string.refreshpls)); - menuButton.setTitleCondensed(getResources().getString(R.string.refreshcon)); - menuButton.setVisible(true); - menuButton.setEnabled(true); - } - if(menuButton2!=null) - { - menuButton2.setIcon(R.drawable.ic_menu_add); - menuButton2.setTitle(getResources().getString(R.string.add)); - menuButton2.setTitleCondensed(getResources().getString(R.string.addcon)); - if(plistFrag!=null) - { - menuButton2.setVisible((plistFrag.plistName!=null&&plistFrag.mode)?!plistFrag.plistName.equals("CURRENT"):true); - menuButton2.setEnabled((plistFrag.plistName!=null&&plistFrag.mode)?!plistFrag.plistName.equals("CURRENT"):true); - } - } - if(plistFrag!=null) - if(plistFrag.getListView()!=null) - plistFrag.getListView().setFastScrollEnabled(true); - if(needPlaylistBack) - { - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - } - }else{ - getSupportActionBar().setDisplayHomeAsUpEnabled(false); - getSupportActionBar().setHomeButtonEnabled(false); + /* + * IntentFilter filter = new IntentFilter(); + * filter.addAction("com.xperia64.timidityae20.ACTION_STOP"); + * filter.addAction("com.xperia64.timidityae20.ACTION_PAUSE"); + * filter.addAction("com.xperia64.timidityae20.ACTION_NEXT"); + * filter.addAction("com.xperia64.timidityae20.ACTION_PREV"); + */ + // registerReceiver(receiver, filter); + + setContentView(R.layout.main); + + if (activityReceiver != null) { + // Create an intent filter to listen to the broadcast sent with the + // action "ACTION_STRING_ACTIVITY" + IntentFilter intentFilter = new IntentFilter(getResources().getString(R.string.ta_rec)); + // Map the intent filter to the receiver + registerReceiver(activityReceiver, intentFilter); + } + + // Start the service on launching the application + if (needService) { + needService = false; + Globals.probablyFresh = 0; + // System.out.println("Starting service"); + startService(new Intent(this, MusicService.class)); + } + + viewPager = (ViewPager) findViewById(R.id.vp_main); + viewPager.setAdapter(new TimidityFragmentPagerAdapter()); + viewPager.addOnPageChangeListener(new OnPageChangeListener() { + + @Override + public void onPageSelected(int index) { + mode = index; + switch (index) { + case 0: + fromPlaylist = false; + if (getSupportActionBar() != null) { + if (menuButton != null) { + menuButton.setIcon(R.drawable.ic_menu_refresh); + menuButton.setVisible(true); + menuButton.setEnabled(true); + menuButton.setTitle(getResources().getString(R.string.refreshfld)); + menuButton.setTitleCondensed(getResources().getString(R.string.refreshcon)); + } + if (menuButton2 != null) { + menuButton2.setIcon(R.drawable.ic_menu_home); + menuButton2.setTitle(getResources().getString(R.string.homefld)); + menuButton2.setTitleCondensed(getResources().getString(R.string.homecon)); + menuButton2.setVisible(true); + menuButton2.setEnabled(true); + } + getSupportActionBar().setDisplayHomeAsUpEnabled(needFileBack); + } else { + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setHomeButtonEnabled(false); + } + if (fileFrag != null) + if (fileFrag.getListView() != null) + fileFrag.getListView().setFastScrollEnabled(true); + break; + case 1: + if (getSupportActionBar() != null) { + if (menuButton != null) { + menuButton.setIcon(R.drawable.ic_menu_agenda); + menuButton.setTitle(getResources().getString(R.string.view)); + menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); + menuButton.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + } + if (menuButton2 != null) { + menuButton2.setIcon(R.drawable.ic_menu_info_details); + menuButton2.setTitle(getResources().getString(R.string.playback)); + menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); + menuButton2.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + } + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setHomeButtonEnabled(false); + } + break; + case 2: + fromPlaylist = true; + if (getSupportActionBar() != null) { + if (menuButton != null) { + menuButton.setIcon(R.drawable.ic_menu_refresh); + menuButton.setTitle(getResources().getString(R.string.refreshpls)); + menuButton.setTitleCondensed(getResources().getString(R.string.refreshcon)); + menuButton.setVisible(true); + menuButton.setEnabled(true); + } + if (menuButton2 != null) { + menuButton2.setIcon(R.drawable.ic_menu_add); + menuButton2.setTitle(getResources().getString(R.string.add)); + menuButton2.setTitleCondensed(getResources().getString(R.string.addcon)); + if (plistFrag != null) { + menuButton2.setVisible((plistFrag.plistName != null && plistFrag.mode) ? !plistFrag.plistName.equals("CURRENT") : true); + menuButton2.setEnabled((plistFrag.plistName != null && plistFrag.mode) ? !plistFrag.plistName.equals("CURRENT") : true); + } + } + if (plistFrag != null) + if (plistFrag.getListView() != null) + plistFrag.getListView().setFastScrollEnabled(true); + if (needPlaylistBack) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + } else { + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setHomeButtonEnabled(false); + } + break; } - break; - } - - } - @Override - public void onPageScrolled(int arg0, float arg1, int arg2) { + } - } + @Override + public void onPageScrolled(int arg0, float arg1, int arg2) { + + } - @Override - public void onPageScrollStateChanged(int arg0) { + @Override + public void onPageScrollStateChanged(int arg0) { - } - }); + } + }); } + @SuppressLint("NewApi") - public void initCallback() - { - if(Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.LOLLIPOP) - { + public void initCallback() { + if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { List permissions = getContentResolver().getPersistedUriPermissions(); - int trueExt=0; - for(File f : getExternalFilesDirs(null)) - { - if(f!=null) + int trueExt = 0; + for (File f : getExternalFilesDirs(null)) { + if (f != null) trueExt++; } - if((permissions==null||permissions.isEmpty())&&Globals.shouldLolNag&&trueExt>1) - { - new AlertDialog.Builder(this).setTitle("SD Card Access").setCancelable(false) - .setMessage("Would you like to give Timidity AE write access to your external sd card? This is recommended if you're converting files or would like to place Timidity AE's data directory there. Problems may occur if a directory other than the root of your SD card is selected.") - .setPositiveButton("Yes", new OnClickListener(){ + if ((permissions == null || permissions.isEmpty()) && Globals.shouldLolNag && trueExt > 1) { + new AlertDialog.Builder(this).setTitle("SD Card Access").setCancelable(false).setMessage("Would you like to give Timidity AE write access to your external sd card? This is recommended if you're converting files or would like to place Timidity AE's data directory there. Problems may occur if a directory other than the root of your SD card is selected.").setPositiveButton("Yes", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); - startActivityForResult(intent, 42); + startActivityForResult(intent, 42); } - - }) - .setNegativeButton("No, do not ask again", new OnClickListener(){ + + }).setNegativeButton("No, do not ask again", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - Globals.prefs.edit().putBoolean("shouldLolNag", Globals.shouldLolNag=false).commit(); + Globals.prefs.edit().putBoolean("shouldLolNag", Globals.shouldLolNag = false).commit(); initCallback2(); } - - }).setNeutralButton("No", new OnClickListener(){ + + }).setNeutralButton("No", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { initCallback2(); } }).show(); - }else{ - for(UriPermission permission : permissions) - { - if(permission.isReadPermission()&&permission.isWritePermission()) - { - Globals.theFold=permission.getUri(); + } else { + for (UriPermission permission : permissions) { + if (permission.isReadPermission() && permission.isWritePermission()) { + Globals.theFold = permission.getUri(); } } - + initCallback2(); } - }else{ + } else { initCallback2(); } } - public void initCallback2() - { - int x = JNIHandler.init(Globals.dataFolder+"timidity/","timidity.cfg", Globals.mono, Globals.defSamp, Globals.sixteen, Globals.buff, Globals.aRate, Globals.preserveSilence, false, Globals.freeInsts); - if(x!=0&&x!=-99) - { - Globals.nativeMidi=true; + + public void initCallback2() { + int x = JNIHandler.init(Globals.dataFolder + "timidity/", "timidity.cfg", Globals.mono, Globals.defSamp, Globals.sixteen, Globals.buff, Globals.aRate, Globals.preserveSilence, false, Globals.freeInsts); + if (x != 0 && x != -99) { + Globals.nativeMidi = true; Toast.makeText(this, String.format(getResources().getString(R.string.tcfg_error), x), Toast.LENGTH_LONG).show(); } handleIntentData(getIntent()); } - public void handleIntentData(Intent in) - { - if(in.getData()!=null) - { + + public void handleIntentData(Intent in) { + if (in.getData() != null) { String data; - if((data=in.getData().getPath())!=null&&in.getData().getScheme()!=null) - { - if(in.getData().getScheme().equals("file")) - { - if(new File(data).exists()) - { - File f = new File(data.substring(0,data.lastIndexOf('/')+1)); - if(f.exists()) - { - if(f.isDirectory()) - { + if ((data = in.getData().getPath()) != null && in.getData().getScheme() != null) { + if (in.getData().getScheme().equals("file")) { + if (new File(data).exists()) { + File f = new File(data.substring(0, data.lastIndexOf('/') + 1)); + if (f.exists()) { + if (f.isDirectory()) { ArrayList files = new ArrayList(); - int position=-1; - int goodCounter=0; - for(File ff: f.listFiles()) - { - if(ff!=null&&ff.isFile()) - { + int position = -1; + int goodCounter = 0; + for (File ff : f.listFiles()) { + if (ff != null && ff.isFile()) { int dotPosition = ff.getName().lastIndexOf('.'); - String extension=""; - if (dotPosition != -1) - { + String extension = ""; + if (dotPosition != -1) { extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US); - if(extension!=null) - { - if((Globals.showVideos?Globals.musicVideoFiles:Globals.musicFiles).contains("*"+extension+"*")) - { - + if (extension != null) { + if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + files.add(ff.getPath()); - if(ff.getPath().equals(data)) - position=goodCounter; + if (ff.getPath().equals(data)) + position = goodCounter; goodCounter++; } } } } } - if(position==-1) + if (position == -1) Toast.makeText(this, getResources().getString(R.string.intErr1), Toast.LENGTH_SHORT).show(); - else{ + else { stop(); - selectedSong(files,position,true,false,false); - fileFrag.getDir(data.substring(0,data.lastIndexOf('/')+1)); + selectedSong(files, position, true, false, false); + fileFrag.getDir(data.substring(0, data.lastIndexOf('/') + 1)); } } } - }else{ - Toast.makeText(this, getResources().getString(R.string.srv_fnf),Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(this, getResources().getString(R.string.srv_fnf), Toast.LENGTH_SHORT).show(); } - }else if(in.getData().getScheme().equals("http")||in.getData().getScheme().equals("https")){ - if(!data.endsWith("/")) - { - if(!Globals.getExternalCacheDir(this).exists()) - { + } else if (in.getData().getScheme().equals("http") || in.getData().getScheme().equals("https")) { + if (!data.endsWith("/")) { + if (!Globals.getExternalCacheDir(this).exists()) { Globals.getExternalCacheDir(this).mkdirs(); } final Globals.DownloadTask downloadTask = new Globals.DownloadTask(this); downloadTask.execute(in.getData().toString(), in.getData().getLastPathSegment()); in.setData(null); - }else{Toast.makeText(this, "This is a directory, not a file",Toast.LENGTH_SHORT).show();} - }else if(in.getData().getScheme().equals("content")&&(data.contains("downloads"))) - { + } else { + Toast.makeText(this, "This is a directory, not a file", Toast.LENGTH_SHORT).show(); + } + } else if (in.getData().getScheme().equals("content") && (data.contains("downloads"))) { String filename = null; Cursor cursor = null; try { - cursor = this.getContentResolver().query(in.getData(), new String[] { - OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}, null, null, null ); - if (cursor != null && cursor.moveToFirst()) { - filename = cursor.getString(0); - } + cursor = this.getContentResolver().query(in.getData(), new String[] { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null, null, null); + if (cursor != null && cursor.moveToFirst()) { + filename = cursor.getString(0); + } } finally { - if (cursor != null) - cursor.close(); + if (cursor != null) + cursor.close(); } - try - { + try { InputStream input = getContentResolver().openInputStream(in.getData()); - if(new File(Globals.getExternalCacheDir(this).getAbsolutePath()+'/'+filename).exists()) - { - new File(Globals.getExternalCacheDir(this).getAbsolutePath()+'/'+filename).delete(); + if (new File(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename).exists()) { + new File(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename).delete(); + } + OutputStream output = new FileOutputStream(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename); + + byte[] buffer = new byte[4096]; + int count; + while ((count = input.read(buffer)) != -1) { + output.write(buffer, 0, count); } - OutputStream output = new FileOutputStream(Globals.getExternalCacheDir(this).getAbsolutePath()+'/'+filename); - - byte[] buffer = new byte[4096]; - int count; - while ((count = input.read(buffer)) != -1) { - output.write(buffer, 0, count); - } - output.close(); - } catch (IOException e) - { + output.close(); + } catch (IOException e) { e.printStackTrace(); return; } - - - File f = new File(Globals.getExternalCacheDir(this).getAbsolutePath()+'/'); - if(f.exists()) - { - if(f.isDirectory()) - { + + File f = new File(Globals.getExternalCacheDir(this).getAbsolutePath() + '/'); + if (f.exists()) { + if (f.isDirectory()) { ArrayList files = new ArrayList(); - int position=-1; - int goodCounter=0; - for(File ff: f.listFiles()) - { - if(ff!=null&&ff.isFile()) - { + int position = -1; + int goodCounter = 0; + for (File ff : f.listFiles()) { + if (ff != null && ff.isFile()) { int dotPosition = ff.getName().lastIndexOf('.'); - String extension=""; - if (dotPosition != -1) - { + String extension = ""; + if (dotPosition != -1) { extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US); - if(extension!=null) - { - if((Globals.showVideos?Globals.musicVideoFiles:Globals.musicFiles).contains("*"+extension+"*")) - { - + if (extension != null) { + if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + files.add(ff.getPath()); - if(ff.getPath().equals(Globals.getExternalCacheDir(this).getAbsolutePath()+'/'+filename)) - position=goodCounter; + if (ff.getPath().equals(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename)) + position = goodCounter; goodCounter++; } } } } } - if(position==-1) + if (position == -1) Toast.makeText(this, getResources().getString(R.string.intErr1), Toast.LENGTH_SHORT).show(); - else{ + else { stop(); - selectedSong(files,position,true,false,false); - fileFrag.getDir(Globals.getExternalCacheDir(this).getAbsolutePath()); + selectedSong(files, position, true, false, false); + fileFrag.getDir(Globals.getExternalCacheDir(this).getAbsolutePath()); } } } - - }else{ + + } else { System.out.println(in.getDataString()); - Toast.makeText(this, getResources().getString(R.string.intErr2)+" ("+in.getData().getScheme()+")",Toast.LENGTH_SHORT).show(); + Toast.makeText(this, getResources().getString(R.string.intErr2) + " (" + in.getData().getScheme() + ")", Toast.LENGTH_SHORT).show(); } } } } + @SuppressLint("NewApi") - public void downloadFinished(String data, String theFilename) - { + public void downloadFinished(String data, String theFilename) { ArrayList files = new ArrayList(); - String name = Globals.getExternalCacheDir(this).getAbsolutePath()+'/'+theFilename; + String name = Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + theFilename; int dotPosition = name.lastIndexOf('.'); - String extension=""; - if (dotPosition != -1) - { + String extension = ""; + if (dotPosition != -1) { extension = (name.substring(dotPosition)).toLowerCase(Locale.US); - if(extension!=null) - { - if((Globals.showVideos?Globals.musicVideoFiles:Globals.musicFiles).contains("*"+extension+"*")) - { - + if (extension != null) { + if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + files.add(name); stop(); - selectedSong(files,0,true,false,false); - fileFrag.getDir(name.substring(0,name.lastIndexOf('/')+1)); + selectedSong(files, 0, true, false, false); + fileFrag.getDir(name.substring(0, name.lastIndexOf('/') + 1)); } } } } + @Override - public void onDestroy() - { - try{ - unregisterReceiver(activityReceiver); - }catch(IllegalArgumentException e) - { - + public void onDestroy() { + try { + unregisterReceiver(activityReceiver); + } catch (IllegalArgumentException e) { + } super.onDestroy(); - //if(deadlyDeath) - //System.exit(0); + // if(deadlyDeath) + // System.exit(0); } + private boolean isMyServiceRunning(Class serviceClass) { - ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); - for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { - if (serviceClass.getName().equals(service.service.getClassName())) { - return true; - } - } - return false; + ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (serviceClass.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; } + @Override protected void onSaveInstanceState(Bundle icicle) { - super.onSaveInstanceState(icicle); - icicle.putBoolean("justtheme", true); - if(playFrag!=null) - getSupportFragmentManager().putFragment(icicle,"playfrag",playFrag); - if(plistFrag!=null) - getSupportFragmentManager().putFragment(icicle,"plfrag",plistFrag); - if(fileFrag!=null) - getSupportFragmentManager().putFragment(icicle,"fffrag",fileFrag); - } + super.onSaveInstanceState(icicle); + icicle.putBoolean("justtheme", true); + if (playFrag != null) + getSupportFragmentManager().putFragment(icicle, "playfrag", playFrag); + if (plistFrag != null) + getSupportFragmentManager().putFragment(icicle, "plfrag", plistFrag); + if (fileFrag != null) + getSupportFragmentManager().putFragment(icicle, "fffrag", fileFrag); + } + @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.main_menu, menu); - menuButton=menu.findItem(R.id.menuBtn1); - menuButton2=menu.findItem(R.id.menuBtn2); - return true; - } + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.main_menu, menu); + menuButton = menu.findItem(R.id.menuBtn1); + menuButton2 = menu.findItem(R.id.menuBtn2); + return true; + } + @Override - public boolean onOptionsItemSelected(MenuItem item) - { - if(item.getItemId()==R.id.menuBtn1) - { - switch(mode) - { + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.menuBtn1) { + switch (mode) { case 0: int x = fileFrag.getListView().getFirstVisiblePosition(); fileFrag.getDir(fileFrag.currPath); fileFrag.setSelection(x); break; case 1: - if(playFrag!=null&&!JNIHandler.type) - { + if (playFrag != null && !JNIHandler.type) { playFrag.incrementInterface(); - }/*else{ - Toast.makeText(this, "Non midi file", Toast.LENGTH_SHORT).show(); - }*/ + } /* + * else{ Toast.makeText(this, "Non midi file", + * Toast.LENGTH_SHORT).show(); } + */ break; case 2: int y = plistFrag.getListView().getFirstVisiblePosition(); - plistFrag.getPlaylists(plistFrag.mode?plistFrag.plistName:null); + plistFrag.getPlaylists(plistFrag.mode ? plistFrag.plistName : null); plistFrag.getListView().setSelection(y); break; } - }else if(item.getItemId()==R.id.menuBtn2){ - switch(mode) - { + } else if (item.getItemId() == R.id.menuBtn2) { + switch (mode) { case 0: - if(fileFrag!=null) + if (fileFrag != null) fileFrag.getDir(Globals.defaultFolder); break; case 1: - if(playFrag!=null) - { - if((!JNIHandler.type)&&Globals.isPlaying==0) - { - playFrag.showMidiDialog(); - }/*else{ - Toast.makeText(this, "Non midi file", Toast.LENGTH_SHORT).show(); - }*/ + if (playFrag != null) { + if ((!JNIHandler.type) && Globals.isPlaying == 0) { + playFrag.showMidiDialog(); + } /* + * else{ Toast.makeText(this, "Non midi file", + * Toast.LENGTH_SHORT).show(); } + */ } break; case 2: plistFrag.add(); break; - + } - }else if(item.getItemId()==android.R.id.home) - { - onBackPressed(); - }else if(item.getItemId()==R.id.quit) - { - deadlyDeath=true; + } else if (item.getItemId() == android.R.id.home) { + onBackPressed(); + } else if (item.getItemId() == R.id.quit) { + deadlyDeath = true; Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); + sendBroadcast(new_intent); stopService(new Intent(this, MusicService.class)); - unregisterReceiver(activityReceiver); - android.os.Process.killProcess(android.os.Process.myPid()); // Probably the same - //System.exit(0); - }else if(item.getItemId()==R.id.asettings) - { + unregisterReceiver(activityReceiver); + android.os.Process.killProcess(android.os.Process.myPid()); // Probably + // the + // same + // System.exit(0); + } else if (item.getItemId() == R.id.asettings) { Intent mainact = new Intent(this, SettingsActivity.class); - mainact.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); - startActivityForResult( mainact, 1 ); - }else if(item.getItemId()==R.id.ahelp) - { - new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.helpt)) - .setMessage(getResources().getString(R.string.helper)).setNegativeButton("OK", new OnClickListener(){ + mainact.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); + startActivityForResult(mainact, 1); + } else if (item.getItemId() == R.id.ahelp) { + new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.helpt)).setMessage(getResources().getString(R.string.helper)).setNegativeButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - + } - + }).show(); } return super.onOptionsItemSelected(item); } + @Override - public void onBackPressed() - { - - switch(mode) - { + public void onBackPressed() { + + switch (mode) { case 0: - if(fileFrag!=null) - if(fileFrag.currPath!=null) - if(!fileFrag.currPath.matches("[/]+")) - { + if (fileFrag != null) + if (fileFrag.currPath != null) + if (!fileFrag.currPath.matches("[/]+")) { fileFrag.getDir(new File(fileFrag.currPath).getParent().toString()); - }else - { - if(Globals.useDefaultBack) - { + } else { + if (Globals.useDefaultBack) { super.onBackPressed(); return; } @@ -964,20 +879,17 @@ public void onBackPressed() } break; case 1: - if(Globals.useDefaultBack) - { + if (Globals.useDefaultBack) { super.onBackPressed(); return; } - viewPager.setCurrentItem((fromPlaylist)?2:0); + viewPager.setCurrentItem((fromPlaylist) ? 2 : 0); break; case 2: - if(plistFrag.mode) + if (plistFrag.mode) plistFrag.getPlaylists(null); - else - { - if(Globals.useDefaultBack) - { + else { + if (Globals.useDefaultBack) { super.onBackPressed(); return; } @@ -986,53 +898,50 @@ public void onBackPressed() break; } } - public void selectedSong(ArrayList files, int songNumber, boolean begin, boolean loc, boolean dontloadplist) - { - fromPlaylist=loc; - if(viewPager!=null) - { + + public void selectedSong(ArrayList files, int songNumber, boolean begin, boolean loc, boolean dontloadplist) { + fromPlaylist = loc; + if (viewPager != null) { viewPager.setCurrentItem(1); } - Globals.plist=files; - if(plistFrag!=null&&!dontloadplist) - { - plistFrag.currPlist=files; + Globals.plist = files; + if (plistFrag != null && !dontloadplist) { + plistFrag.currPlist = files; } - //plistFrag.getListView().setItemChecked(songNumber, true); + // plistFrag.getListView().setItemChecked(songNumber, true); Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); + sendBroadcast(new_intent); new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 0); - - if(fileFrag!=null) - { - new_intent.putExtra(getResources().getString(R.string.msrv_currfold),fileFrag.currPath); - } - new_intent.putExtra(getResources().getString(R.string.msrv_songnum), songNumber); - new_intent.putExtra(getResources().getString(R.string.msrv_begin), begin); - new_intent.putExtra(getResources().getString(R.string.msrv_dlplist), dontloadplist); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 0); + + if (fileFrag != null) { + new_intent.putExtra(getResources().getString(R.string.msrv_currfold), fileFrag.currPath); + } + new_intent.putExtra(getResources().getString(R.string.msrv_songnum), songNumber); + new_intent.putExtra(getResources().getString(R.string.msrv_begin), begin); + new_intent.putExtra(getResources().getString(R.string.msrv_dlplist), dontloadplist); + sendBroadcast(new_intent); } + public class TimidityFragmentPagerAdapter extends FragmentPagerAdapter { - final String[] pages = {"Files", "Player", "Playlists"}; - public TimidityFragmentPagerAdapter() - { + final String[] pages = { "Files", "Player", "Playlists" }; + + public TimidityFragmentPagerAdapter() { super(getSupportFragmentManager()); } + @Override - public int getCount() - { + public int getCount() { return pages.length; } + @Override - public Fragment getItem(int position) - { - switch(position) - { + public Fragment getItem(int position) { + switch (position) { case 0: fileFrag = FileBrowserFragment.create(Globals.defaultFolder); return fileFrag; @@ -1040,50 +949,44 @@ public Fragment getItem(int position) playFrag = PlayerFragment.create(); return playFrag; case 2: - plistFrag = PlaylistFragment.create(Globals.dataFolder+"playlists/"); + plistFrag = PlaylistFragment.create(Globals.dataFolder + "playlists/"); return plistFrag; default: return null; } } + @Override - public CharSequence getPageTitle(int position) - { + public CharSequence getPageTitle(int position) { return pages[position]; } } + @Override - public void needFileBackCallback(boolean yes) - { - needFileBack=yes; - if(getSupportActionBar()!=null) - { - if(viewPager.getCurrentItem()==0) - { - if(needFileBack) - { + public void needFileBackCallback(boolean yes) { + needFileBack = yes; + if (getSupportActionBar() != null) { + if (viewPager.getCurrentItem() == 0) { + if (needFileBack) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); - }else{ + } else { getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setHomeButtonEnabled(false); } } } } + @Override - public void needPlaylistBackCallback(boolean yes, boolean current) - { - needPlaylistBack=yes; - if(getSupportActionBar()!=null) - { - if(viewPager.getCurrentItem()==2) - { - if(needPlaylistBack) - { + public void needPlaylistBackCallback(boolean yes, boolean current) { + needPlaylistBack = yes; + if (getSupportActionBar() != null) { + if (viewPager.getCurrentItem() == 2) { + if (needPlaylistBack) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); menuButton2.setVisible(!current); menuButton2.setEnabled(!current); - }else{ + } else { menuButton2.setVisible(true); menuButton2.setEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(false); @@ -1092,503 +995,158 @@ public void needPlaylistBackCallback(boolean yes, boolean current) } } } + // Broadcast actions // This is painful. - public void play() - { + public void play() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 1); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 1); + sendBroadcast(new_intent); } - public void pause() - { + + public void pause() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 2); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 2); + sendBroadcast(new_intent); } - public void next() - { + + public void next() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 3); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 3); + sendBroadcast(new_intent); } - public void prev() - { + + public void prev() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 4); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 4); + sendBroadcast(new_intent); } - public void stop() - { + + public void stop() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); + sendBroadcast(new_intent); } - public void loop(int mode) - { + + public void loop(int mode) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 6); - new_intent.putExtra(getResources().getString(R.string.msrv_loopmode), mode); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 6); + new_intent.putExtra(getResources().getString(R.string.msrv_loopmode), mode); + sendBroadcast(new_intent); } - public void shuffle(int mode) - { + + public void shuffle(int mode) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 7); - new_intent.putExtra(getResources().getString(R.string.msrv_shufmode), mode); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 7); + new_intent.putExtra(getResources().getString(R.string.msrv_shufmode), mode); + sendBroadcast(new_intent); } - public void seek(int time) - { + + public void seek(int time) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 9); - new_intent.putExtra(getResources().getString(R.string.msrv_seektime), time); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 9); + new_intent.putExtra(getResources().getString(R.string.msrv_seektime), time); + sendBroadcast(new_intent); } - public void writeFile(String input, String output) - { + + public void writeFile(String input, String output) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 14); - new_intent.putExtra(getResources().getString(R.string.msrv_infile), input); - new_intent.putExtra(getResources().getString(R.string.msrv_outfile), output); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 14); + new_intent.putExtra(getResources().getString(R.string.msrv_infile), input); + new_intent.putExtra(getResources().getString(R.string.msrv_outfile), output); + sendBroadcast(new_intent); } + @SuppressLint("NewApi") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - // Check which request we're responding to - if (requestCode == 1) - { - if(oldTheme!=Globals.theme) - { - Intent intent = getIntent(); - intent.putExtra("justtheme", true); - intent.putExtra("needservice", false); - finish(); - startActivity(intent); - } - - }else if(requestCode==42) - { - if (resultCode == RESULT_OK) - { - Uri treeUri = data.getData(); - getContentResolver().takePersistableUriPermission(treeUri, - Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - } - initCallback2(); - } - } - public void readyForInit() - { - if(needInit) - initCallback(); - } - public void dynExport() - { - localfinished=false; - if(Globals.isMidi(currSongName)&&Globals.isPlaying==0) - { - - - AlertDialog.Builder alert = new AlertDialog.Builder(this); - - alert.setTitle(getResources().getString(R.string.dynex_alert1)); - alert.setMessage(getResources().getString(R.string.dynex_alert1_msg)); - InputFilter filter = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) - { - for (int i = start; i < end; i++) - { - String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; - if (IC.contains("*"+source.charAt(i)+"*")) - { - return ""; - } - } - return null; - } - }; - final EditText input = new EditText(this); - input.setFilters(new InputFilter[]{filter}); - alert.setView(input); - - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int whichButton) - { - String value = input.getText().toString(); - if(!value.toLowerCase(Locale.US).endsWith(".wav")) - value+=".wav"; - String parent=currSongName.substring(0,currSongName.lastIndexOf('/')+1); - boolean alreadyExists = new File(parent+value).exists(); - boolean aWrite=true; - String needRename = null; - String probablyTheRoot = ""; - String probablyTheDirectory = ""; - try{ - new FileOutputStream(parent+value,true).close(); - }catch(FileNotFoundException e) - { - aWrite=false; - } catch (IOException e) - { - e.printStackTrace(); - } - - if(aWrite&&!alreadyExists) - new File(parent+value).delete(); - - if(aWrite&&new File(parent).canWrite()) - { - value=parent+value; - }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null) - { - String[] tmp = Globals.getDocFilePaths(TimidityActivity.this,parent); - probablyTheDirectory = tmp[0]; - probablyTheRoot = tmp[1]; - if(probablyTheDirectory.length()>1) - { - needRename = parent.substring(parent.indexOf(probablyTheRoot)+probablyTheRoot.length())+value; - value = probablyTheDirectory+'/'+value; - }else{ - value=Environment.getExternalStorageDirectory().getAbsolutePath()+'/'+value; - } - }else{ - value=Environment.getExternalStorageDirectory().getAbsolutePath()+'/'+value; - } - final String finalval = value; - final boolean canWrite = aWrite; - final String needToRename = needRename; - final String probRoot = probablyTheRoot; - if(new File(finalval).exists()||(new File(probRoot+needRename).exists()&&needToRename!=null)) - { - AlertDialog dialog2 = new AlertDialog.Builder(TimidityActivity.this).create(); - dialog2.setTitle(getResources().getString(R.string.warning)); - dialog2.setMessage(getResources().getString(R.string.dynex_alert2_msg)); - dialog2.setCancelable(false); - dialog2.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int buttonId) - { - if(!canWrite&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - if(needToRename!=null) - { - Globals.tryToDeleteFile(TimidityActivity.this, probRoot+needToRename); - Globals.tryToDeleteFile(TimidityActivity.this, finalval); - }else{ - Globals.tryToDeleteFile(TimidityActivity.this, finalval); - } - }else{ - new File(finalval).delete(); - } - saveWavPart2(finalval, needToRename); - } - }); - dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int buttonId) - { - - } - }); - dialog2.show(); - }else{ - saveWavPart2(finalval, needToRename); - } - + // Check which request we're responding to + if (requestCode == 1) { + if (oldTheme != Globals.theme) { + Intent intent = getIntent(); + intent.putExtra("justtheme", true); + intent.putExtra("needservice", false); + finish(); + startActivity(intent); } - }); - - alert.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - // Canceled. - } - }); - - alerty = alert.show(); - - } - } - - public void saveCfg() - { - localfinished=false; - if(Globals.isMidi(currSongName)&&Globals.isPlaying==0) - { - - - AlertDialog.Builder alert = new AlertDialog.Builder(this); - - alert.setTitle("Save Cfg"); - alert.setMessage("Save a MIDI configuration file"); - InputFilter filter = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { - for (int i = start; i < end; i++) { - String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; - if (IC.contains("*"+source.charAt(i)+"*")) { - return ""; - } - } - return null; - } - }; - // Set an EditText view to get user input - final EditText input = new EditText(this); - input.setFilters(new InputFilter[]{filter}); - alert.setView(input); - - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - if(!value.toLowerCase(Locale.US).endsWith(Globals.compressCfg?".tzf":".tcf")) - value+=(Globals.compressCfg?".tzf":".tcf"); - String parent=currSongName.substring(0,currSongName.lastIndexOf('/')+1); - boolean aWrite=true; - boolean alreadyExists = new File(parent+value).exists(); - String needRename = null; - String probablyTheRoot = ""; - String probablyTheDirectory = ""; - try{ - new FileOutputStream(parent+value,true).close(); - }catch(FileNotFoundException e) - { - aWrite=false; - } catch (IOException e) - { - e.printStackTrace(); - } - if(!alreadyExists&&aWrite) - new File(parent+value).delete(); - if(aWrite&&new File(parent).canWrite()) - { - value=parent+value; - }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null) - { - //TODO - // Write the file to getExternalFilesDir, then move it with the Uri - // We need to tell JNIHandler that movement is needed. - - String[] tmp = Globals.getDocFilePaths(TimidityActivity.this,parent); - probablyTheDirectory = tmp[0]; - probablyTheRoot = tmp[1]; - if(probablyTheDirectory.length()>1) - { - needRename = parent.substring(parent.indexOf(probablyTheRoot)+probablyTheRoot.length())+value; - value = probablyTheDirectory+'/'+value; - }else{ - value=Environment.getExternalStorageDirectory().getAbsolutePath()+'/'+value; - return; + } else if (requestCode == 42) { + if (resultCode == RESULT_OK) { + Uri treeUri = data.getData(); + getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } - }else{ - value=Environment.getExternalStorageDirectory().getAbsolutePath()+'/'+value; - } - final String finalval = value; - final boolean canWrite = aWrite; - final String needToRename = needRename; - final String probRoot = probablyTheRoot; - if(new File(finalval).exists()||(new File(probRoot+needRename).exists()&&needToRename!=null)) - { - AlertDialog dialog2 = new AlertDialog.Builder(TimidityActivity.this).create(); - dialog2.setTitle("Warning"); - dialog2.setMessage("Overwrite config file?"); - dialog2.setCancelable(false); - dialog2.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - if(!canWrite&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - if(needToRename!=null) - { - Globals.tryToDeleteFile(TimidityActivity.this, probRoot+needToRename); - Globals.tryToDeleteFile(TimidityActivity.this, finalval); - }else{ - Globals.tryToDeleteFile(TimidityActivity.this, finalval); - } - }else{ - new File(finalval).delete(); - } - saveCfgPart2(finalval, needToRename); - } - }); - dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - - } - }); - dialog2.show(); - }else{ - saveCfgPart2(finalval, needToRename); - } + initCallback2(); } - }); - - alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - // Canceled. - } - }); + } - alerty = alert.show(); - } + public void readyForInit() { + if (needInit) + initCallback(); } - public void saveCfgPart2(final String finalval, final String needToRename) - { - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 16); - new_intent.putExtra(getResources().getString(R.string.msrv_outfile), finalval); - sendBroadcast(new_intent); - final ProgressDialog prog; - prog = new ProgressDialog(TimidityActivity.this); - prog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - dialog.dismiss(); - } - }); - prog.setTitle("Saving CFG"); - prog.setMessage("Saving..."); - prog.setIndeterminate(true); - prog.setCancelable(false); - prog.show(); - new Thread(new Runnable() { - @Override - public void run() { - while(!localfinished&&prog.isShowing()){ - try { - - Thread.sleep(25); - } catch (InterruptedException e){}} - - TimidityActivity.this.runOnUiThread(new Runnable() { - public void run() { - String trueName = finalval; - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null&&needToRename!=null) - { - if(Globals.renameDocumentFile(TimidityActivity.this, finalval, needToRename)) - { - trueName=needToRename; - }else{ - trueName="Error"; - } - } - Toast.makeText( TimidityActivity.this, "Wrote "+trueName, Toast.LENGTH_SHORT).show(); - prog.dismiss(); - fileFrag.getDir(fileFrag.currPath); - } - }); - - } - }).start(); + + public void loadCfg() { + new FileBrowserDialog().create(0, Globals.configFiles, this, this, getLayoutInflater(), true, currSongName.substring(0, currSongName.lastIndexOf('/')), "Loaded"); } - public void saveWavPart2(final String finalval, final String needToRename) - { + + public void loadCfg(String path) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 15); - new_intent.putExtra(getResources().getString(R.string.msrv_outfile), finalval); - sendBroadcast(new_intent); - final ProgressDialog prog; - prog = new ProgressDialog(TimidityActivity.this); - prog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - dialog.dismiss(); - } - }); - prog.setTitle("Converting to WAV"); - prog.setMessage("Converting..."); - prog.setIndeterminate(false); - prog.setCancelable(false); - prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - prog.show(); - new Thread(new Runnable() { - @Override - public void run() { - while(!localfinished&&prog.isShowing()){ - prog.setMax(JNIHandler.maxTime); - prog.setProgress(JNIHandler.currTime); - try { - - Thread.sleep(25); - } catch (InterruptedException e){}} - if(!localfinished) - { - JNIHandler.stop(); - TimidityActivity.this.runOnUiThread(new Runnable() { - public void run() { - Toast.makeText( TimidityActivity.this, "Conversion canceled", Toast.LENGTH_SHORT).show(); - if(!Globals.keepWav) - { - if(new File(finalval).exists()) - new File(finalval).delete(); - }else{ - fileFrag.getDir(fileFrag.currPath); - } - } - }); - - }else{ - TimidityActivity.this.runOnUiThread(new Runnable() { - public void run() { - String trueName = finalval; - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null&&needToRename!=null) - { - if(Globals.renameDocumentFile(TimidityActivity.this, finalval, needToRename)) - { - trueName=needToRename; - }else{ - trueName="Error"; - } - } - Toast.makeText( TimidityActivity.this, "Wrote "+trueName, Toast.LENGTH_SHORT).show(); - prog.dismiss(); - fileFrag.getDir(fileFrag.currPath); - } - }); - } - } - }).start(); - } - public void loadCfg() - { - new FileBrowserDialog().create( 0, Globals.configFiles, this, this, getLayoutInflater(), true, currSongName.substring(0,currSongName.lastIndexOf('/')), "Loaded"); - } - public void loadCfg(String path) - { - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17); - new_intent.putExtra(getResources().getString(R.string.msrv_infile), path); - sendBroadcast(new_intent); + new_intent.setAction(getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17); + new_intent.putExtra(getResources().getString(R.string.msrv_infile), path); + sendBroadcast(new_intent); } + @Override - public void setItem(String path, int type) - { + public void setItem(String path, int type) { loadCfg(path); } + @Override - public void write() - { - + public void write() { + } + @Override - public void ignore() - { - + public void ignore() { + + } + + public void setLocalFinished(boolean yes) { + if (special != null) { + special.setLocalFinished(yes); + } + } + + public void dynExport(boolean whilePlaying) { + WavSaver ws = new WavSaver(this, currSongName, whilePlaying); + special = ws; + ws.dynExport(); + } + + public void dynExport(String filename, boolean whilePlaying) { + WavSaver ws = new WavSaver(this, filename, whilePlaying); + special = ws; + ws.dynExport(); + } + + public void saveCfg() { + ConfigSaver cs = new ConfigSaver(this, currSongName); + special = cs; + cs.saveCfg(); + } + + public void saveCfgPart2(String s1, String s2) { + ConfigSaver cs = new ConfigSaver(this, currSongName); + special = cs; + cs.saveCfgPart2(s1, s2); } } diff --git a/src/com/xperia64/timidityae/TrackFragment.java b/src/com/xperia64/timidityae/TrackFragment.java deleted file mode 100755 index 827187e..0000000 --- a/src/com/xperia64/timidityae/TrackFragment.java +++ /dev/null @@ -1,295 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2014 xperia64 - * - * Copyright (C) 1999-2008 Masanao Izumo - * - * Copyright (C) 1995 Tuukka Toivonen - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Public License v3.0 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/gpl.html - ******************************************************************************/ -package com.xperia64.timidityae; - -import java.util.ArrayList; -import java.util.List; -import android.annotation.SuppressLint; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.graphics.Color; -import android.os.Build; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.text.Editable; -import android.text.TextWatcher; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.EditText; -import android.widget.SeekBar.OnSeekBarChangeListener; -import android.widget.ListView; -import android.widget.SeekBar; -import android.widget.Spinner; -import android.widget.AdapterView.OnItemClickListener; -import com.xperia64.timidityae.R; - -public class TrackFragment extends Fragment { - ArrayList localInst = new ArrayList(); - - ArrayList localVol = new ArrayList(); - - //ArrayList JNIHandler.drums = new ArrayList(); - ArrayAdapter fileList; - boolean fromUser; - ListView channelList; - //int bigCounter=6; - AlertDialog ddd; - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.track_fragment, container, false); - channelList = (ListView) v.findViewById(R.id.trackList); - return v; - - } - @Override - public void onViewCreated(View view, Bundle savedInstanceState) - { - reset(); - - fileList = - new ArrayAdapter(getActivity(), R.layout.row); - for(int i = 0; i arg0, View arg1, final int arg2, - long arg3) { - AlertDialog.Builder b = new AlertDialog.Builder(getActivity()); - View v = getActivity().getLayoutInflater().inflate(R.layout.track_dialog, null); - final Spinner instSpin = (Spinner) v.findViewById(R.id.instSpin); - instSpin.setClickable(JNIHandler.custInst.get(arg2)&&!JNIHandler.drums.get(arg2)); - instSpin.setOnLongClickListener(null); - instSpin.setEnabled(JNIHandler.custInst.get(arg2)&&!JNIHandler.drums.get(arg2)); - List arrayAdapter = new ArrayList(); - final int offset=(!JNIHandler.drums.get(arg2))?0:34; - if(!JNIHandler.drums.get(arg2)) - { - for(String inst : getActivity().getResources().getStringArray(R.array.midi_instruments)) - arrayAdapter.add(inst); - }else{ - for(String inst : getActivity().getResources().getStringArray(R.array.midi_drums)) - arrayAdapter.add(inst); - } - ArrayAdapter dataAdapter = new ArrayAdapter(getActivity(), - android.R.layout.simple_spinner_item, arrayAdapter); - if(Build.VERSION.SDK_INT0) - { - int numm = Integer.parseInt(s.toString()); - if(numm>127) - { - fromUser=true; - numm=127; - } - if(numm<0) - { - fromUser=true; - numm=0; - } - if(fromUser) - { - txtVol.setText(Integer.toString(numm)); - } - fromUser=true; - volSeek.setProgress(numm); - fromUser=false; - } - }else{ - fromUser=false; - } - } - public void beforeTextChanged(CharSequence s, int start, int count, int after){} - public void onTextChanged(CharSequence s, int start, int before, int count){} - }); - final CheckBox inst = (CheckBox) v.findViewById(R.id.defInstr); - inst.setEnabled(!JNIHandler.drums.get(arg2)); - inst.setChecked(!JNIHandler.custInst.get(arg2)); - inst.setOnCheckedChangeListener(new OnCheckedChangeListener(){ - - @Override - public void onCheckedChanged(CompoundButton arg0, - boolean arg1) { - - instSpin.setClickable(!arg1); - instSpin.setEnabled(!arg1); - } - - }); - final CheckBox vol = (CheckBox) v.findViewById(R.id.defVol); - vol.setChecked(!JNIHandler.custVol.get(arg2)); - //System.out.println("Def inst: "+(!JNIHandler.custInst.get(arg2)?"true":"false")+" def vol: "+(!JNIHandler.custVol.get(arg2)?"true":"false")); - vol.setOnCheckedChangeListener(new OnCheckedChangeListener(){ - - @Override - public void onCheckedChanged(CompoundButton arg0, - boolean arg1) { - - volSeek.setClickable(!arg1); - volSeek.setEnabled(!arg1); - txtVol.setClickable(!arg1); - txtVol.setEnabled(!arg1); - } - - }); - if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) - v.setBackgroundColor(Globals.theme==1?Color.WHITE:Color.BLACK); - b.setView(v); - b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() - { - - @Override - public void onClick(DialogInterface dialog, int which) { - - JNIHandler.custInst.set(arg2, !inst.isChecked()); - JNIHandler.custVol.set(arg2, !vol.isChecked()); - JNIHandler.setChannelVolumeTimidity(arg2|(JNIHandler.custVol.get(arg2)?0x800:0x8000), volSeek.getProgress()); - JNIHandler.setChannelTimidity(arg2|(JNIHandler.custInst.get(arg2)?0x800:0x8000), instSpin.getSelectedItemPosition()); - if(!JNIHandler.paused&&Globals.isPlaying==0) - JNIHandler.seekTo(JNIHandler.currTime); - //bigCounter=12; - updateList(); - } - }); - - b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() - { - @Override public void onClick(DialogInterface dialog, int which) {} - }); - b.setTitle(String.format((getActivity().getResources().getString(R.string.trk_form2)), (arg2+1))); - ddd=b.create(); - ddd.show(); - } - - }); - } - public void reset() - { - localInst = new ArrayList(); - localVol = new ArrayList(); - if(ddd!=null) - { - if(ddd.isShowing()) - { - ddd.dismiss(); - ddd=null; - } - } - for(Integer x : JNIHandler.programs) - { - localInst.add(x); - } - for(Integer x : JNIHandler.volumes) - { - localVol.add(x); - } - } - public void updateList() - { - if(!JNIHandler.type) - { - //if(++bigCounter>4) - //{ - //bigCounter=0; - boolean needUpdate=false; - - for(int i = 0; i arg0, View arg1, int arg2, long arg3) { File file = new File(path.get(arg2)); + System.out.println(path.get(arg2)); if (file.isDirectory()) { if (file.canRead()) @@ -221,33 +231,20 @@ public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { new AlertDialog.Builder(context) .setIcon(R.drawable.ic_launcher) - .setTitle( - "[" - + file.getName() - + "] " - + (context.getResources() - .getString(R.string.fb_cread))) - .setPositiveButton( - context.getResources().getString( - android.R.string.ok), + .setTitle( String.format("[%1$s] %2$s", file.getName(), context.getResources().getString(R.string.fb_cread))) + .setPositiveButton(context.getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override - public void onClick(DialogInterface dialog, - int which) - { - } + public void onClick(DialogInterface dialog, int which){} }).show(); } } else { if (file.canRead()) { - Toast.makeText( - context, - msg+ " '" + fname.get(arg2) + '\'', - Toast.LENGTH_SHORT).show(); - mCallback.setItem(file.getAbsolutePath(), type); - if(closeImmediate) + Toast.makeText(context, String.format("%1$s '%2$s'", msg, fname.get(arg2)),Toast.LENGTH_SHORT).show(); + onSelectedCallback.setItem(file.getAbsolutePath(), type); + if(closeImmediately) ddd.dismiss(); } } diff --git a/src/com/xperia64/timidityae/SoundfontArrayAdapter.java b/src/com/xperia64/timidityae/gui/dialogs/SoundfontArrayAdapter.java similarity index 53% rename from src/com/xperia64/timidityae/SoundfontArrayAdapter.java rename to src/com/xperia64/timidityae/gui/dialogs/SoundfontArrayAdapter.java index eb79e5e..1807c17 100755 --- a/src/com/xperia64/timidityae/SoundfontArrayAdapter.java +++ b/src/com/xperia64/timidityae/gui/dialogs/SoundfontArrayAdapter.java @@ -9,7 +9,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.gui.dialogs; import java.io.File; import java.util.ArrayList; @@ -33,53 +33,55 @@ public interface SoundfontArrayAdapterListener { public void setSFEnabled(int position, boolean yes); } - SoundfontArrayAdapterListener mc; private LayoutInflater inflater; private ArrayList itemChecked = new ArrayList(); + public SoundfontArrayAdapter(SoundfontArrayAdapterListener c, Context context, List sfList) { super(context, R.layout.row_check, R.id.checkText, sfList); mc = c; inflater = LayoutInflater.from(context); - for (int i=0; i < sfList.size(); i++) { - itemChecked.add(i, !sfList.get(i).startsWith("#")); + for (int i = 0; i < sfList.size(); i++) { + itemChecked.add(i, !sfList.get(i).startsWith("#")); } } + @Override public View getView(final int position, View convertView, final ViewGroup parent) { - View view = convertView; - final SoundfontHolder viewHolder; - if(view == null){ - view = inflater.inflate(R.layout.row_check, null); - viewHolder = new SoundfontHolder(); - viewHolder.name= (TextView) view.findViewById(R.id.checkText); - viewHolder.b = (ToggleButton) view.findViewById(R.id.sfSwitch); + View view = convertView; + final SoundfontHolder viewHolder; + if (view == null) { + view = inflater.inflate(R.layout.row_check, null); + viewHolder = new SoundfontHolder(); + viewHolder.name = (TextView) view.findViewById(R.id.checkText); + viewHolder.b = (ToggleButton) view.findViewById(R.id.sfSwitch); - view.setTag(viewHolder); - }else{ - viewHolder = (SoundfontHolder) view.getTag(); - } - String tmp = getItem(position); - viewHolder.name.setText(tmp.substring(tmp.lastIndexOf(File.separator) + 1)); - viewHolder.b.setOnClickListener(new View.OnClickListener() { + view.setTag(viewHolder); + } else { + viewHolder = (SoundfontHolder) view.getTag(); + } + String tmp = getItem(position); + viewHolder.name.setText(tmp.substring(tmp.lastIndexOf(File.separator) + 1)); + viewHolder.b.setOnClickListener(new View.OnClickListener() { - public void onClick(View v) { - mc.setSFEnabled(position, viewHolder.b.isChecked()); - }}); - viewHolder.b.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onClick(View v) { + mc.setSFEnabled(position, viewHolder.b.isChecked()); + } + }); + viewHolder.b.setOnCheckedChangeListener(new OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, - boolean isChecked) { - itemChecked.set(position, isChecked); - } - }); - viewHolder.b.setChecked(itemChecked.get(position)); - return view; + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + itemChecked.set(position, isChecked); + } + }); + viewHolder.b.setChecked(itemChecked.get(position)); + return view; } - static class SoundfontHolder { - TextView name; - ToggleButton b; - } + static class SoundfontHolder { + + TextView name; + ToggleButton b; + } } diff --git a/src/com/xperia64/timidityae/SoundfontDialog.java b/src/com/xperia64/timidityae/gui/dialogs/SoundfontDialog.java similarity index 61% rename from src/com/xperia64/timidityae/SoundfontDialog.java rename to src/com/xperia64/timidityae/gui/dialogs/SoundfontDialog.java index 410107e..78fbc06 100755 --- a/src/com/xperia64/timidityae/SoundfontDialog.java +++ b/src/com/xperia64/timidityae/gui/dialogs/SoundfontDialog.java @@ -9,14 +9,16 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.gui.dialogs; import java.io.File; import java.util.ArrayList; import java.util.Locale; -import com.xperia64.timidityae.FileBrowserDialog.FileBrowserDialogListener; +import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.JNIHandler; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog.FileBrowserDialogListener; import android.app.Activity; import android.app.AlertDialog; @@ -41,68 +43,80 @@ public class SoundfontDialog implements OnItemLongClickListener, FileBrowserDial ListView mList; LinearLayout mLayout; SoundfontDialogListener mCallback; - public interface SoundfontDialogListener{ + + public interface SoundfontDialogListener { public void writeSoundfonts(ArrayList l); } - public void create(ArrayList currList, SoundfontDialogListener sl, final Activity c, final LayoutInflater f, final String path) - { + + public void create(ArrayList currList, SoundfontDialogListener sl, final Activity c, final LayoutInflater f, final String path) { sfList = new ArrayList(currList.size()); - for (String foo: currList) { - sfList.add((String)foo); + for (String foo : currList) { + sfList.add((String) foo); } - context=c; + context = c; mCallback = sl; AlertDialog.Builder b = new AlertDialog.Builder(context); mLayout = (LinearLayout) f.inflate(R.layout.list, null); mList = (ListView) mLayout.findViewById(android.R.id.list); - - SoundfontArrayAdapter fileList = - new SoundfontArrayAdapter(this, context, sfList); + + SoundfontArrayAdapter fileList = new SoundfontArrayAdapter(this, context, sfList); mList.setAdapter(fileList); mList.setOnItemLongClickListener(this); b.setView(mLayout); b.setCancelable(false); b.setTitle(c.getResources().getString(R.string.sf_man)); - b.setPositiveButton(c.getResources().getString(R.string.done), new DialogInterface.OnClickListener() - { - @Override public void onClick(DialogInterface dialog, int which) {mCallback.writeSoundfonts(sfList);} - }); - b.setNeutralButton(c.getResources().getString(R.string.addcon), new DialogInterface.OnClickListener() - { - @Override public void onClick(DialogInterface dialog, int which) {} + b.setPositiveButton(c.getResources().getString(R.string.done), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + mCallback.writeSoundfonts(sfList); + } + }); + b.setNeutralButton(c.getResources().getString(R.string.addcon), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + } + }); + b.setNegativeButton(c.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } }); - b.setNegativeButton(c.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() - { - @Override public void onClick(DialogInterface dialog, int which) {dialog.dismiss();} - }); AlertDialog ddd = b.create(); ddd.show(); Button theButton = ddd.getButton(DialogInterface.BUTTON_NEUTRAL); - theButton.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {tmpList = new ArrayList(); new FileBrowserDialog().create(0, Globals.fontFiles, SoundfontDialog.this, c, f, false, path, c.getResources().getString(R.string.fb_add));}}); + theButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + tmpList = new ArrayList(); + new FileBrowserDialog().create(0, Globals.fontFiles, SoundfontDialog.this, c, f, false, path, c.getResources().getString(R.string.fb_add)); + } + }); } @Override public void setItem(final String path, int type) { - if(path.toLowerCase(Locale.US).endsWith(".sfark")||path.toLowerCase(Locale.US).endsWith(".sfark.exe")) - { + if (path.toLowerCase(Locale.US).endsWith(".sfark") || path.toLowerCase(Locale.US).endsWith(".sfark.exe")) { AlertDialog.Builder be = new AlertDialog.Builder(context); be.setCancelable(false); be.setTitle("Extract sfArk?"); - be.setMessage(String.format("%s must be extracted. Extract to %s?",path.substring(path.lastIndexOf('/')+1),path.substring(path.lastIndexOf('/')+1,path.lastIndexOf('.'))+".sf2")); - be.setNegativeButton(context.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener(){ + be.setMessage(String.format("%s must be extracted. Extract to %s?", path.substring(path.lastIndexOf('/') + 1), path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.')) + ".sf2")); + be.setNegativeButton(context.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - - }}); - be.setPositiveButton(context.getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener(){ + + } + }); + be.setPositiveButton(context.getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AsyncTask task = new AsyncTask() { - + ProgressDialog pd; + @Override protected void onPreExecute() { pd = new ProgressDialog(context); @@ -112,127 +126,124 @@ protected void onPreExecute() { pd.setIndeterminate(true); pd.show(); } - + @Override protected Void doInBackground(Void... arg0) { - JNIHandler.decompressSFArk(path, path.substring(path.lastIndexOf('/')+1,path.lastIndexOf('.'))+".sf2"); + JNIHandler.decompressSFArk(path, path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.')) + ".sf2"); return null; } - + @Override protected void onPostExecute(Void result) { - if(pd!=null) + if (pd != null) pd.dismiss(); - if(new File(path.substring(0,path.lastIndexOf('.'))+".sf2").exists()) - { - tmpList.add(path.substring(0,path.lastIndexOf('.'))+".sf2"); + if (new File(path.substring(0, path.lastIndexOf('.')) + ".sf2").exists()) { + tmpList.add(path.substring(0, path.lastIndexOf('.')) + ".sf2"); AlertDialog.Builder bee = new AlertDialog.Builder(context); bee.setCancelable(false); bee.setTitle("Delete sfArk?"); - bee.setMessage(String.format("Delete %s?",path.substring(path.lastIndexOf('/')+1))); - bee.setNegativeButton(context.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener(){ + bee.setMessage(String.format("Delete %s?", path.substring(path.lastIndexOf('/') + 1))); + bee.setNegativeButton(context.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - - }}); + + } + }); bee.setPositiveButton(context.getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { - + @Override public void onClick(DialogInterface dialog, int which) { new File(path).delete(); } }); - } - else + } else Toast.makeText(context, "Error extracting sfArk", Toast.LENGTH_SHORT).show(); - //b.setEnabled(true); + // b.setEnabled(true); } - + }; - task.execute((Void[])null); - - }}); + task.execute((Void[]) null); + + } + }); be.show(); - }else{ + } else { tmpList.add(path); } - + } + @Override public void write() { - + sfList.addAll(tmpList); - SoundfontArrayAdapter fileList = - new SoundfontArrayAdapter(this, context, sfList); + SoundfontArrayAdapter fileList = new SoundfontArrayAdapter(this, context, sfList); mList.setAdapter(fileList); mList.setOnItemLongClickListener(this); } + @Override public void ignore() { - tmpList=null; + tmpList = null; } + @Override - public boolean onItemLongClick(AdapterView arg0, View arg1, final int arg2, - long arg3) { - AlertDialog.Builder builderSingle = new AlertDialog.Builder( - context); - builderSingle.setIcon(R.drawable.ic_launcher); - builderSingle.setTitle(context.getResources().getString(R.string.sf_rem)); - builderSingle.setCancelable(false); - builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - + public boolean onItemLongClick(AdapterView arg0, View arg1, final int arg2, long arg3) { + AlertDialog.Builder builderSingle = new AlertDialog.Builder(context); + builderSingle.setIcon(R.drawable.ic_launcher); + builderSingle.setTitle(context.getResources().getString(R.string.sf_rem)); + builderSingle.setCancelable(false); + builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); - + } }); - builderSingle.setPositiveButton(context.getResources().getString(R.string.sf_rem2), new DialogInterface.OnClickListener() { - + builderSingle.setPositiveButton(context.getResources().getString(R.string.sf_rem2), new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { - AlertDialog.Builder builderDouble = new AlertDialog.Builder( - context).setIcon(R.drawable.ic_launcher).setTitle(String.format(context.getResources().getString(R.string.sf_com), sfList.get(arg2).substring(sfList.get(arg2).lastIndexOf('/')+1))).setCancelable(false); - builderDouble.setPositiveButton(context.getResources().getString(R.string.yes),new DialogInterface.OnClickListener() { - + AlertDialog.Builder builderDouble = new AlertDialog.Builder(context).setIcon(R.drawable.ic_launcher).setTitle(String.format(context.getResources().getString(R.string.sf_com), sfList.get(arg2).substring(sfList.get(arg2).lastIndexOf('/') + 1))).setCancelable(false); + builderDouble.setPositiveButton(context.getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { sfList.remove(arg2); - SoundfontArrayAdapter fileList = - new SoundfontArrayAdapter(SoundfontDialog.this, context, sfList); + SoundfontArrayAdapter fileList = new SoundfontArrayAdapter(SoundfontDialog.this, context, sfList); mList.setAdapter(fileList); mList.setOnItemLongClickListener(SoundfontDialog.this); - } - }); + } + }); builderDouble.setNegativeButton(context.getResources().getString(R.string.no), new DialogInterface.OnClickListener() { - + @Override - public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}); + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); builderDouble.show(); dialog.dismiss(); - + } }); - builderSingle.show(); + builderSingle.show(); return true; } @Override public void setSFEnabled(int position, boolean enable) { String pos = sfList.get(position); - if(pos.startsWith("#")&&enable) - { + if (pos.startsWith("#") && enable) { pos = pos.substring(1); sfList.set(position, pos); - }else if(!pos.startsWith("#")&&!enable) - { - sfList.set(position, "#"+pos); + } else if (!pos.startsWith("#") && !enable) { + sfList.set(position, "#" + pos); } } - - } diff --git a/src/com/xperia64/timidityae/ArtFragment.java b/src/com/xperia64/timidityae/gui/fragments/ArtFragment.java similarity index 82% rename from src/com/xperia64/timidityae/ArtFragment.java rename to src/com/xperia64/timidityae/gui/fragments/ArtFragment.java index 4f2388b..30f940d 100755 --- a/src/com/xperia64/timidityae/ArtFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/ArtFragment.java @@ -9,7 +9,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.gui.fragments; import android.app.Activity; import android.graphics.Bitmap; @@ -21,49 +21,40 @@ import android.widget.ImageView; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.util.Globals; public class ArtFragment extends Fragment { private ImageView mImg; private boolean artOk = false; @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.art_fragment, container, false); mImg = (ImageView) v.findViewById(R.id.albumArt); return v; - } @Override - public void onViewCreated(View view, Bundle savedInstanceState) - { + public void onViewCreated(View view, Bundle savedInstanceState) { // If the view is set up, we can set the album art artOk = true; setArt(Globals.currArt, getActivity()); } - public void setArt(final Bitmap art, Activity a) - { - if (artOk) - { - if (art != null) - { + public void setArt(final Bitmap art, Activity a) { + if (artOk) { + if (art != null) { a.runOnUiThread(new Runnable() { @Override - public void run() - { + public void run() { mImg.setImageBitmap(art); mImg.invalidate(); } }); - } else - { + } else { a.runOnUiThread(new Runnable() { @Override - public void run() - { + public void run() { mImg.setImageResource(R.drawable.timidity); mImg.invalidate(); } diff --git a/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java b/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java new file mode 100755 index 0000000..b808356 --- /dev/null +++ b/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java @@ -0,0 +1,218 @@ +/******************************************************************************* + * Copyright (C) 2014 xperia64 + * + * Copyright (C) 1999-2008 Masanao Izumo + * + * Copyright (C) 1995 Tuukka Toivonen + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/gpl.html + ******************************************************************************/ +package com.xperia64.timidityae.gui.fragments; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import com.xperia64.timidityae.R; +import com.xperia64.timidityae.TimidityActivity; +import com.xperia64.timidityae.util.FileComparator; +import com.xperia64.timidityae.util.Globals; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Bundle; +import android.os.Environment; +import android.support.v4.app.ListFragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +public class FileBrowserFragment extends ListFragment { + public String currPath; + List path; + List fname; + boolean gotDir = false; + ActionFileBackListener mCallback; + public boolean localfinished = false; + + public interface ActionFileBackListener { + public void needFileBackCallback(boolean yes); + } + + public static FileBrowserFragment create(String fold) { + Bundle args = new Bundle(); + args.putString(Globals.currFoldKey, fold); + FileBrowserFragment fragment = new FileBrowserFragment(); + fragment.setArguments(args); + return fragment; + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (getArguments() != null) + currPath = getArguments().getString(Globals.currFoldKey); + if (currPath == null) + currPath = Environment.getExternalStorageDirectory().getAbsolutePath(); + else if (!new File(currPath).exists()) + currPath = Environment.getExternalStorageDirectory().getAbsolutePath(); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.list, container, false); + return v; + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + if (!gotDir) { + gotDir = true; + getDir(currPath); + } + } + + @Override + public void onAttach(Context activity) { + super.onAttach(activity); + try { + mCallback = (ActionFileBackListener) activity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + " must implement ActionFileBackListener"); + } + if (Globals.shouldRestore) { + Intent new_intent = new Intent(); + new_intent.setAction(getActivity().getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(getActivity().getResources().getString(R.string.msrv_cmd), 10); + getActivity().sendBroadcast(new_intent); + } + } + + public void getDir(String dirPath) { + currPath = dirPath; + fname = new ArrayList(); + path = new ArrayList(); + if (currPath != null) { + File f = new File(currPath); + if (f.exists()) { + File[] files = f.listFiles(); + if (files != null && files.length > 0) { + + Arrays.sort(files, new FileComparator()); + + // System.out.println(currPath); + if (!currPath.matches("[/]+")) { + fname.add("../"); + // Thank you Marshmallow. + // Disallowing access to /storage/emulated has now + // prevent billions of hacking attempts daily. + if (new File(f.getParent()).canRead()) { + path.add(f.getParent() + "/"); + } else { + path.add("/"); + } + mCallback.needFileBackCallback(true); + } else { + mCallback.needFileBackCallback(false); + } + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if ((!file.getName().startsWith(".") && !Globals.showHiddenFiles) || Globals.showHiddenFiles) { + if (file.isFile()) { + int dotPosition = file.getName().lastIndexOf("."); + String extension = ""; + if (dotPosition != -1) { + extension = (file.getName().substring(dotPosition)).toLowerCase(Locale.US); + if (extension != null) { + + if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + + path.add(file.getAbsolutePath()); + fname.add(file.getName()); + } + } else if (file.getName().endsWith("/")) { + path.add(file.getAbsolutePath() + "/"); + fname.add(file.getName() + "/"); + } + } + } else { + path.add(file.getAbsolutePath() + "/"); + fname.add(file.getName() + "/"); + } + } + } + } else { + if (!currPath.matches("[/]+")) { + fname.add("../"); + path.add(f.getParent() + "/"); + + } + } + ArrayAdapter fileList = new ArrayAdapter(getActivity(), R.layout.row, fname); + getListView().setFastScrollEnabled(true); + getListView().setOnItemLongClickListener(new OnItemLongClickListener() { + + @Override + public boolean onItemLongClick(AdapterView l, View v, final int position, long id) { + System.out.println("Derp" + "Drip"); + if (Globals.isMidi(path.get(position))) { + ((TimidityActivity) getActivity()).dynExport(path.get(position), false); + return true; + } + return false; + } + + }); + setListAdapter(fileList); + } + } + } + + @Override + public void onListItemClick(ListView l, View v, int position, long id) { + File file = new File(path.get(position)); + System.out.println(path.get(position)); + if (file.isDirectory()) { + if (file.canRead()) { + getDir(path.get(position)); + } else { + new AlertDialog.Builder(getActivity()).setIcon(R.drawable.ic_launcher).setTitle(String.format("[%1$s] %2$s", file.getName(), getResources().getString(R.string.fb_cread))).setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + } + }).show(); + } + } else { + if (file.canRead()) { + ArrayList files = new ArrayList(); + int firstFile = -1; + for (int i = 0; i < path.size(); i++) { + if (!path.get(i).endsWith("/")) { + files.add(path.get(i)); + if (firstFile == -1) { + firstFile = i; + } + } + } + ((TimidityActivity) getActivity()).selectedSong(files, position - firstFile, true, false, false); + } + } + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putString(Globals.currFoldKey, currPath); + } +} diff --git a/src/com/xperia64/timidityae/LyricFragment.java b/src/com/xperia64/timidityae/gui/fragments/LyricFragment.java similarity index 83% rename from src/com/xperia64/timidityae/LyricFragment.java rename to src/com/xperia64/timidityae/gui/fragments/LyricFragment.java index 0d216a2..83c83d8 100755 --- a/src/com/xperia64/timidityae/LyricFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/LyricFragment.java @@ -9,7 +9,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.gui.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -20,6 +20,7 @@ import android.widget.ScrollView; import android.widget.TextView; +import com.xperia64.timidityae.JNIHandler; import com.xperia64.timidityae.R; public class LyricFragment extends Fragment { @@ -29,13 +30,10 @@ public class LyricFragment extends Fragment { // TODO Make lyrics shiny-er @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) - { + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ready = false; - View root = inflater.inflate(R.layout.lyrical_fragment, container, - false); + View root = inflater.inflate(R.layout.lyrical_fragment, container, false); lyrics = (TextView) root.findViewById(R.id.lyrics); scrollContainer = (ScrollView) root.findViewById(R.id.lyric_holder); @@ -44,22 +42,17 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, } @Override - public void onViewCreated(View view, Bundle savedInstanceState) - { + public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ready = true; } - public void updateLyrics() - { - if (ready && getActivity() != null) - { + public void updateLyrics() { + if (ready && getActivity() != null) { getActivity().runOnUiThread(new Runnable() { @Override - public void run() - { - lyrics.setText(TextUtils.isEmpty(JNIHandler.currentLyric) ? "(No Lyrics)" - : JNIHandler.currentLyric); + public void run() { + lyrics.setText(TextUtils.isEmpty(JNIHandler.currentLyric) ? "(No Lyrics)" : JNIHandler.currentLyric); lyrics.invalidate(); if (scrollContainer != null) scrollContainer.fullScroll(ScrollView.FOCUS_DOWN); diff --git a/src/com/xperia64/timidityae/PlayerFragment.java b/src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java similarity index 95% rename from src/com/xperia64/timidityae/PlayerFragment.java rename to src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java index 0fb249d..a362bcb 100755 --- a/src/com/xperia64/timidityae/PlayerFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java @@ -9,7 +9,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.gui.fragments; import java.io.File; import java.io.FileNotFoundException; @@ -48,7 +48,10 @@ import android.widget.Toast; import android.widget.SeekBar.OnSeekBarChangeListener; +import com.xperia64.timidityae.JNIHandler; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.TimidityActivity; +import com.xperia64.timidityae.util.Globals; @SuppressLint("Recycle") public class PlayerFragment extends Fragment { @@ -88,7 +91,7 @@ public class PlayerFragment extends Fragment { boolean canEnablePlay=true; boolean updaterPlacid = false; // - AlertDialog ddd; + public AlertDialog ddd; TextView tempo; TextView pitch; TextView voices; @@ -795,7 +798,7 @@ public void onClick(View arg0) { @Override public void onClick(View arg0) { - mActivity.dynExport(); + mActivity.dynExport(true); } }); @@ -908,7 +911,7 @@ public void onClick(DialogInterface dialog, int buttonId) { new File(mActivity.currSongName+".def.tcf").delete(); new File(mActivity.currSongName+".def.tzf").delete(); } - mActivity.localfinished=false; + mActivity.setLocalFinished(false); mActivity.saveCfgPart2(finalval1, needToRename1); deldefCfg.setEnabled(true); /*Intent new_intent = new Intent(); @@ -934,7 +937,7 @@ public void onClick(DialogInterface dialog, int buttonId) { new_intent.putExtra(getResources().getString(R.string.msrv_outfile), mActivity.currSongName+".def.tcf"); getActivity().sendBroadcast(new_intent); deldefCfg.setEnabled(true);*/ - mActivity.localfinished=false; + mActivity.setLocalFinished(false); mActivity.saveCfgPart2(finalval1, needToRename1); deldefCfg.setEnabled(true); } @@ -1048,6 +1051,5 @@ public void setArt() artsy.setArt(Globals.currArt, getActivity()); } } - } diff --git a/src/com/xperia64/timidityae/PlaylistFragment.java b/src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java similarity index 95% rename from src/com/xperia64/timidityae/PlaylistFragment.java rename to src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java index 248ad50..0f25d22 100755 --- a/src/com/xperia64/timidityae/PlaylistFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java @@ -9,7 +9,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.gui.fragments; import java.io.BufferedReader; import java.io.DataInputStream; @@ -24,8 +24,12 @@ import java.util.Arrays; import java.util.Locale; -import com.xperia64.timidityae.FileBrowserDialog.FileBrowserDialogListener; +import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog; +import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog.FileBrowserDialogListener; +import com.xperia64.timidityae.util.FileComparator; +import com.xperia64.timidityae.util.Globals; import com.xperia64.timidityae.R; +import com.xperia64.timidityae.TimidityActivity; import android.app.AlertDialog; import android.content.Context; @@ -53,13 +57,13 @@ public class PlaylistFragment extends ListFragment implements FileBrowserDialogL ActionPlaylistBackListener mCallback; ArrayList path; ArrayList fname; - ArrayList currPlist; + public ArrayList currPlist; ArrayList vola; - String plistName; + public String plistName; String tmpName; int loki=-1; - int highlightMe = -1; - boolean mode=false; + public int highlightMe = -1; + public boolean mode=false; boolean dontReloadPlist = false; public interface ActionPlaylistBackListener{ public void needPlaylistBackCallback(boolean yes, boolean current); @@ -725,6 +729,6 @@ public void write() } getPlaylists(plistName); - } - + } + } diff --git a/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java b/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java new file mode 100755 index 0000000..c1c4142 --- /dev/null +++ b/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java @@ -0,0 +1,282 @@ +/******************************************************************************* + * Copyright (C) 2014 xperia64 + * + * Copyright (C) 1999-2008 Masanao Izumo + * + * Copyright (C) 1995 Tuukka Toivonen + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Public License v3.0 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/gpl.html + ******************************************************************************/ +package com.xperia64.timidityae.gui.fragments; + +import java.util.ArrayList; +import java.util.List; +import android.annotation.SuppressLint; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.graphics.Color; +import android.os.Build; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.SeekBar.OnSeekBarChangeListener; +import android.widget.ListView; +import android.widget.SeekBar; +import android.widget.Spinner; +import android.widget.AdapterView.OnItemClickListener; + +import com.xperia64.timidityae.JNIHandler; +import com.xperia64.timidityae.R; +import com.xperia64.timidityae.util.Globals; + +public class TrackFragment extends Fragment { + ArrayList localInst = new ArrayList(); + + ArrayList localVol = new ArrayList(); + + // ArrayList JNIHandler.drums = new ArrayList(); + ArrayAdapter fileList; + boolean fromUser; + ListView channelList; + // int bigCounter=6; + AlertDialog ddd; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.track_fragment, container, false); + channelList = (ListView) v.findViewById(R.id.trackList); + return v; + + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + reset(); + + fileList = new ArrayAdapter(getActivity(), R.layout.row); + for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) { + fileList.add(String.format(getActivity().getResources().getString(R.string.trk_form), (getActivity().getResources().getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)), (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i))); + } + channelList.setAdapter(fileList); + channelList.setOnItemClickListener(new OnItemClickListener() { + + @SuppressLint("InflateParams") + @Override + public void onItemClick(AdapterView arg0, View arg1, final int arg2, long arg3) { + AlertDialog.Builder b = new AlertDialog.Builder(getActivity()); + View v = getActivity().getLayoutInflater().inflate(R.layout.track_dialog, null); + final Spinner instSpin = (Spinner) v.findViewById(R.id.instSpin); + instSpin.setClickable(JNIHandler.custInst.get(arg2) && !JNIHandler.drums.get(arg2)); + instSpin.setOnLongClickListener(null); + instSpin.setEnabled(JNIHandler.custInst.get(arg2) && !JNIHandler.drums.get(arg2)); + List arrayAdapter = new ArrayList(); + final int offset = (!JNIHandler.drums.get(arg2)) ? 0 : 34; + if (!JNIHandler.drums.get(arg2)) { + for (String inst : getActivity().getResources().getStringArray(R.array.midi_instruments)) + arrayAdapter.add(inst); + } else { + for (String inst : getActivity().getResources().getStringArray(R.array.midi_drums)) + arrayAdapter.add(inst); + } + ArrayAdapter dataAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, arrayAdapter); + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item); + } else { + dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + } + + dataAdapter.setNotifyOnChange(false); + if (!JNIHandler.drums.get(arg2)) { + instSpin.setAdapter(dataAdapter); + instSpin.setSelection(localInst.get(arg2) - offset); + } + final EditText txtVol = (EditText) v.findViewById(R.id.txtVol); + txtVol.setText(Integer.toString(localVol.get(arg2))); + txtVol.setClickable(JNIHandler.custVol.get(arg2)); + txtVol.setEnabled(JNIHandler.custVol.get(arg2)); + + final SeekBar volSeek = (SeekBar) v.findViewById(R.id.volSeek); + volSeek.setClickable(JNIHandler.custVol.get(arg2)); + volSeek.setEnabled(JNIHandler.custVol.get(arg2)); + volSeek.setMax(127); + volSeek.setProgress(localVol.get(arg2)); + volSeek.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { + + @Override + public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { + if (arg2 && !fromUser) { + fromUser = true; + txtVol.setText(Integer.toString(arg0.getProgress())); + } else { + fromUser = false; + } + } + + @Override + public void onStartTrackingTouch(SeekBar arg0) { + } + + @Override + public void onStopTrackingTouch(SeekBar arg0) { + } + + }); + + txtVol.addTextChangedListener(new TextWatcher() { + public void afterTextChanged(Editable s) { + if (!fromUser) { + if (s.length() > 0) { + int numm = Integer.parseInt(s.toString()); + if (numm > 127) { + fromUser = true; + numm = 127; + } + if (numm < 0) { + fromUser = true; + numm = 0; + } + if (fromUser) { + txtVol.setText(Integer.toString(numm)); + } + fromUser = true; + volSeek.setProgress(numm); + fromUser = false; + } + } else { + fromUser = false; + } + } + + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + }); + final CheckBox inst = (CheckBox) v.findViewById(R.id.defInstr); + inst.setEnabled(!JNIHandler.drums.get(arg2)); + inst.setChecked(!JNIHandler.custInst.get(arg2)); + inst.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton arg0, boolean arg1) { + + instSpin.setClickable(!arg1); + instSpin.setEnabled(!arg1); + } + + }); + final CheckBox vol = (CheckBox) v.findViewById(R.id.defVol); + vol.setChecked(!JNIHandler.custVol.get(arg2)); + // System.out.println("Def inst: + // "+(!JNIHandler.custInst.get(arg2)?"true":"false")+" def vol: + // "+(!JNIHandler.custVol.get(arg2)?"true":"false")); + vol.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton arg0, boolean arg1) { + + volSeek.setClickable(!arg1); + volSeek.setEnabled(!arg1); + txtVol.setClickable(!arg1); + txtVol.setEnabled(!arg1); + } + + }); + if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) + v.setBackgroundColor(Globals.theme == 1 ? Color.WHITE : Color.BLACK); + b.setView(v); + b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + + JNIHandler.custInst.set(arg2, !inst.isChecked()); + JNIHandler.custVol.set(arg2, !vol.isChecked()); + JNIHandler.setChannelVolumeTimidity(arg2 | (JNIHandler.custVol.get(arg2) ? 0x800 : 0x8000), volSeek.getProgress()); + JNIHandler.setChannelTimidity(arg2 | (JNIHandler.custInst.get(arg2) ? 0x800 : 0x8000), instSpin.getSelectedItemPosition()); + if (!JNIHandler.paused && Globals.isPlaying == 0) + JNIHandler.seekTo(JNIHandler.currTime); + // bigCounter=12; + updateList(); + } + }); + + b.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + } + }); + b.setTitle(String.format((getActivity().getResources().getString(R.string.trk_form2)), (arg2 + 1))); + ddd = b.create(); + ddd.show(); + } + + }); + } + + public void reset() { + localInst = new ArrayList(); + localVol = new ArrayList(); + if (ddd != null) { + if (ddd.isShowing()) { + ddd.dismiss(); + ddd = null; + } + } + for (Integer x : JNIHandler.programs) { + localInst.add(x); + } + for (Integer x : JNIHandler.volumes) { + localVol.add(x); + } + } + + public void updateList() { + if (!JNIHandler.type) { + // if(++bigCounter>4) + // { + // bigCounter=0; + boolean needUpdate = false; + + for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) { + if (i < localInst.size()) { + if (localInst.get(i) != JNIHandler.programs.get(i)) { + localInst.set(i, JNIHandler.programs.get(i)); + needUpdate = true; + } + } + if (i < localVol.size()) { + if (localVol.get(i) != JNIHandler.volumes.get(i)) { + localVol.set(i, JNIHandler.volumes.get(i)); + needUpdate = true; + } + } + } + if (needUpdate) { + // System.out.println("Need an update"); + fileList.setNotifyOnChange(false); // Prevents 'clear()' from + // clearing/resetting the + // listview + fileList.clear(); + for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) { + fileList.add(String.format(getActivity().getResources().getString(R.string.trk_form), (getActivity().getResources().getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)), (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i))); + } + fileList.notifyDataSetChanged(); + } + // } + } + } +} diff --git a/src/com/xperia64/timidityae/util/ConfigSaver.java b/src/com/xperia64/timidityae/util/ConfigSaver.java new file mode 100755 index 0000000..57bccd9 --- /dev/null +++ b/src/com/xperia64/timidityae/util/ConfigSaver.java @@ -0,0 +1,211 @@ +package com.xperia64.timidityae.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Locale; + +import com.xperia64.timidityae.R; +import com.xperia64.timidityae.TimidityActivity; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Build; +import android.os.Environment; +import android.text.InputFilter; +import android.text.Spanned; +import android.widget.EditText; +import android.widget.Toast; + +public class ConfigSaver implements TimidityActivity.SpecialAction { + + Activity context; + String currSongName; + AlertDialog alerty; + + public ConfigSaver(Activity context, String currSongName) { + this.context = context; + this.currSongName = currSongName; + } + + boolean localfinished; + + public void saveCfg() { + localfinished = false; + if (Globals.isMidi(currSongName) && Globals.isPlaying == 0) { + AlertDialog.Builder alert = new AlertDialog.Builder(context); + + alert.setTitle("Save Cfg"); + alert.setMessage("Save a MIDI configuration file"); + InputFilter filter = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; + if (IC.contains("*" + source.charAt(i) + "*")) { + return ""; + } + } + return null; + } + }; + // Set an EditText view to get user input + final EditText input = new EditText(context); + input.setFilters(new InputFilter[] { filter }); + alert.setView(input); + + alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + String value = input.getText().toString(); + if (!value.toLowerCase(Locale.US).endsWith(Globals.compressCfg ? ".tzf" : ".tcf")) { + value += (Globals.compressCfg ? ".tzf" : ".tcf"); + } + String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1); + boolean aWrite = true; + boolean alreadyExists = new File(parent + value).exists(); + String needRename = null; + String probablyTheRoot = ""; + String probablyTheDirectory = ""; + try { + new FileOutputStream(parent + value, true).close(); + } catch (FileNotFoundException e) { + aWrite = false; + } catch (IOException e) { + e.printStackTrace(); + } + if (!alreadyExists && aWrite) { + new File(parent + value).delete(); + } + if (aWrite && new File(parent).canWrite()) { + value = parent + value; + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) { + // TODO + // Write the file to getExternalFilesDir, then move it + // with the Uri + // We need to tell JNIHandler that movement is needed. + + String[] tmp = Globals.getDocFilePaths(context, parent); + probablyTheDirectory = tmp[0]; + probablyTheRoot = tmp[1]; + if (probablyTheDirectory.length() > 1) { + needRename = parent.substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value; + value = probablyTheDirectory + '/' + value; + } else { + value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; + return; + } + } else { + value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; + } + final String finalval = value; + final boolean canWrite = aWrite; + final String needToRename = needRename; + final String probRoot = probablyTheRoot; + if (new File(finalval).exists() || (new File(probRoot + needRename).exists() && needToRename != null)) { + AlertDialog dialog2 = new AlertDialog.Builder(context).create(); + dialog2.setTitle("Warning"); + dialog2.setMessage("Overwrite config file?"); + dialog2.setCancelable(false); + dialog2.setButton(DialogInterface.BUTTON_POSITIVE, context.getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (needToRename != null) { + Globals.tryToDeleteFile(context, probRoot + needToRename); + Globals.tryToDeleteFile(context, finalval); + } else { + Globals.tryToDeleteFile(context, finalval); + } + } else { + new File(finalval).delete(); + } + saveCfgPart2(finalval, needToRename); + } + }); + dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, context.getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + } + }); + dialog2.show(); + } else { + saveCfgPart2(finalval, needToRename); + } + } + }); + + alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + // Canceled. + } + }); + + alerty = alert.show(); + } + } + + public void saveCfgPart2(final String finalval, final String needToRename) { + Intent new_intent = new Intent(); + new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), 16); + new_intent.putExtra(context.getResources().getString(R.string.msrv_outfile), finalval); + context.sendBroadcast(new_intent); + final ProgressDialog prog; + prog = new ProgressDialog(context); + prog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + prog.setTitle("Saving CFG"); + prog.setMessage("Saving..."); + prog.setIndeterminate(true); + prog.setCancelable(false); + prog.show(); + new Thread(new Runnable() { + @Override + public void run() { + while (!localfinished && prog.isShowing()) { + try { + + Thread.sleep(25); + } catch (InterruptedException e) { + } + } + + context.runOnUiThread(new Runnable() { + public void run() { + String trueName = finalval; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null && needToRename != null) { + if (Globals.renameDocumentFile(context, finalval, needToRename)) { + trueName = needToRename; + } else { + trueName = "Error"; + } + } + Toast.makeText(context, "Wrote " + trueName, Toast.LENGTH_SHORT).show(); + prog.dismiss(); + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(context.getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(context.getResources().getString(R.string.ta_cmd), 1); + context.sendBroadcast(outgoingIntent); + } + }); + + } + }).start(); + } + + @Override + public AlertDialog getAlertDialog() { + return alerty; + } + + @Override + public void setLocalFinished(boolean localfinished) { + // TODO Auto-generated method stub + this.localfinished = localfinished; + } +} diff --git a/src/com/xperia64/timidityae/FileComparator.java b/src/com/xperia64/timidityae/util/FileComparator.java similarity index 56% rename from src/com/xperia64/timidityae/FileComparator.java rename to src/com/xperia64/timidityae/util/FileComparator.java index 6dc8056..dcc0939 100755 --- a/src/com/xperia64/timidityae/FileComparator.java +++ b/src/com/xperia64/timidityae/util/FileComparator.java @@ -9,30 +9,26 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.util; import java.io.File; import java.text.Collator; import java.util.Comparator; +public class FileComparator implements Comparator { + private Collator c = Collator.getInstance(); - public class FileComparator implements Comparator - { - private Collator c = Collator.getInstance(); + public int compare(Object o1, Object o2) { + if (o1 == o2) + return 0; + File f1 = (File) o1; + File f2 = (File) o2; - public int compare(Object o1, - Object o2) - { - if(o1 == o2) - return 0; - File f1 = (File) o1; - File f2 = (File) o2; + if (f1.isDirectory() && f2.isFile()) + return -1; + if (f1.isFile() && f2.isDirectory()) + return 1; - if(f1.isDirectory() && f2.isFile()) - return -1; - if(f1.isFile() && f2.isDirectory()) - return 1; - - return c.compare(f1.getName(), f2.getName()); + return c.compare(f1.getName(), f2.getName()); } } diff --git a/src/com/xperia64/timidityae/Globals.java b/src/com/xperia64/timidityae/util/Globals.java similarity index 96% rename from src/com/xperia64/timidityae/Globals.java rename to src/com/xperia64/timidityae/util/Globals.java index b41dc27..ac49751 100755 --- a/src/com/xperia64/timidityae/Globals.java +++ b/src/com/xperia64/timidityae/util/Globals.java @@ -9,7 +9,7 @@ * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html ******************************************************************************/ -package com.xperia64.timidityae; +package com.xperia64.timidityae.util; import java.io.BufferedReader; import java.io.DataInputStream; @@ -31,8 +31,10 @@ import javax.net.ssl.HttpsURLConnection; +import com.xperia64.timidityae.JNIHandler; +import com.xperia64.timidityae.ObjectSerializer; import com.xperia64.timidityae.R; - +import com.xperia64.timidityae.TimidityActivity; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; @@ -154,6 +156,21 @@ public static int[] validRates(boolean stereo, boolean sixteen) rates[i]=valid.get(i); return rates; } +public static SparseIntArray validBuffers(int[] rates, boolean stereo, boolean sixteen) +{ + SparseIntArray buffers = new SparseIntArray(); + for(int rate : rates) + { + buffers.put(rate, AudioTrack.getMinBufferSize(rate, (stereo)?AudioFormat.CHANNEL_OUT_STEREO:AudioFormat.CHANNEL_OUT_MONO, (sixteen)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT)); + } + return buffers; + /*HashMap buffers = new HashMap(); + for(int rate : rates) + { + buffers.put(rate, AudioTrack.getMinBufferSize(rate, (stereo)?AudioFormat.CHANNEL_OUT_STEREO:AudioFormat.CHANNEL_OUT_MONO, (sixteen)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT)); + } + return buffers;*/ +} /*public static boolean canWrite(String path) { if(!path.endsWith("/")) @@ -194,23 +211,10 @@ public static int[] validRates(boolean stereo, boolean sixteen) { return false; }*/ -public static SparseIntArray validBuffers(int[] rates, boolean stereo, boolean sixteen) -{ - SparseIntArray buffers = new SparseIntArray(); - for(int rate : rates) - { - buffers.put(rate, AudioTrack.getMinBufferSize(rate, (stereo)?AudioFormat.CHANNEL_OUT_STEREO:AudioFormat.CHANNEL_OUT_MONO, (sixteen)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT)); - } - return buffers; - /*HashMap buffers = new HashMap(); - for(int rate : rates) - { - buffers.put(rate, AudioTrack.getMinBufferSize(rate, (stereo)?AudioFormat.CHANNEL_OUT_STEREO:AudioFormat.CHANNEL_OUT_MONO, (sixteen)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT)); - } - return buffers;*/ -} + public static int probablyFresh=0; +public static final int NOTIFICATION_ID = 13901858; //---------SETTINGS STORAGE---------- public static SharedPreferences prefs; public static boolean firstRun; @@ -238,6 +242,7 @@ public static SparseIntArray validBuffers(int[] rates, boolean stereo, boolean s public static boolean reShuffle = false; public static boolean preserveSilence = true; public static boolean freeInsts = true; +public static boolean phoneState = true; public static void reloadSettings(Activity c, AssetManager assets) { @@ -1159,8 +1164,6 @@ protected String doInBackground(String... sUrl) { #define RC_TOGGLE_MUTE 31 #define RC_SOLO_PLAY 32 #define RC_MUTE_CLEAR 33*/ -//@formatter:on + // @formatter:on - - } diff --git a/src/com/xperia64/timidityae/util/SettingsStorage.java b/src/com/xperia64/timidityae/util/SettingsStorage.java new file mode 100755 index 0000000..0d7d100 --- /dev/null +++ b/src/com/xperia64/timidityae/util/SettingsStorage.java @@ -0,0 +1,5 @@ +package com.xperia64.timidityae.util; + +public class SettingsStorage { + +} diff --git a/src/com/xperia64/timidityae/util/WavSaver.java b/src/com/xperia64/timidityae/util/WavSaver.java new file mode 100755 index 0000000..fcd3468 --- /dev/null +++ b/src/com/xperia64/timidityae/util/WavSaver.java @@ -0,0 +1,232 @@ +package com.xperia64.timidityae.util; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Locale; + +import com.xperia64.timidityae.JNIHandler; +import com.xperia64.timidityae.R; +import com.xperia64.timidityae.TimidityActivity; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.os.Build; +import android.os.Environment; +import android.text.InputFilter; +import android.text.Spanned; +import android.widget.EditText; +import android.widget.Toast; + +public class WavSaver implements TimidityActivity.SpecialAction { + Activity context; + String currSongName; + boolean localfinished; + AlertDialog alerty; + boolean playingExport; // export while playing + + public WavSaver(Activity context, String currSongName, boolean playingExport) { + this.context = context; + this.currSongName = currSongName; + this.playingExport = playingExport; + } + + public void dynExport() { + localfinished = false; + if (Globals.isMidi(currSongName) && (Globals.isPlaying == 0 || !playingExport)) { + + AlertDialog.Builder alert = new AlertDialog.Builder(context); + + alert.setTitle(context.getResources().getString(R.string.dynex_alert1)); + alert.setMessage(context.getResources().getString(R.string.dynex_alert1_msg)); + InputFilter filter = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; + if (IC.contains("*" + source.charAt(i) + "*")) { + return ""; + } + } + return null; + } + }; + final EditText input = new EditText(context); + input.setFilters(new InputFilter[] { filter }); + alert.setView(input); + + alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + String value = input.getText().toString(); + if (!value.toLowerCase(Locale.US).endsWith(".wav")) + value += ".wav"; + String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1); + boolean alreadyExists = new File(parent + value).exists(); + boolean aWrite = true; + String needRename = null; + String probablyTheRoot = ""; + String probablyTheDirectory = ""; + try { + new FileOutputStream(parent + value, true).close(); + } catch (FileNotFoundException e) { + aWrite = false; + } catch (IOException e) { + e.printStackTrace(); + } + + if (aWrite && !alreadyExists) + new File(parent + value).delete(); + + if (aWrite && new File(parent).canWrite()) { + value = parent + value; + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) { + String[] tmp = Globals.getDocFilePaths(context, parent); + probablyTheDirectory = tmp[0]; + probablyTheRoot = tmp[1]; + if (probablyTheDirectory.length() > 1) { + needRename = parent.substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value; + value = probablyTheDirectory + '/' + value; + } else { + value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; + } + } else { + value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; + } + final String finalval = value; + final boolean canWrite = aWrite; + final String needToRename = needRename; + final String probRoot = probablyTheRoot; + if (new File(finalval).exists() || (new File(probRoot + needRename).exists() && needToRename != null)) { + AlertDialog dialog2 = new AlertDialog.Builder(context).create(); + dialog2.setTitle(context.getResources().getString(R.string.warning)); + dialog2.setMessage(context.getResources().getString(R.string.dynex_alert2_msg)); + dialog2.setCancelable(false); + dialog2.setButton(DialogInterface.BUTTON_POSITIVE, context.getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (needToRename != null) { + Globals.tryToDeleteFile(context, probRoot + needToRename); + Globals.tryToDeleteFile(context, finalval); + } else { + Globals.tryToDeleteFile(context, finalval); + } + } else { + new File(finalval).delete(); + } + saveWavPart2(finalval, needToRename); + } + }); + dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, context.getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + } + }); + dialog2.show(); + } else { + saveWavPart2(finalval, needToRename); + } + + } + }); + + alert.setNegativeButton(context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + // Canceled. + } + }); + + alerty = alert.show(); + + } + } + + public void saveWavPart2(final String finalval, final String needToRename) { + Intent new_intent = new Intent(); + new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); + new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), playingExport ? 15 : 14); + if (!playingExport) { + new_intent.putExtra(context.getResources().getString(R.string.msrv_infile), currSongName); + } + new_intent.putExtra(context.getResources().getString(R.string.msrv_outfile), finalval); + context.sendBroadcast(new_intent); + final ProgressDialog prog; + prog = new ProgressDialog(context); + prog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + prog.setTitle("Converting to WAV"); + prog.setMessage("Converting..."); + prog.setIndeterminate(false); + prog.setCancelable(false); + prog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + prog.show(); + new Thread(new Runnable() { + @Override + public void run() { + while (!localfinished && prog.isShowing()) { + prog.setMax(JNIHandler.maxTime); + prog.setProgress(JNIHandler.currTime); + try { + + Thread.sleep(25); + } catch (InterruptedException e) { + } + } + if (!localfinished) { + JNIHandler.stop(); + context.runOnUiThread(new Runnable() { + public void run() { + Toast.makeText(context, "Conversion canceled", Toast.LENGTH_SHORT).show(); + if (!Globals.keepWav) { + if (new File(finalval).exists()) + new File(finalval).delete(); + } else { + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(context.getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(context.getResources().getString(R.string.ta_cmd), 1); + context.sendBroadcast(outgoingIntent); + } + } + }); + + } else { + context.runOnUiThread(new Runnable() { + public void run() { + String trueName = finalval; + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null && needToRename != null) { + if (Globals.renameDocumentFile(context, finalval, needToRename)) { + trueName = needToRename; + } else { + trueName = "Error"; + } + } + Toast.makeText(context, "Wrote " + trueName, Toast.LENGTH_SHORT).show(); + prog.dismiss(); + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(context.getResources().getString(R.string.ta_rec)); + outgoingIntent.putExtra(context.getResources().getString(R.string.ta_cmd), 1); + context.sendBroadcast(outgoingIntent); + } + }); + } + } + }).start(); + } + + @Override + public AlertDialog getAlertDialog() { + // TODO Auto-generated method stub + return alerty; + } + + @Override + public void setLocalFinished(boolean localfinished) { + // TODO Auto-generated method stub + this.localfinished = localfinished; + } +} diff --git a/src/com/xperia64/timidityae/util/WavWriter.java b/src/com/xperia64/timidityae/util/WavWriter.java new file mode 100755 index 0000000..67cb0a9 --- /dev/null +++ b/src/com/xperia64/timidityae/util/WavWriter.java @@ -0,0 +1,124 @@ +package com.xperia64.timidityae.util; + +import java.io.BufferedOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.RandomAccessFile; + +public class WavWriter { + public boolean writeToFile = false; + public long filesize = 0; + public String fileToWrite = ""; + public boolean finishedWriting = false; + public boolean dataWritten = false; + public DataOutputStream outFile; + + boolean bitSize; + boolean mono; + long sampleRate; + + private byte[] intToByteArray(int i) { + byte[] b = new byte[4]; + b[0] = (byte) (i & 0xFF); + b[1] = (byte) ((i >> 8) & 0xFF); + b[2] = (byte) ((i >> 16) & 0xFF); + b[3] = (byte) ((i >> 24) & 0xFF); + return b; + } + + private byte[] shortToByteArray(short data) { + return new byte[] { (byte) (data & 0xff), (byte) ((data >>> 8) & 0xff) }; + } + + public void setupOutputFile(String filename, boolean bitSize, boolean mono, long sampleRate) { + this.bitSize = bitSize; + this.sampleRate = sampleRate; + this.mono = mono; + writeToFile = true; + finishedWriting = false; + fileToWrite = filename; + filesize = 0; + try { + long mySubChunk1Size = 16; + int myBitsPerSample = (bitSize ? 16 : 8); + int myFormat = 1; + long myChannels = ((mono) ? 1 : 2); + long mySampleRate = sampleRate; + long myByteRate = mySampleRate * myChannels * myBitsPerSample / 8; + int myBlockAlign = (int) (myChannels * myBitsPerSample / 8); + + // byte[] clipData = getBytesFromFile(fileToConvert); + + // long myDataSize = clipData.length; // this changes + // long myChunk2Size = myDataSize * myChannels * myBitsPerSample/8; + // long myChunkSize = 36 + myChunk2Size; + + OutputStream os; + os = new FileOutputStream(new File(fileToWrite)); + BufferedOutputStream bos = new BufferedOutputStream(os); + outFile = new DataOutputStream(bos); + + outFile.writeBytes("RIFF"); // 00 - RIFF + outFile.write(intToByteArray(0/* (int)myChunkSize */), 0, 4); // 04 - how big is the rest of this file? + outFile.writeBytes("WAVE"); // 08 - WAVE + outFile.writeBytes("fmt "); // 12 - fmt + outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk + outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation + outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???) + outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second) + outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second + outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels + outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24 + outFile.writeBytes("data"); // 36 - data + outFile.write(intToByteArray(0/* (int)myChunkSize */), 0, 4); // 40 - how big is this data chunk + // outFile.write(clipData); // 44 - the actual data itself - just a long string of numbers + + // outFile.flush(); + // outFile.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void finishOutput() { + try { + outFile.flush(); + outFile.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + finishedWriting = true; + long myDataSize = filesize; // this changes + int myBitsPerSample = (bitSize ? 16 : 8); + long myChannels = ((mono) ? 1 : 2); + long myChunk2Size = myDataSize * myChannels * myBitsPerSample / 8; + long myChunkSize = 36 + myChunk2Size; + + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(fileToWrite, "rw"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + try { + raf.seek(04); + raf.write(intToByteArray((int) myChunkSize)); + raf.seek(40); + raf.write(intToByteArray((int) myDataSize)); + raf.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void write(byte[] data, int offset, int length) throws IOException { + filesize += length; + outFile.write(data, offset, length); + } +} From 97588f8f64290f4e8bfec9d7e34ba6923e009485 Mon Sep 17 00:00:00 2001 From: xperia64 Date: Sun, 13 Dec 2015 18:30:42 -0500 Subject: [PATCH 02/20] 3.0 refactoring --- AndroidManifest.xml | 2 +- res/values/strings.xml | 26 +- .../xperia64/timidityae/DummyActivity.java | 7 +- src/com/xperia64/timidityae/JNIHandler.java | 128 +- src/com/xperia64/timidityae/MusicService.java | 1849 ++++++++--------- .../xperia64/timidityae/SettingsActivity.java | 46 +- .../xperia64/timidityae/TimidityActivity.java | 195 +- .../gui/TimidityAEWidgetProvider.java | 26 +- .../gui/dialogs/FileBrowserDialog.java | 176 +- .../gui/fragments/FileBrowserFragment.java | 52 +- .../gui/fragments/LyricFragment.java | 9 +- .../gui/fragments/PlayerFragment.java | 1149 +++++----- .../gui/fragments/PlaylistFragment.java | 1018 +++++---- .../gui/fragments/TrackFragment.java | 45 +- .../timidityae/util/CommandStrings.java | 89 + .../xperia64/timidityae/util/ConfigSaver.java | 206 +- .../timidityae/util/DocumentFileUtils.java | 212 ++ src/com/xperia64/timidityae/util/Globals.java | 762 +------ .../{ => util}/ObjectSerializer.java | 2 +- .../timidityae/util/SettingsStorage.java | 456 ++++ .../xperia64/timidityae/util/WavSaver.java | 51 +- 21 files changed, 3174 insertions(+), 3332 deletions(-) create mode 100755 src/com/xperia64/timidityae/util/CommandStrings.java create mode 100755 src/com/xperia64/timidityae/util/DocumentFileUtils.java rename src/com/xperia64/timidityae/{ => util}/ObjectSerializer.java (95%) diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 2a2ccf8..6852a27 100755 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -828,7 +828,7 @@ android:finishOnTaskLaunch="true" android:name="com.xperia64.timidityae.MusicService"> - diff --git a/res/values/strings.xml b/res/values/strings.xml index 3939be2..5da1dd4 100755 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -181,31 +181,7 @@ - - -com.xperia64.timidityae.MusicService_RECEIVER -com.xperia64.timidityae.MusicService_CMD -com.xperia64.timidityae.MusicService_SONGNUM -com.xperia64.timidityae.MusicService_CURRFOLD -com.xperia64.timidityae.MusicService_Begin -com.xperia64.timidityae.MusicService_LoopMode -com.xperia64.timidityae.MusicService_ShuffleMode -com.xperia64.timidityae.MusicService_SeekTime -com.xperia64.timidityae.MusicService_InputFile -com.xperia64.timidityae.MusicService_OutputFile -com.xperia64.timidityae.MusicService_Reset -com.xperia64.timidityae.MusicService_DontLoadPlist - -com.xperia64.timidityae.TimidityActivity_RECEIVER -com.xperia64.timidityae.TimidityActivity_CMD -com.xperia64.timidityae.TimidityActivity_FileName -com.xperia64.timidityae.TimidityActivity_StartTime -com.xperia64.timidityae.TimidityActivity_SongTitle -com.xperia64.timidityae.TimidityActivity_CurrPath -com.xperia64.timidityae.TimidityActivity_ShuffleMode -com.xperia64.timidityae.TimidityActivity_LoopMode -com.xperia64.timidityae.TimidityActivity_Pause -com.xperia64.timidityae.TimidityActivity_PauseArg + diff --git a/src/com/xperia64/timidityae/DummyActivity.java b/src/com/xperia64/timidityae/DummyActivity.java index 9e62774..f17ab5e 100755 --- a/src/com/xperia64/timidityae/DummyActivity.java +++ b/src/com/xperia64/timidityae/DummyActivity.java @@ -10,8 +10,9 @@ public void onCreate( Bundle potato ) { // Really Google? This bug is still present in Lollipop. // I should not have to create an Activity just to keep my service alive. super.onCreate( potato ); - this.finish(); // With and without this something breaks. With, it - // closes the task manager. Without, volume buttons - // break and lag occurs. + // With and without this something breaks. + // With, it closes the task manager. + // Without, volume buttons break and lag occurs. + this.finish(); } } \ No newline at end of file diff --git a/src/com/xperia64/timidityae/JNIHandler.java b/src/com/xperia64/timidityae/JNIHandler.java index 6b50d2b..3eeda63 100755 --- a/src/com/xperia64/timidityae/JNIHandler.java +++ b/src/com/xperia64/timidityae/JNIHandler.java @@ -57,12 +57,12 @@ public class JNIHandler { public static int maxTime = 0; public static int currTime = 0; public static boolean paused = false; - public static boolean type = true; // true = mediaplayer, false = audiotrack - public static int monoop; - public static boolean bits; + public static boolean isMediaPlayerFormat = true; // true = mediaplayer, false = audiotrack + public static int channelMode; // 0 = mono (downmixed), 1 = mono (synthesized), 2 = stereo + public static boolean sixteenBit; public static int rate; public static int buffer; - public static int alternativeCheck = 555555; // VVVVVV=OK. + // Timidity Stuff public static int MAX_CHANNELS = 32; public static int currsamp = 0; @@ -75,17 +75,24 @@ public class JNIHandler { public static int overwriteLyricAt = 0; public static int threadedError = 0; public static int exceptional = 0; - public static int ttr; - public static int tt; + public static int playbackPercentage; + public static int playbackTempo; // This number is not the tempo in BPM, but some number that can be used to calculate the real tempo public static int tb = 0; public static int voice; public static int maxvoice = 256; - public static int koffset = 0; + public static int keyOffset = 0; // public static boolean breakLoops = false; public static boolean dataWritten = false; public static boolean shouldPlayNow = true; - public static int ultSafetyCheck = 1; + + + + + public static boolean finishedCallbackCheck = true; // Is set + public static boolean isPlaying = false; // Active low. + public static boolean isBlocking = false; // false = not currently blocking, true = blocking. Makes sure timidity actually returned. + // public static ArrayList lyricLines; // End Timidity Stuff @@ -95,10 +102,10 @@ public class JNIHandler { public static void pause() // or unpause. { - if (Globals.isPlaying == 0) { + if (isPlaying) { if (paused) { paused = false; - if (type) { + if (isMediaPlayerFormat) { mMediaPlayer.start(); } else { controlTimidity(7, 0); @@ -112,7 +119,7 @@ public static void pause() // or unpause. } } else { paused = true; - if (type) { + if (isMediaPlayerFormat) { mMediaPlayer.pause(); } else { controlTimidity(7, 0); @@ -129,22 +136,22 @@ public static void pause() // or unpause. } public static void stop() { - if (type) { + if (isMediaPlayerFormat) { mMediaPlayer.setOnCompletionListener(null); try { mMediaPlayer.stop(); } catch (IllegalStateException e) { } - Globals.isPlaying = 1; - ultSafetyCheck = 1; - alternativeCheck = 555555; + isPlaying = false; + finishedCallbackCheck = true; + isBlocking = false; } else { controlTimidity(30, 0); } } public static void seekTo(int time) { - if (type) { + if (isMediaPlayerFormat) { mMediaPlayer.seekTo(time); } else { controlTimidity(6, time); @@ -157,7 +164,7 @@ public static void waitUntilReady() { } public static void waitUntilReady(int interval) { - while (!JNIHandler.timidityReady()) { + while (!timidityReady()) { try { Thread.sleep(interval); } catch (InterruptedException e) { @@ -170,7 +177,7 @@ public static void waitForStop() { } public static void waitForStop(int interval) { - while (Globals.isPlaying == 0 || alternativeCheck == 333333 || ultSafetyCheck == 0) { + while (isPlaying || isBlocking || !finishedCallbackCheck) { try { Thread.sleep(interval); } catch (InterruptedException e) { @@ -180,16 +187,16 @@ public static void waitForStop(int interval) { public static void setupOutputFile(String filename) { currentWavWriter = new WavWriter(); - currentWavWriter.setupOutputFile(filename, bits, (monoop < 2), rate); + currentWavWriter.setupOutputFile(filename, sixteenBit, (channelMode < 2), rate); } public static void buffit(byte[] data, int length) { dataWritten = true; if (shouldPlayNow) { - if (monoop == 0) { + if (channelMode == 0) { byte[] mono = new byte[length / 2]; - if (bits) { + if (sixteenBit) { for (int i = 0; i < mono.length / 2; ++i) { int HI = 1; int LO = 0; @@ -251,15 +258,15 @@ public static int init(String path, String file, int mono, int resamp, boolean s custInst.add(false); custVol.add(false); } - monoop = mono; - bits = sixteen; + channelMode = mono; + sixteenBit = sixteen; rate = r; buffer = b; if (mMediaPlayer == null) mMediaPlayer = new MediaPlayer(); prepared = true; - return prepareTimidity(path, path + file, (monoop == 1) ? 1 : 0, resamp, bits ? 1 : 0, preserveSilence ? 1 : 0, reloading ? 1 : 0, freeInsts ? 1 : 0); + return prepareTimidity(path, path + file, (channelMode == 1) ? 1 : 0, resamp, sixteenBit ? 1 : 0, preserveSilence ? 1 : 0, reloading ? 1 : 0, freeInsts ? 1 : 0); } else { // Log.w("Warning", "Attempt to prepare again cancelled."); return -99; @@ -269,16 +276,16 @@ public static int init(String path, String file, int mono, int resamp, boolean s static Thread t; public static int play(final String songTitle) { + if (new File(songTitle).exists()) { - - if (alternativeCheck == 555555) { - koffset = 0; + if (isBlocking == false) { + keyOffset = 0; tb = 0; currentLyric = ""; overwriteLyricAt = 0; - Globals.isPlaying = 0; - ultSafetyCheck = 0; - type = false; + isPlaying = true; + finishedCallbackCheck = false; + isMediaPlayerFormat = false; paused = false; dataWritten = false; shouldPlayNow = true; @@ -287,7 +294,7 @@ public static int play(final String songTitle) { custVol.set(i, false); } if (!Globals.isMidi(songTitle)) { - type = true; + isMediaPlayerFormat = true; try { mMediaPlayer.setOnCompletionListener(null); mMediaPlayer.reset(); @@ -301,16 +308,16 @@ public void onPrepared(MediaPlayer arg0) { }); mMediaPlayer.prepare(); mMediaPlayer.start(); - alternativeCheck = 333333; + isBlocking = true; mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { arg0.setOnCompletionListener(null); - Globals.isPlaying = 1; - ultSafetyCheck = 1; - alternativeCheck = 555555; + isPlaying = false; + finishedCallbackCheck = true; + isBlocking = false; } }); @@ -325,18 +332,22 @@ public void onCompletion(MediaPlayer arg0) { // timidity stuff for black midi. t = new Thread(new Runnable() { public void run() { - alternativeCheck = 333333; - mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, rate, (monoop == 2) ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO, (bits) ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT, buffer, AudioTrack.MODE_STREAM); + isBlocking = true; + mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, rate, + (channelMode == 2) ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO, + (sixteenBit) ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT, + buffer, AudioTrack.MODE_STREAM); if (!(currentWavWriter != null && !currentWavWriter.finishedWriting)) + { try { mAudioTrack.play(); } catch (Exception e) { exceptional |= 1; } - - alternativeCheck = loadSongTimidity(songTitle); - alternativeCheck = 555555; + } + loadSongTimidity(songTitle); + isBlocking = false; if (currentWavWriter != null && !currentWavWriter.finishedWriting) currentWavWriter.finishOutput(); @@ -406,26 +417,25 @@ public static void controlMe(int y) { } public static int bufferSize() { + // If a wav file is currently being written, + // tell timidity it is doing a great job at playing in realtime + // to avoid cutting off notes and such. if (currentWavWriter != null && !currentWavWriter.finishedWriting) { return 0; } try { - - return (((int) (mAudioTrack.getPlaybackHeadPosition() * mAudioTrack.getChannelCount() * (2 - (mAudioTrack.getAudioFormat() & 1))))); // # - // of - // frames - // *4 - // = - // comparison - // factor + // Samples * Number of Channels * sample size + return (((int) (mAudioTrack.getPlaybackHeadPosition() * + mAudioTrack.getChannelCount() * + (2 - (mAudioTrack.getAudioFormat() & 1))))); // 16 bit is 2, 8 bit is 3. We should never have to worry about 4, which is floating. } catch (IllegalStateException e) { return 0; } } public static void finishIt() { - ultSafetyCheck = 1; - Globals.isPlaying = 1; + finishedCallbackCheck = true; + isPlaying = false; } public static void flushIt() { @@ -448,9 +458,9 @@ public static int getRate() { public static void updateLyrics(byte[] b) { final StringBuilder stb = new StringBuilder(currentLyric); final StringBuilder tmpBuild = new StringBuilder(); - boolean isNormalLyric = b[0] == 'L'; - boolean isNewline = b[0] == 'N'; - boolean isComment = b[0] == 'Q'; + boolean isNormalLyric = (b[0] == 'L'); + boolean isNewline = (b[0] == 'N'); + boolean isComment = (b[0] == 'Q'); for (int i = 2; i < b.length; i++) { if (b[i] == 0) @@ -495,19 +505,25 @@ public static void updateDrumInfo(int ch, int isDrum) { drums.set(ch, (isDrum != 0)); } + // Called by native. Do not rename or modify declaration. public static void updateTempo(int t, int tr) { - tt = t; - ttr = tr; + playbackTempo = t; + playbackPercentage = tr; + System.out.println("T: "+t+" tr "+tr); // TODO something // int x = (int) (500000 / (double) t * 120 * (double) tr / 100 + 0.5); // System.out.println("T: "+t+ " TR: "+tr+" X: "+x); } + // Called by native. Do not rename or modify declaration. public static void updateMaxVoice(int vvv) { maxvoice = vvv; } + // Called by native. Do not rename or modify declaration. public static void updateKey(int k) { - koffset = k; + keyOffset = k; } + + } diff --git a/src/com/xperia64/timidityae/MusicService.java b/src/com/xperia64/timidityae/MusicService.java index c02eb63..0368d35 100755 --- a/src/com/xperia64/timidityae/MusicService.java +++ b/src/com/xperia64/timidityae/MusicService.java @@ -31,6 +31,9 @@ import com.xperia64.timidityae.R; import com.xperia64.timidityae.gui.TimidityAEWidgetProvider; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.ObjectSerializer; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; import android.annotation.SuppressLint; import android.app.Notification; @@ -56,32 +59,33 @@ import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.TextUtils; +import android.util.Log; import android.util.SparseIntArray; //import android.util.Log; import android.view.KeyEvent; import android.widget.RemoteViews; import android.widget.Toast; -public class MusicService extends Service{ +public class MusicService extends Service { public ArrayList playList; public SparseIntArray shuffledIndices; public SparseIntArray reverseShuffledIndices; // HashMap - public int currSongNumber=-1; - public int realSongNumber=-1; + public int currSongNumber = -1; + public int realSongNumber = -1; public boolean shouldStart; - public boolean shouldAdvance=true; + public boolean shouldAdvance = true; public String currFold; - public int loopMode=1; - public int shuffleMode=0; + public int loopMode = 1; + public int shuffleMode = 0; public boolean paused; - public boolean fullStop=false; - public boolean foreground=false; + public boolean fullStop = false; + public boolean foreground = false; public boolean fixedShuffle = true; - boolean death=false; - boolean phonepause=false; + boolean death = false; + boolean phonepause = false; PowerManager.WakeLock wl; - boolean shouldDoWidget=true; + boolean shouldDoWidget = true; int[] widgetIds; String currTitle; Notification mainNotification; @@ -89,592 +93,537 @@ public class MusicService extends Service{ RemoteViews remoteViews; Random random = new Random(System.currentTimeMillis()); private final IBinder musicBind = new MusicBinder(); + @Override - public IBinder onBind(Intent arg0) - { + public IBinder onBind(Intent arg0) { return musicBind; } - - public class MusicBinder extends Binder - { - MusicService getService() - { + + public class MusicBinder extends Binder { + MusicService getService() { return MusicService.this; } } - + private Handler handler; - + @SuppressLint("NewApi") @Override - public void onTaskRemoved( Intent rootIntent ) { - Intent intent = new Intent( this, DummyActivity.class ); - intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); - startActivity( intent ); - super.onTaskRemoved(rootIntent); + public void onTaskRemoved(Intent rootIntent) { + Intent intent = new Intent(this, DummyActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + super.onTaskRemoved(rootIntent); } + @Override public int onStartCommand(Intent intent, int flags, int startId) { - handler = new Handler(); - return START_NOT_STICKY; - // return super.onStartCommand(intent, flags, startId); + handler = new Handler(); + return START_NOT_STICKY; + // return super.onStartCommand(intent, flags, startId); } - PhoneStateListener phoneStateListener = new PhoneStateListener() { - @Override - public void onCallStateChanged(int state, String incomingNumber) { - if (state == TelephonyManager.CALL_STATE_RINGING) { - //Incoming call: Pause music - if(Globals.isPlaying==0&&!JNIHandler.paused&&!phonepause&&!(JNIHandler.currentWavWriter!=null&&!JNIHandler.currentWavWriter.finishedWriting)) - { - phonepause=true; - pause(); - } - } else if(state == TelephonyManager.CALL_STATE_IDLE) { - //Not in call: Play music - if(Globals.isPlaying==0&&JNIHandler.paused&&phonepause) - { - phonepause=false; - pause(); - } - } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) { - //A call is dialing, active or on hold - } - super.onCallStateChanged(state, incomingNumber); - } - }; - public void genShuffledPlist() - { - shuffledIndices = new SparseIntArray(); - reverseShuffledIndices = new SparseIntArray(); - ArrayList tmp = new ArrayList(); - for(int i = 0; i tmp = new ArrayList(); + for (int i = 0; i < playList.size(); i++) { + tmp.add(i); + } + Collections.shuffle(tmp); + + for (int i = 0; i < playList.size(); i++) { + shuffledIndices.put(i, tmp.get(i)); + reverseShuffledIndices.put(tmp.get(i), i); + } } + } - private BroadcastReceiver serviceReceiver = new BroadcastReceiver() { - @SuppressWarnings("unchecked") - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) - { - KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); - if(event.getAction() == KeyEvent.ACTION_DOWN) - { - switch(event.getKeyCode()) - { - case KeyEvent.KEYCODE_MEDIA_PLAY: - case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: - case KeyEvent.KEYCODE_MEDIA_PAUSE: - if(Globals.isPlaying==0) - { - pause(); - }else{ - play(); - } - break; - case KeyEvent.KEYCODE_MEDIA_NEXT: - shouldAdvance=false; - next(); - break; - case KeyEvent.KEYCODE_MEDIA_PREVIOUS: - shouldAdvance=false; - previous(); - break; - case KeyEvent.KEYCODE_MEDIA_STOP: - fullStop=true; - shouldAdvance=false; - stop(); - break; - } - } - }else if(Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) - { - if (intent.hasExtra("state")){ - if (intent.getIntExtra("state", 0) == 0){ - if (Globals.isPlaying==0){ - if(!JNIHandler.paused) - { - pause(); - } - } - } - } - }else{ - int cmd = intent.getIntExtra(getResources().getString(R.string.msrv_cmd), -5); // V - //System.out.println("Cmd received: "+cmd); - - // Sigh. Here we go: - Intent outgoingIntent = new Intent(); - switch(cmd) - { - case 0: // We have a new playlist. Load it and the immediate song to load. - death=true; - ArrayList tmpList = Globals.plist; - if(tmpList==null) - { - break; - } - int tmpNum = intent.getIntExtra(getResources().getString(R.string.msrv_songnum), -1); - if(tmpNum<=-1) - { - break; - } - boolean shouldNotLoadPlist = intent.getBooleanExtra(getResources().getString(R.string.msrv_dlplist), false); - if(shouldNotLoadPlist) - { - currSongNumber = tmpNum; - if(shuffleMode == 1) - { - realSongNumber = shuffledIndices.get(tmpNum); - } - }else{ - currSongNumber=realSongNumber=tmpNum; - playList=tmpList; - genShuffledPlist(); - } - Globals.plist=null; - tmpList=null; - currFold=intent.getStringExtra(getResources().getString(R.string.msrv_currfold)); - - if(shuffleMode == 1 && !shouldNotLoadPlist) - { - currSongNumber = reverseShuffledIndices.get(realSongNumber); - } - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 4); - if(shuffleMode == 1) - { - Globals.tmpplist=new ArrayList(); - for(int i = 0; i2) - break; - loopMode=tmpMode; - break; - case 7: // Shuffle mode - shuffleMode = intent.getIntExtra(getResources().getString(R.string.msrv_shufmode), 0); - if(shuffleMode == 1) - { - fixedShuffle = false; - if(Globals.reShuffle||reverseShuffledIndices==null||shuffledIndices==null) - { - genShuffledPlist(); - - } - currSongNumber = reverseShuffledIndices.get(currSongNumber); - }else{ - if(!fixedShuffle) - { - currSongNumber = realSongNumber; - fixedShuffle = true; - } - } - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 4); - if(shuffleMode == 1) - { - Globals.tmpplist=new ArrayList(); - for(int i = 0; i(); - for(int i = 0; i tmpList = Globals.plist; + if (tmpList == null) { + break; + } + int tmpNum = intent.getIntExtra(CommandStrings.msrv_songnum, -1); + if (tmpNum <= -1) { + break; + } + boolean shouldNotLoadPlist = intent.getBooleanExtra(CommandStrings.msrv_dlplist, false); + if (shouldNotLoadPlist) { + currSongNumber = tmpNum; + if (shuffleMode == 1) { + realSongNumber = shuffledIndices.get(tmpNum); + } + } else { + currSongNumber = realSongNumber = tmpNum; + playList = tmpList; + genShuffledPlist(); + } + Globals.plist = null; + tmpList = null; + currFold = intent.getStringExtra(CommandStrings.msrv_currfold); + + if (shuffleMode == 1 && !shouldNotLoadPlist) { + currSongNumber = reverseShuffledIndices.get(realSongNumber); + } + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_copy_plist); + if (shuffleMode == 1) { + Globals.tmpplist = new ArrayList(); + for (int i = 0; i < playList.size(); i++) { + Globals.tmpplist.add(playList.get(shuffledIndices.get(i))); + } + } else { + Globals.tmpplist = playList; + } + sendBroadcast(outgoingIntent); + // if(shouldStart=intent.getBooleanExtra(ServiceStrings.msrv_begin),false)||true) + // { + play(); + // } + break; + case CommandStrings.msrv_cmd_play: // Initial play cmd + play(); + break; + case CommandStrings.msrv_cmd_pause: // Play/pause + pause(); + break; + case CommandStrings.msrv_cmd_next: // Next + shouldAdvance = false; + next(); + break; + case CommandStrings.msrv_cmd_prev: // Previous + shouldAdvance = false; + previous(); + break; + case CommandStrings.msrv_cmd_stop: // Stop + fullStop = true; + Globals.hardStop = true; + shouldAdvance = false; + stop(); + break; + case CommandStrings.msrv_cmd_loop_mode: // Loop mode + int tmpMode = intent.getIntExtra(CommandStrings.msrv_loopmode, -1); + if (tmpMode < 0 || tmpMode > 2) + break; + loopMode = tmpMode; + break; + case CommandStrings.msrv_cmd_shuf_mode: // Shuffle mode + if (playList == null) { + break; + } + shuffleMode = intent.getIntExtra(CommandStrings.msrv_shufmode, 0); + if (shuffleMode == 1) { + fixedShuffle = false; + if (SettingsStorage.reShuffle || reverseShuffledIndices == null || shuffledIndices == null) { + genShuffledPlist(); + } + if (reverseShuffledIndices == null) { + break; + } + currSongNumber = reverseShuffledIndices.get(currSongNumber); + } else { + if (!fixedShuffle) { + currSongNumber = realSongNumber; + fixedShuffle = true; + } + } + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_copy_plist); + if (shuffleMode == 1) { + Globals.tmpplist = new ArrayList(); + for (int i = 0; i < playList.size(); i++) { + Globals.tmpplist.add(playList.get(shuffledIndices.get(i))); + } + } else { + Globals.tmpplist = playList; + } + sendBroadcast(outgoingIntent); + break; + /*case ServiceStrings.msrv_cmd_req_time: // Request seekBar times + break;*/ + case CommandStrings.msrv_cmd_seek: // Actually seek + JNIHandler.seekTo(intent.getIntExtra(CommandStrings.msrv_seektime, 1)); + break; + case CommandStrings.msrv_cmd_get_fold: // Request current folder + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_load_filebrowser); + outgoingIntent.putExtra(CommandStrings.ta_currpath, currFold); + sendBroadcast(outgoingIntent); + break; + case CommandStrings.msrv_cmd_get_info: // Request player info + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_gui_play_full); + outgoingIntent.putExtra(CommandStrings.ta_startt, JNIHandler.maxTime); + outgoingIntent.putExtra(CommandStrings.ta_shufmode, shuffleMode); + outgoingIntent.putExtra(CommandStrings.ta_loopmode, loopMode); + outgoingIntent.putExtra(CommandStrings.ta_songttl, currTitle); + if (shuffleMode == 1) { + outgoingIntent.putExtra(CommandStrings.ta_filename, playList.get(shuffledIndices.get(currSongNumber))); + } else { + outgoingIntent.putExtra(CommandStrings.ta_filename, playList.get(currSongNumber)); + } + + sendBroadcast(outgoingIntent); + break; + case CommandStrings.msrv_cmd_get_plist: // Request playlist + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_copy_plist); + if (shuffleMode == 1) { + Globals.tmpplist = new ArrayList(); + for (int i = 0; i < playList.size(); i++) { + Globals.tmpplist.add(playList.get(shuffledIndices.get(i))); + } + } else { + Globals.tmpplist = playList; + } + sendBroadcast(outgoingIntent); + break; + case CommandStrings.msrv_cmd_play_or_pause: + if (JNIHandler.isPlaying) { + pause(); + } else { + play(); + } + break; + case CommandStrings.msrv_cmd_write_new: // We want to write an output file + fullStop = true; + shouldAdvance = false; + Globals.hardStop = true; + stop(); + while (((JNIHandler.isPlaying || JNIHandler.isBlocking))) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + final String input = intent.getStringExtra(CommandStrings.msrv_infile); + String output = intent.getStringExtra(CommandStrings.msrv_outfile); + if (input != null && output != null) { + JNIHandler.setupOutputFile(output); + JNIHandler.play(input); + } + new Thread(new Runnable() { @Override - public void run() - { - while(!death&&((Globals.isPlaying==1))) - { - if(JNIHandler.alternativeCheck==555555) - { - death=true; + public void run() { + while (!death && ((!JNIHandler.isPlaying))) { + if (!JNIHandler.isBlocking) { + death = true; } - try {Thread.sleep(10);} catch (InterruptedException e){}} - if(new File(input+".def.tcf").exists() || new File(input+".def.tzf").exists()) - { - String suffix; - if(new File(input+".def.tcf").exists() && new File(input+".def.tzf").exists()) - { - suffix = (Globals.compressCfg?".def.tzf":".def.tcf"); - }else if(new File(input+".def.tcf").exists()){ - suffix = ".def.tcf"; - }else{ - suffix = ".def.tzf"; - } - JNIHandler.shouldPlayNow=false; - JNIHandler.currTime=0; - while(Globals.isPlaying==0&&!death&&!JNIHandler.dataWritten) - { - try - { - Thread.sleep(25); - } catch (InterruptedException e){ - e.printStackTrace(); - } + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + } + if (new File(input + ".def.tcf").exists() || new File(input + ".def.tzf").exists()) { + String suffix; + if (new File(input + ".def.tcf").exists() && new File(input + ".def.tzf").exists()) { + suffix = (SettingsStorage.compressCfg ? ".def.tzf" : ".def.tcf"); + } else if (new File(input + ".def.tcf").exists()) { + suffix = ".def.tcf"; + } else { + suffix = ".def.tzf"; + } + JNIHandler.shouldPlayNow = false; + JNIHandler.currTime = 0; + while (JNIHandler.isPlaying && !death && !JNIHandler.dataWritten) { + try { + Thread.sleep(25); + } catch (InterruptedException e) { + e.printStackTrace(); } - Intent outgoingIntent = new Intent(); // silly, but should be done async. I think. - outgoingIntent.setAction(getResources().getString(R.string.msrv_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.msrv_cmd), 17); - outgoingIntent.putExtra(getResources().getString(R.string.msrv_infile),input+suffix); - outgoingIntent.putExtra(getResources().getString(R.string.msrv_reset),true); - sendBroadcast(outgoingIntent); - } - while(((Globals.isPlaying==0))) - { - try {Thread.sleep(25);} catch (InterruptedException e){} - } - - System.out.println("Finished playing"); - Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 8); - sendBroadcast(outgoingIntent); - death=false; + } + Intent outgoingIntent = new Intent(); // silly, but should be done async. I think. + outgoingIntent.setAction(CommandStrings.msrv_rec); + outgoingIntent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_load_cfg); + outgoingIntent.putExtra(CommandStrings.msrv_infile, input + suffix); + outgoingIntent.putExtra(CommandStrings.msrv_reset, true); + sendBroadcast(outgoingIntent); + } + while (((JNIHandler.isPlaying))) { + try { + Thread.sleep(25); + } catch (InterruptedException e) { + } + } + + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_special_notification_finished); + sendBroadcast(outgoingIntent); + death = false; } - }).start(); - //play(); - break; - case 15: // We want to write an output file while playing. - shouldAdvance=false; - if(JNIHandler.paused) - { - JNIHandler.pause(); - JNIHandler.waitUntilReady(50); - } - JNIHandler.seekTo(0); // Why is this async. Seriously. - JNIHandler.waitUntilReady(); - JNIHandler.pause(); - JNIHandler.waitUntilReady(); - String output2 = intent.getStringExtra(getResources().getString(R.string.msrv_outfile)); - if(Globals.isPlaying==0&&output2!=null) - { - JNIHandler.setupOutputFile(output2); - JNIHandler.pause(); - } - new Thread(new Runnable(){ + }).start(); + // play(); + break; + case CommandStrings.msrv_cmd_write_curr: // We want to write an output file while playing. + shouldAdvance = false; + if (JNIHandler.paused) { + JNIHandler.pause(); + JNIHandler.waitUntilReady(50); + } + JNIHandler.seekTo(0); // Why is this async. Seriously. + JNIHandler.waitUntilReady(); + JNIHandler.pause(); + JNIHandler.waitUntilReady(); + String output2 = intent.getStringExtra(CommandStrings.msrv_outfile); + if (JNIHandler.isPlaying && output2 != null) { + JNIHandler.setupOutputFile(output2); + JNIHandler.pause(); + } + new Thread(new Runnable() { @Override - public void run() - { - while(((Globals.isPlaying==1))) - { - try {Thread.sleep(10);} catch (InterruptedException e){} + public void run() { + while (((!JNIHandler.isPlaying))) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } } - while(((Globals.isPlaying==0))) - { - try {Thread.sleep(25);} catch (InterruptedException e){} - } - Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 8); - sendBroadcast(outgoingIntent); - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 5); - outgoingIntent.putExtra(getResources().getString(R.string.ta_pause), false); - sendBroadcast(outgoingIntent); + while (((JNIHandler.isPlaying))) { + try { + Thread.sleep(25); + } catch (InterruptedException e) { + } + } + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_special_notification_finished); + sendBroadcast(outgoingIntent); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_pause_stop); + outgoingIntent.putExtra(CommandStrings.ta_pause, false); + sendBroadcast(outgoingIntent); } - }).start(); - break; - case 16: // store midi settings - boolean wasPaused=JNIHandler.paused; - if(!JNIHandler.paused) - { - JNIHandler.pause(); - JNIHandler.waitUntilReady(50); - } - String output3 = intent.getStringExtra(getResources().getString(R.string.msrv_outfile)); - int[] numbers = new int[3]; - numbers[0] = JNIHandler.tb; - numbers[1] = JNIHandler.koffset; - numbers[2] = JNIHandler.maxvoice; - String[] serializedSettings=new String[5]; // I'm sorry. I'm sorry. - try - { - serializedSettings[0]=ObjectSerializer.serialize(JNIHandler.custInst); - serializedSettings[1]=ObjectSerializer.serialize(JNIHandler.custVol); - serializedSettings[2]=ObjectSerializer.serialize(JNIHandler.programs); - serializedSettings[3]=ObjectSerializer.serialize(JNIHandler.volumes); - serializedSettings[4]=ObjectSerializer.serialize(numbers); - } catch (IOException e) - { + }).start(); + break; + case CommandStrings.msrv_cmd_save_cfg: // store midi settings + boolean wasPaused = JNIHandler.paused; + if (!JNIHandler.paused) { + JNIHandler.pause(); + JNIHandler.waitUntilReady(50); + } + String output3 = intent.getStringExtra(CommandStrings.msrv_outfile); + int[] numbers = new int[3]; + numbers[0] = JNIHandler.tb; + numbers[1] = JNIHandler.keyOffset; + numbers[2] = JNIHandler.maxvoice; + String[] serializedSettings = new String[5]; // I'm sorry. I'm sorry. + try { + serializedSettings[0] = ObjectSerializer.serialize(JNIHandler.custInst); + serializedSettings[1] = ObjectSerializer.serialize(JNIHandler.custVol); + serializedSettings[2] = ObjectSerializer.serialize(JNIHandler.programs); + serializedSettings[3] = ObjectSerializer.serialize(JNIHandler.volumes); + serializedSettings[4] = ObjectSerializer.serialize(numbers); + } catch (IOException e) { e.printStackTrace(); } - - if(Globals.compressCfg) - { - BufferedWriter writer = null; - try - { - GZIPOutputStream zip = new GZIPOutputStream(new FileOutputStream(new File(output3))); - writer = new BufferedWriter(new OutputStreamWriter(zip, "US-ASCII")); + if (SettingsStorage.compressCfg) { + BufferedWriter writer = null; + try { + GZIPOutputStream zip = new GZIPOutputStream(new FileOutputStream(new File(output3))); - for(String s : serializedSettings) - { - writer.append(s); - writer.newLine(); - } - } catch (IOException e) { - e.printStackTrace(); + writer = new BufferedWriter(new OutputStreamWriter(zip, "US-ASCII")); + + for (String s : serializedSettings) { + writer.append(s); + writer.newLine(); } - finally - { - if(writer != null) - try { - writer.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }else{ - FileWriter fw = null; - try { - fw = new FileWriter(output3,false); - for(String s : serializedSettings) - { - fw.write(s+"\n"); - } - fw.close(); - } catch (IOException e) { - e.printStackTrace(); - }} - if(!wasPaused) - { - JNIHandler.pause(); - JNIHandler.waitUntilReady(50); - } - Intent outgoingIntent15 = new Intent(); - outgoingIntent15.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent15.putExtra(getResources().getString(R.string.ta_cmd), 8); - sendBroadcast(outgoingIntent15); - break; - case 17: // load midi settings - if(JNIHandler.paused) - { - JNIHandler.pause(); - JNIHandler.waitUntilReady(50); - } - String input2 = intent.getStringExtra(getResources().getString(R.string.msrv_infile)); - ArrayList msprograms = new ArrayList(); - ArrayList mscustInst = new ArrayList(); - ArrayList msvolumes = new ArrayList(); - ArrayList mscustVol = new ArrayList(); - int[] newnumbers = new int[3]; - FileInputStream fstream; - try - { + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (writer != null) + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } else { + FileWriter fw = null; + try { + fw = new FileWriter(output3, false); + for (String s : serializedSettings) { + fw.write(s + "\n"); + } + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (!wasPaused) { + JNIHandler.pause(); + JNIHandler.waitUntilReady(50); + } + Intent outgoingIntent15 = new Intent(); + outgoingIntent15.setAction(CommandStrings.ta_rec); + outgoingIntent15.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_special_notification_finished); + sendBroadcast(outgoingIntent15); + break; + case CommandStrings.msrv_cmd_load_cfg: // load midi settings + if (JNIHandler.paused) { + JNIHandler.pause(); + JNIHandler.waitUntilReady(50); + } + String input2 = intent.getStringExtra(CommandStrings.msrv_infile); + ArrayList msprograms = new ArrayList(); + ArrayList mscustInst = new ArrayList(); + ArrayList msvolumes = new ArrayList(); + ArrayList mscustVol = new ArrayList(); + int[] newnumbers = new int[3]; + FileInputStream fstream; + try { BufferedReader br; - if(input2.endsWith(".tzf")) - { + if (input2.endsWith(".tzf")) { InputStream fileStream = new FileInputStream(input2); InputStream gzipStream = new GZIPInputStream(fileStream); InputStreamReader decoder = new InputStreamReader(gzipStream, "US-ASCII"); br = new BufferedReader(decoder); - }else{ - - fstream = new FileInputStream(input2); - DataInputStream in = new DataInputStream(fstream); - br = new BufferedReader(new InputStreamReader(in)); + } else { + + fstream = new FileInputStream(input2); + DataInputStream in = new DataInputStream(fstream); + br = new BufferedReader(new InputStreamReader(in)); } - mscustInst=(ArrayList) ObjectSerializer.deserialize(br.readLine()); - mscustVol=(ArrayList) ObjectSerializer.deserialize(br.readLine()); - msprograms=(ArrayList) ObjectSerializer.deserialize(br.readLine()); - msvolumes=(ArrayList) ObjectSerializer.deserialize(br.readLine()); - newnumbers = (int[]) ObjectSerializer.deserialize(br.readLine()); - br.close(); - } catch (IOException e) - { + // I could check if all of these are actually ArrayLists, but eclipse still won't be happy + mscustInst = (ArrayList) ObjectSerializer.deserialize(br.readLine()); + mscustVol = (ArrayList) ObjectSerializer.deserialize(br.readLine()); + msprograms = (ArrayList) ObjectSerializer.deserialize(br.readLine()); + msvolumes = (ArrayList) ObjectSerializer.deserialize(br.readLine()); + newnumbers = (int[]) ObjectSerializer.deserialize(br.readLine()); + br.close(); + } catch (IOException e) { e.printStackTrace(); } - if(mscustInst.size()!=mscustVol.size()|| - mscustVol.size()!=msprograms.size()|| - msprograms.size()!=msvolumes.size()) - { - // wat - break; + if (mscustInst.size() != mscustVol.size() || mscustVol.size() != msprograms.size() || msprograms.size() != msvolumes.size()) { + // wat + break; } - for(int i = 0; i0) - { + int newtb = newnumbers[0] - JNIHandler.tb; + if (newtb > 0) { JNIHandler.controlTimidity(17, newtb); JNIHandler.waitUntilReady(); - }else if(newtb<0) - { - JNIHandler.controlTimidity(18, -1*newtb); + } else if (newtb < 0) { + JNIHandler.controlTimidity(18, -1 * newtb); JNIHandler.waitUntilReady(); } - JNIHandler.tb=newnumbers[0]; - - int newko = newnumbers[1]-JNIHandler.koffset; - if(newko>0) - { + JNIHandler.tb = newnumbers[0]; + + int newko = newnumbers[1] - JNIHandler.keyOffset; + if (newko > 0) { JNIHandler.controlTimidity(15, newko); JNIHandler.waitUntilReady(); - }else if(newko<0) - { + } else if (newko < 0) { JNIHandler.controlTimidity(16, newko); JNIHandler.waitUntilReady(); } - JNIHandler.koffset=newnumbers[1]; - int newvoice=newnumbers[2]-JNIHandler.maxvoice; - if(newvoice!=0) - { - if(newvoice>0) - { - JNIHandler.controlTimidity(19,newvoice); - }else{ - JNIHandler.controlTimidity(20,-1*newvoice); + JNIHandler.keyOffset = newnumbers[1]; + int newvoice = newnumbers[2] - JNIHandler.maxvoice; + if (newvoice != 0) { + if (newvoice > 0) { + JNIHandler.controlTimidity(19, newvoice); + } else { + JNIHandler.controlTimidity(20, -1 * newvoice); } JNIHandler.waitUntilReady(); } - if(intent.getBooleanExtra(getResources().getString(R.string.msrv_reset), false)) - { + if (intent.getBooleanExtra(CommandStrings.msrv_reset, false)) { JNIHandler.seekTo(0); - JNIHandler.shouldPlayNow=true; + JNIHandler.shouldPlayNow = true; JNIHandler.waitUntilReady(); } - break; - case 18: // Reload native libs - if(!JNIHandler.type) + break; + case CommandStrings.msrv_cmd_reload_libs: // Reload native libs + if(!JNIHandler.isMediaPlayerFormat) { fullStop=true; Globals.hardStop=true; @@ -682,496 +631,462 @@ public void run() stop(); JNIHandler.waitForStop(); } - //System.out.println("Unloading: "+JNIHandler.unloadLib()); + int logRet = JNIHandler.unloadLib(); + Log.d("TIMIDITY", "Unloading: "+logRet); JNIHandler.prepared = false; JNIHandler.volumes = new ArrayList(); JNIHandler.programs = new ArrayList(); JNIHandler.drums = new ArrayList(); JNIHandler.custInst = new ArrayList(); JNIHandler.custVol = new ArrayList(); - //System.out.println("Reloading: "+JNIHandler.loadLib(Globals.getLibDir(MusicService.this)+"libtimidityplusplus.so")); - int x = JNIHandler.init(Globals.dataFolder+"timidity/","timidity.cfg", Globals.mono, Globals.defSamp, Globals.sixteen, Globals.buff, Globals.aRate, Globals.preserveSilence, true, Globals.freeInsts); + logRet = JNIHandler.loadLib(Globals.getLibDir(MusicService.this)+"libtimidityplusplus.so"); + Log.d("TIMIDITY", "Reloading: "+logRet); + int x = JNIHandler.init(SettingsStorage.dataFolder+"timidity/","timidity.cfg", SettingsStorage.channelMode, SettingsStorage.defaultResamp, SettingsStorage.sixteenBit, SettingsStorage.bufferSize, SettingsStorage.audioRate, SettingsStorage.preserveSilence, true, SettingsStorage.freeInsts); if(x!=0&&x!=-99) { - Globals.nativeMidi=true; + SettingsStorage.nativeMidi=true; Toast.makeText(MusicService.this, String.format(getResources().getString(R.string.tcfg_error), x), Toast.LENGTH_LONG).show(); } - break; - } - } - } - }; - + break; + } + } + } + }; - @Override - public void onCreate() { - super.onCreate(); - if (serviceReceiver != null) { - IntentFilter intentFilter = new IntentFilter(); - intentFilter.addAction(getResources().getString(R.string.msrv_rec)); - intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); - intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON); - registerReceiver(serviceReceiver, intentFilter); - } - pm = (PowerManager) getSystemService(Context.POWER_SERVICE); - wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Timidity AE"); - wl.setReferenceCounted(false); - if(shouldDoWidget) + @Override + public void onCreate() { + super.onCreate(); + if (serviceReceiver != null) { + IntentFilter intentFilter = new IntentFilter(); + intentFilter.addAction(CommandStrings.msrv_rec); + intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); + intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON); + registerReceiver(serviceReceiver, intentFilter); + } + pm = (PowerManager) getSystemService(Context.POWER_SERVICE); + wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Timidity AE"); + wl.setReferenceCounted(false); + if (shouldDoWidget) widgetIds = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); - - TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if(mgr != null && Globals.phoneState) { - mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); - } - //foreground=false; - if(wl.isHeld()) - wl.release(); - - stopForeground(true); - - } - @Override - public void onDestroy() { - super.onDestroy(); - unregisterReceiver(serviceReceiver); - } - @SuppressLint("NewApi") - public void play() - { - if(playList!=null&&currSongNumber>=0) - { - shouldAdvance=false; - death=true; - fullStop=false; - stop(); - death=false; - Globals.shouldRestore=true; - while(!death&&((Globals.isPlaying==0||JNIHandler.alternativeCheck==333333))) - { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } + TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); + if (mgr != null && Globals.phoneState) { + mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } - - if(!death) - { - final int songIndex; - if(shuffleMode == 1) - { - songIndex = realSongNumber = shuffledIndices.get(currSongNumber); - }else{ - songIndex = realSongNumber = currSongNumber; - } - MediaMetadataRetriever mmr = new MediaMetadataRetriever(); + // foreground=false; + if (wl.isHeld()) + wl.release(); - String tmpTitle; - String fileName = playList.get(songIndex); - try{ - mmr.setDataSource(fileName); - tmpTitle = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); - }catch (RuntimeException e) - { - tmpTitle=fileName.substring(playList.get(songIndex).lastIndexOf('/')+1); - } - if(tmpTitle!=null) - { - if(TextUtils.isEmpty(tmpTitle)) - tmpTitle=fileName.substring(fileName.lastIndexOf('/')+1); - }else{ - tmpTitle=fileName.substring(fileName.lastIndexOf('/')+1); + stopForeground(true); + + } + + @Override + public void onDestroy() { + super.onDestroy(); + unregisterReceiver(serviceReceiver); + } + + @SuppressLint("NewApi") + public void play() { + if (playList != null && currSongNumber >= 0) { + shouldAdvance = false; + death = true; + fullStop = false; + stop(); + death = false; + Globals.shouldRestore = true; + while (!death && ((JNIHandler.isPlaying || JNIHandler.isBlocking == true))) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - setupMediaArtAndWidget(fileName, mmr); - Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 6); - sendBroadcast(outgoingIntent); - - currTitle=tmpTitle; - shouldAdvance=true; - paused=false; - - final int x=JNIHandler.play(playList.get(songIndex)); - if(x!=0) - { - switch(x) - { - case -1: - handler.post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_fnf), Toast.LENGTH_SHORT).show(); - } - }); - - break; - case -3: - handler.post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), "Error initializing AudioTrack. Try decreasing the buffer size.", Toast.LENGTH_LONG).show(); - } - }); - - break; - case -9: - handler.post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_loading), Toast.LENGTH_SHORT).show(); - } - }); - break; - default: - handler.post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), String.format(getResources().getString(R.string.srv_unk),x), Toast.LENGTH_SHORT).show(); - } - }); - break; - } - - Globals.isPlaying=1; - JNIHandler.type=true; - shouldAdvance=false; - JNIHandler.paused=false; - stop(); - }else{ - updateNotification(currTitle, paused); - new Thread(new Runnable(){ - public void run() - { - while(!death&&((Globals.isPlaying==1&&shouldAdvance))){ - if(JNIHandler.alternativeCheck==555555) - death=true; - - //System.out.println(String.format("alt check: %d death: %s isplaying: %d shouldAdvance: %s seekBarReady: %s",JNIHandler.alternativeCheck,death?"true":"false",Globals.isPlaying,shouldAdvance?"true":"false",JNIHandler.seekbarReady?"true":"false")); - try {Thread.sleep(10);} catch (InterruptedException e){}} - if(!death) - { - Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.ta_cmd), 0); - outgoingIntent.putExtra(getResources().getString(R.string.ta_startt),JNIHandler.maxTime); - outgoingIntent.putExtra(getResources().getString(R.string.ta_songttl),currTitle); - outgoingIntent.putExtra(getResources().getString(R.string.ta_filename),playList.get(songIndex)); - outgoingIntent.putExtra("stupidNumber",songIndex); - sendBroadcast(outgoingIntent); - } - if(new File(playList.get(songIndex)+".def.tcf").exists()||new File(playList.get(songIndex)+".def.tzf").exists()) - { - String suffix; - if(new File(playList.get(songIndex)+".def.tcf").exists()&&new File(playList.get(songIndex)+".def.tzf").exists()) - { - suffix = (Globals.compressCfg?".def.tzf":".def.tcf"); - }else if(new File(playList.get(songIndex)+".def.tcf").exists()) - { - suffix = ".def.tcf"; - }else{ - suffix = ".def.tzf"; - } - JNIHandler.shouldPlayNow=false; - JNIHandler.currTime=0; - while(Globals.isPlaying==0&&!death&&shouldAdvance&&!JNIHandler.dataWritten) - { - try - { - Thread.sleep(25); - } catch (InterruptedException e) - { - e.printStackTrace(); + + if (!death) { + final int songIndex; + if (shuffleMode == 1) { + songIndex = realSongNumber = shuffledIndices.get(currSongNumber); + } else { + songIndex = realSongNumber = currSongNumber; + } + MediaMetadataRetriever mmr = new MediaMetadataRetriever(); + + String tmpTitle; + String fileName = playList.get(songIndex); + try { + mmr.setDataSource(fileName); + tmpTitle = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); + } catch (RuntimeException e) { + tmpTitle = fileName.substring(playList.get(songIndex).lastIndexOf('/') + 1); + } + if (tmpTitle != null) { + if (TextUtils.isEmpty(tmpTitle)) + tmpTitle = fileName.substring(fileName.lastIndexOf('/') + 1); + } else { + tmpTitle = fileName.substring(fileName.lastIndexOf('/') + 1); + } + setupMediaArtAndWidget(fileName, mmr); + Intent outgoingIntent = new Intent(); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_update_art); + sendBroadcast(outgoingIntent); + + currTitle = tmpTitle; + shouldAdvance = true; + paused = false; + + final int x = JNIHandler.play(playList.get(songIndex)); + if (x != 0) { + switch (x) { + case -1: + handler.post(new Runnable() { + @Override + public void run() { + Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_fnf), Toast.LENGTH_SHORT).show(); + } + }); + + break; + case -3: + handler.post(new Runnable() { + @Override + public void run() { + Toast.makeText(getApplicationContext(), "Error initializing AudioTrack. Try decreasing the buffer size.", Toast.LENGTH_LONG).show(); + } + }); + + break; + case -9: + handler.post(new Runnable() { + @Override + public void run() { + Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_loading), Toast.LENGTH_SHORT).show(); + } + }); + break; + default: + handler.post(new Runnable() { + @Override + public void run() { + Toast.makeText(getApplicationContext(), String.format(getResources().getString(R.string.srv_unk), x), Toast.LENGTH_SHORT).show(); + } + }); + break; } - } - Intent outgoingIntent = new Intent(); // silly, but should be done async. I think. - outgoingIntent.setAction(getResources().getString(R.string.msrv_rec)); - outgoingIntent.putExtra(getResources().getString(R.string.msrv_cmd), 17); - outgoingIntent.putExtra(getResources().getString(R.string.msrv_infile),playList.get(songIndex)+suffix); - outgoingIntent.putExtra(getResources().getString(R.string.msrv_reset),true); - sendBroadcast(outgoingIntent); - } - while(!death&&(((Globals.isPlaying==0||JNIHandler.alternativeCheck==333333)&&shouldAdvance))){ - try {Thread.sleep(25);} catch (InterruptedException e){}} - if(shouldAdvance&&!death) - { - shouldAdvance=false; - new Thread(new Runnable(){ - public void run() - { - if(playList.size()>1&&(((songIndex+1 1 && (((songIndex + 1 < playList.size() && loopMode == 0)) || loopMode == 1)) { + next(); + } else if (loopMode == 2 || playList.size() == 1) { + play(); + } else if (loopMode == 0) { + Globals.hardStop = true; + Intent new_intent = new Intent(); + new_intent.setAction(CommandStrings.ta_rec); + new_intent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_pause_stop); + new_intent.putExtra(CommandStrings.ta_pause, false); + sendBroadcast(new_intent); + } + } + }).start(); + + } + + } + }).start(); + } + } } } - public void pause() - { - if(playList!=null&&currSongNumber>=0) - { - if(Globals.isPlaying==0) - { - paused=!paused; - JNIHandler.pause(); - Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.ta_rec)); - new_intent.putExtra(getResources().getString(R.string.ta_cmd), 5); - new_intent.putExtra(getResources().getString(R.string.ta_pause), true); - new_intent.putExtra(getResources().getString(R.string.ta_pausea), paused); - sendBroadcast(new_intent); - updateNotification(currTitle, paused); - - - } + + public void pause() { + if (playList != null && currSongNumber >= 0) { + if (JNIHandler.isPlaying) { + paused = !paused; + JNIHandler.pause(); + Intent new_intent = new Intent(); + new_intent.setAction(CommandStrings.ta_rec); + new_intent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_pause_stop); + new_intent.putExtra(CommandStrings.ta_pause, true); + new_intent.putExtra(CommandStrings.ta_pausea, paused); + sendBroadcast(new_intent); + updateNotification(currTitle, paused); + + } } } - public void next() - { - death=true; - if(playList!=null&&currSongNumber>=0) - { - - if(playList.size()>1) - { - if(shuffleMode==2){ - int tmpNum=currSongNumber; - while(tmpNum==currSongNumber) - { + + public void next() { + death = true; + if (playList != null && currSongNumber >= 0) { + + if (playList.size() > 1) { + if (shuffleMode == 2) { + int tmpNum = currSongNumber; + while (tmpNum == currSongNumber) { try { Thread.sleep(10); // Don't hog CPU. Please. } catch (InterruptedException e) { e.printStackTrace(); } - tmpNum=random.nextInt(playList.size()); + tmpNum = random.nextInt(playList.size()); } - currSongNumber=tmpNum; - }else{ - if(++currSongNumber>=playList.size()) - { - currSongNumber=0; + currSongNumber = tmpNum; + } else { + if (++currSongNumber >= playList.size()) { + currSongNumber = 0; } } } - play(); + play(); } } - public void previous() - { - death=true; - if(playList!=null&&currSongNumber>=0) - { - currSongNumber-=1; - if(currSongNumber<0) - { - currSongNumber=playList.size()-1; - } - play(); + + public void previous() { + death = true; + if (playList != null && currSongNumber >= 0) { + currSongNumber -= 1; + if (currSongNumber < 0) { + currSongNumber = playList.size() - 1; + } + play(); } } - public void stop() - { - if(Globals.isPlaying==0) - { - death=true; + public void stop() { + if (JNIHandler.isPlaying) { + + death = true; Intent stop_intent = new Intent(); - stop_intent.setAction(getResources().getString(R.string.ta_rec)); - stop_intent.putExtra(getResources().getString(R.string.ta_cmd), 5); - stop_intent.putExtra(getResources().getString(R.string.ta_pause), false); - sendBroadcast(stop_intent); - - - Globals.shouldRestore=false; + stop_intent.setAction(CommandStrings.ta_rec); + stop_intent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_pause_stop); + stop_intent.putExtra(CommandStrings.ta_pause, false); + sendBroadcast(stop_intent); + + Globals.shouldRestore = false; JNIHandler.stop(); - if(fullStop) - { + if (fullStop) { TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if(mgr != null && Globals.phoneState) { - mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); + if (mgr != null && Globals.phoneState) { + mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); } - Globals.shouldRestore=false; - if(wl.isHeld()) + Globals.shouldRestore = false; + if (wl.isHeld()) wl.release(); - foreground=false; - fullStop=false; + foreground = false; + fullStop = false; // Fix the widget - if(shouldDoWidget) - { - stop_intent = new Intent(this, TimidityAEWidgetProvider.class); - stop_intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - //stop_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - stop_intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,widgetIds); - stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", true); - stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", ""); - stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", false); - stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.death", true); - sendBroadcast(stop_intent); - }else{ - Globals.nukedWidgets=true; + if (shouldDoWidget) { + stop_intent = new Intent(this, TimidityAEWidgetProvider.class); + stop_intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // stop_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + stop_intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", true); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", ""); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", false); + stop_intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.death", true); + sendBroadcast(stop_intent); + } else { + SettingsStorage.nukedWidgets = true; } - stopForeground(true); - //stopSelf(); - + stopForeground(true); + // stopSelf(); + } } } - public void updateNotification(String title, boolean paused) - { - //System.out.println("Updating notification"); - - remoteViews = new RemoteViews(getPackageName(), - R.layout.music_notification); - remoteViews.setTextViewText(R.id.titley, currTitle); - remoteViews.setImageViewResource(R.id.notPause, (paused)?R.drawable.ic_media_play:R.drawable.ic_media_pause); - // Previous - Intent new_intent = new Intent(); - //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 4); - PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(this, 1, new_intent, 0); - remoteViews.setOnClickPendingIntent(R.id.notPrev, pendingNotificationIntent); - // Play/Pause - new_intent = new Intent(); - //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 2); - pendingNotificationIntent = PendingIntent.getBroadcast(this, 2, new_intent, 0); - remoteViews.setOnClickPendingIntent(R.id.notPause, pendingNotificationIntent); - // Next - new_intent = new Intent(); - //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 3); - pendingNotificationIntent = PendingIntent.getBroadcast(this, 3, new_intent, 0); - remoteViews.setOnClickPendingIntent(R.id.notNext, pendingNotificationIntent); - // Stop - new_intent = new Intent(); - //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); - pendingNotificationIntent = PendingIntent.getBroadcast(this, 4, new_intent, 0); - remoteViews.setOnClickPendingIntent(R.id.notStop, pendingNotificationIntent); - final Intent emptyIntent = new Intent(this, TimidityActivity.class); - //emptyIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - PendingIntent pendingIntent = PendingIntent.getActivity(this, 5, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT); - NotificationCompat.Builder mBuilder = - new NotificationCompat.Builder(this) - .setContentTitle(getResources().getString(R.string.app_name)) - .setContentText(currTitle) - .setContentIntent(pendingIntent) - .setContent(remoteViews); - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - mBuilder.setSmallIcon(R.drawable.ic_lol); - }else{ - mBuilder.setSmallIcon(R.drawable.ic_launcher); - } - mainNotification=mBuilder.build(); - mainNotification.flags|=Notification.FLAG_ONLY_ALERT_ONCE|Notification.FLAG_ONGOING_EVENT; - if(!foreground) - { - foreground=true; - // Dear Google, - // Your terrible Marshmallow power management had better not break this. - // If it does, I am using REQUEST_IGNORE_BATTERY_OPTIMIZATIONS. - // If you ban me for using it, there will be consequences. - startForeground(Globals.NOTIFICATION_ID, mainNotification); - if(!wl.isHeld()) - { - wl.acquire(); - } - - TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); - if(mgr != null && Globals.phoneState) - { - mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); - } - }else{ - if(!wl.isHeld()) - { - wl.acquire(); - } - NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - mNotificationManager.notify(Globals.NOTIFICATION_ID, mainNotification); - } - if(shouldDoWidget) - { - Intent intent = new Intent(this, TimidityAEWidgetProvider.class); - intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); - // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, - // since it seems the onUpdate() is only fired on that: - //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,widgetIds); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", paused); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", currTitle); - intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); - sendBroadcast(intent); - } + + public void updateNotification(String title, boolean paused) { + // System.out.println("Updating notification"); + + remoteViews = new RemoteViews(getPackageName(), R.layout.music_notification); + remoteViews.setTextViewText(R.id.titley, currTitle); + remoteViews.setImageViewResource(R.id.notPause, (paused) ? R.drawable.ic_media_play : R.drawable.ic_media_pause); + // Previous + Intent new_intent = new Intent(); + // new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_prev); + PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(this, 1, new_intent, 0); + remoteViews.setOnClickPendingIntent(R.id.notPrev, pendingNotificationIntent); + // Play/Pause + new_intent = new Intent(); + // new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_pause); + pendingNotificationIntent = PendingIntent.getBroadcast(this, 2, new_intent, 0); + remoteViews.setOnClickPendingIntent(R.id.notPause, pendingNotificationIntent); + // Next + new_intent = new Intent(); + // new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_next); + pendingNotificationIntent = PendingIntent.getBroadcast(this, 3, new_intent, 0); + remoteViews.setOnClickPendingIntent(R.id.notNext, pendingNotificationIntent); + // Stop + new_intent = new Intent(); + // new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_stop); + pendingNotificationIntent = PendingIntent.getBroadcast(this, 4, new_intent, 0); + remoteViews.setOnClickPendingIntent(R.id.notStop, pendingNotificationIntent); + final Intent emptyIntent = new Intent(this, TimidityActivity.class); + // emptyIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + PendingIntent pendingIntent = PendingIntent.getActivity(this, 5, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setContentTitle(getResources().getString(R.string.app_name)).setContentText(currTitle).setContentIntent(pendingIntent).setContent(remoteViews); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + mBuilder.setSmallIcon(R.drawable.ic_lol); + } else { + mBuilder.setSmallIcon(R.drawable.ic_launcher); + } + mainNotification = mBuilder.build(); + mainNotification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_ONGOING_EVENT; + if (!foreground) { + foreground = true; + // Dear Google, + // Your terrible Marshmallow power management had better not break this. + // If it does, I am using REQUEST_IGNORE_BATTERY_OPTIMIZATIONS. + // If you ban me for using it, there will be consequences. + startForeground(Globals.NOTIFICATION_ID, mainNotification); + if (!wl.isHeld()) { + wl.acquire(); + } + + TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); + if (mgr != null && Globals.phoneState) { + mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); + } + } else { + if (!wl.isHeld()) { + wl.acquire(); } - + NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + mNotificationManager.notify(Globals.NOTIFICATION_ID, mainNotification); + } + if (shouldDoWidget) { + Intent intent = new Intent(this, TimidityAEWidgetProvider.class); + intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, + // since it seems the onUpdate() is only fired on that: + // intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", paused); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", currTitle); + intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); + sendBroadcast(intent); + } + } + @SuppressLint("NewApi") - public void setupMediaArtAndWidget(String fileName, MediaMetadataRetriever mmr) - { - Globals.currArt=null; - boolean goodart=false; - if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) // Please work + public void setupMediaArtAndWidget(String fileName, MediaMetadataRetriever mmr) { + Globals.currArt = null; + boolean goodart = false; + if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) // Please work { - try{ - + try { + byte[] art = mmr.getEmbeddedPicture(); - if(art!=null) - { - Globals.currArt=BitmapFactory.decodeByteArray(art, 0, art.length); - goodart=Globals.currArt!=null; + if (art != null) { + Globals.currArt = BitmapFactory.decodeByteArray(art, 0, art.length); + goodart = Globals.currArt != null; } - }catch (Exception e){} + } catch (Exception e) { + } } - if(!goodart) - { - String goodPath=fileName.substring(0,fileName.lastIndexOf('/')+1)+"folder.jpg"; - if(new File(goodPath).exists()) - { - try{ - Globals.currArt=BitmapFactory.decodeFile(goodPath); - }catch (RuntimeException e){} - }else{ + if (!goodart) { + String goodPath = fileName.substring(0, fileName.lastIndexOf('/') + 1) + "folder.jpg"; + if (new File(goodPath).exists()) { + try { + Globals.currArt = BitmapFactory.decodeFile(goodPath); + } catch (RuntimeException e) { + } + } else { // Try albumart.jpg - goodPath=fileName.substring(0,fileName.lastIndexOf('/')+1)+"AlbumArt.jpg"; - if(new File(goodPath).exists()) - { - try{ - Globals.currArt=BitmapFactory.decodeFile(goodPath); - }catch (RuntimeException e){ - // + goodPath = fileName.substring(0, fileName.lastIndexOf('/') + 1) + "AlbumArt.jpg"; + if (new File(goodPath).exists()) { + try { + Globals.currArt = BitmapFactory.decodeFile(goodPath); + } catch (RuntimeException e) { + // } } } } - if(shouldDoWidget) - { - Intent intent = new Intent(this,TimidityAEWidgetProvider.class); + if (shouldDoWidget) { + Intent intent = new Intent(this, TimidityAEWidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, // since it seems the onUpdate() is only fired on that: widgetIds = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); - - //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + + // intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); sendBroadcast(intent); } } } - - diff --git a/src/com/xperia64/timidityae/SettingsActivity.java b/src/com/xperia64/timidityae/SettingsActivity.java index 4038784..cc48a51 100755 --- a/src/com/xperia64/timidityae/SettingsActivity.java +++ b/src/com/xperia64/timidityae/SettingsActivity.java @@ -15,7 +15,11 @@ import java.util.ArrayList; import java.util.List; +import com.xperia64.timidityae.util.DocumentFileUtils; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.ObjectSerializer; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; import com.xperia64.timidityae.R; import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog; import com.xperia64.timidityae.gui.dialogs.SoundfontDialog; @@ -106,7 +110,7 @@ protected void onCreate(Bundle savedInstanceState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR && Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { this.setTheme(android.support.v7.appcompat.R.style.Theme_AppCompat); } else { - this.setTheme((Globals.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); + this.setTheme((SettingsStorage.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); } super.onCreate(savedInstanceState); getSupportActionBar().setDisplayHomeAsUpEnabled(true); @@ -184,15 +188,15 @@ public void onBackPressed() { e.printStackTrace(); } if (needUpdateSf) { - Globals.writeCfg(SettingsActivity.this, Globals.dataFolder + "/timidity/timidity.cfg", tmpSounds); // TODO + SettingsStorage.writeCfg(SettingsActivity.this, SettingsStorage.dataFolder + "/timidity/timidity.cfg", tmpSounds); // TODO // ?? } - Globals.reloadSettings(this, this.getAssets()); + SettingsStorage.reloadSettings(this, this.getAssets()); if (needRestart) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 18); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_reload_libs); sendBroadcast(new_intent); } Intent returnIntent = new Intent(); @@ -209,7 +213,7 @@ public void setItem(String path, int type) { case 3: prefs.edit().putString("defaultPath", path).commit(); manHomeFolder.setText(path); - Globals.defaultFolder = path; + SettingsStorage.homeFolder = path; ((BaseAdapter) pf.getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); break; case 4: @@ -235,9 +239,9 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { Uri treeUri = data.getData(); getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - Globals.theFold = treeUri; + DocumentFileUtils.docFileDevice = treeUri; } else { - Globals.theFold = null; + DocumentFileUtils.docFileDevice = null; } } @@ -316,7 +320,7 @@ public void onCreate(Bundle savedInstanceState) { @Override public boolean onPreferenceChange(Preference arg0, Object arg1) { - Globals.showHiddenFiles = (Boolean) arg1; + SettingsStorage.showHiddenFiles = (Boolean) arg1; return true; } @@ -325,7 +329,7 @@ public boolean onPreferenceChange(Preference arg0, Object arg1) { @Override public boolean onPreferenceChange(Preference arg0, Object arg1) { - Globals.showVideos = (Boolean) arg1; + SettingsStorage.showVideos = (Boolean) arg1; return true; } @@ -334,10 +338,10 @@ public boolean onPreferenceChange(Preference arg0, Object arg1) { @Override public boolean onPreferenceChange(Preference arg0, Object arg1) { - if (!Globals.onlyNative) - Globals.nativeMidi = (Boolean) arg1; + if (!SettingsStorage.onlyNative) + SettingsStorage.nativeMidi = (Boolean) arg1; else - Globals.nativeMidi = true; + SettingsStorage.nativeMidi = true; return true; } @@ -346,7 +350,7 @@ public boolean onPreferenceChange(Preference arg0, Object arg1) { @Override public boolean onPreferenceChange(Preference arg0, Object arg1) { - Globals.keepWav = (Boolean) arg1; + SettingsStorage.keepPartialWav = (Boolean) arg1; return true; } @@ -463,7 +467,7 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { String sixteen = "16";// s.bitMode.getValue(); boolean sb = (stereo != null) ? stereo.equals("2") : true; boolean sxb = (sixteen != null) ? sixteen.equals("16") : true; - SparseIntArray mmm = Globals.validBuffers(Globals.validRates(sb, sxb), sb, sxb); + SparseIntArray mmm = SettingsStorage.validBuffers(SettingsStorage.validRates(sb, sxb), sb, sxb); if (mmm != null) { int minBuff = mmm.get(Integer.parseInt((String) newValue)); @@ -542,8 +546,8 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { // buffSize = Integer.parseInt(prefs.getString("tplusBuff", // "192000")); // System.out.println("Buffsize is: "+buffSize); - Globals.updateBuffers(Globals.updateRates()); - int[] values = Globals.updateRates(); + SettingsStorage.updateBuffers(SettingsStorage.updateRates()); + int[] values = SettingsStorage.updateRates(); if (values != null) { CharSequence[] hz = new CharSequence[values.length]; CharSequence[] hzItems = new CharSequence[values.length]; @@ -570,7 +574,7 @@ public boolean onPreferenceChange(Preference preference, final Object newValue) String sixteen = "16"; // s.bitMode.getValue(); boolean sb = (stereo != null) ? stereo.equals("2") : true; boolean sxb = (sixteen != null) ? sixteen.equals("16") : true; - SparseIntArray mmm = Globals.validBuffers(Globals.validRates(sb, sxb), sb, sxb); + SparseIntArray mmm = SettingsStorage.validBuffers(SettingsStorage.validRates(sb, sxb), sb, sxb); if (mmm != null) { int minBuff = mmm.get(Integer.parseInt(s.rates.getValue())); @@ -604,7 +608,7 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { String sixteen = "16"; // s.bitMode.getValue(); boolean sb = (stereo != null) ? stereo.equals("2") : true; boolean sxb = (sixteen != null) ? sixteen.equals("16") : true; - SparseIntArray mmm = Globals.validBuffers(Globals.validRates(sb, sxb), sb, sxb); + SparseIntArray mmm = SettingsStorage.validBuffers(SettingsStorage.validRates(sb, sxb), sb, sxb); if (mmm != null) { int minBuff = mmm.get(Integer.parseInt(s.rates.getValue())); @@ -653,7 +657,7 @@ public boolean onPreferenceChange(Preference preference, Object newValue) { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { - Globals.theme = Integer.parseInt((String) newValue); + SettingsStorage.theme = Integer.parseInt((String) newValue); Intent intent = s.getIntent(); s.finish(); startActivity(intent); @@ -669,7 +673,7 @@ public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preferen if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (preference instanceof PreferenceScreen) { - s.setTheme((Globals.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); + s.setTheme((SettingsStorage.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); s.setUpNestedScreen((PreferenceScreen) preference); } } diff --git a/src/com/xperia64/timidityae/TimidityActivity.java b/src/com/xperia64/timidityae/TimidityActivity.java index e3a884f..d86b48f 100755 --- a/src/com/xperia64/timidityae/TimidityActivity.java +++ b/src/com/xperia64/timidityae/TimidityActivity.java @@ -64,7 +64,10 @@ import com.xperia64.timidityae.gui.fragments.PlayerFragment; import com.xperia64.timidityae.gui.fragments.PlaylistFragment; import com.xperia64.timidityae.util.ConfigSaver; +import com.xperia64.timidityae.util.DocumentFileUtils; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; import com.xperia64.timidityae.util.WavSaver; // Eclipse Stahp @@ -101,25 +104,23 @@ public interface SpecialAction { @Override public void onReceive(Context context, Intent intent) { - int cmd = intent.getIntExtra(getResources().getString(R.string.ta_cmd), -5); // -V + int cmd = intent.getIntExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_error); // -V switch (cmd) { - case -5: - break; - case 0: - currSongName = intent.getStringExtra(getResources().getString(R.string.ta_filename)); + case CommandStrings.ta_cmd_gui_play: + currSongName = intent.getStringExtra(CommandStrings.ta_filename); if (viewPager.getCurrentItem() == 1) { menuButton.setIcon(R.drawable.ic_menu_agenda); menuButton.setTitle(getResources().getString(R.string.view)); menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); - menuButton.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton.setVisible((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); + menuButton.setEnabled((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); menuButton2.setIcon(R.drawable.ic_menu_info_details); menuButton2.setTitle(getResources().getString(R.string.playback)); menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); - menuButton2.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setVisible((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); + menuButton2.setEnabled((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); } - playFrag.play(intent.getIntExtra(getResources().getString(R.string.ta_startt), 0), intent.getStringExtra(getResources().getString(R.string.ta_songttl))); + playFrag.play(intent.getIntExtra(CommandStrings.ta_startt, 0), intent.getStringExtra(CommandStrings.ta_songttl)); if (plistFrag != null) { plistFrag.highlightMe = intent.getIntExtra("stupidNumber", -1); try { @@ -134,38 +135,38 @@ public void onReceive(Context context, Intent intent) { } break; - case 1: + case CommandStrings.ta_cmd_refresh_filebrowser: fileFrag.getDir(fileFrag.currPath); break; - case 2: + case CommandStrings.ta_cmd_load_filebrowser: try { - fileFrag.getDir(intent.getStringExtra(getResources().getString(R.string.ta_currpath))); + fileFrag.getDir(intent.getStringExtra(CommandStrings.ta_currpath)); } catch (IllegalStateException e) { } break; - case 3: - currSongName = intent.getStringExtra(getResources().getString(R.string.ta_filename)); + case CommandStrings.ta_cmd_gui_play_full: + currSongName = intent.getStringExtra(CommandStrings.ta_filename); if (viewPager.getCurrentItem() == 1) { menuButton.setIcon(R.drawable.ic_menu_agenda); menuButton.setTitle(getResources().getString(R.string.view)); menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); - menuButton.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton.setVisible((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); + menuButton.setEnabled((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); menuButton2.setIcon(R.drawable.ic_menu_info_details); menuButton2.setTitle(getResources().getString(R.string.playback)); menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); - menuButton2.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setVisible((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); + menuButton2.setEnabled((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); } - playFrag.play(intent.getIntExtra(getResources().getString(R.string.ta_startt), 0), intent.getStringExtra(getResources().getString(R.string.ta_songttl)), intent.getIntExtra(getResources().getString(R.string.ta_shufmode), 0), intent.getIntExtra(getResources().getString(R.string.ta_loopmode), 1)); + playFrag.play(intent.getIntExtra(CommandStrings.ta_startt, 0), intent.getStringExtra(CommandStrings.ta_songttl), intent.getIntExtra(CommandStrings.ta_shufmode, 0), intent.getIntExtra(CommandStrings.ta_loopmode, 1)); break; - case 4: + case CommandStrings.ta_cmd_copy_plist: plistFrag.currPlist = Globals.tmpplist; Globals.tmpplist = null; break; - case 5: // Notifiy pause/stop - if (!intent.getBooleanExtra(getResources().getString(R.string.ta_pause), false) && Globals.hardStop) { + case CommandStrings.ta_cmd_pause_stop: // Notifiy pause/stop + if (!intent.getBooleanExtra(CommandStrings.ta_pause, false) && Globals.hardStop) { Globals.hardStop = false; if (viewPager.getCurrentItem() == 1) { menuButton.setIcon(R.drawable.ic_menu_agenda); @@ -198,18 +199,18 @@ public void run() { } }); } - playFrag.pauseStop(intent.getBooleanExtra(getResources().getString(R.string.ta_pause), false), intent.getBooleanExtra(getResources().getString(R.string.ta_pausea), false)); + playFrag.pauseStop(intent.getBooleanExtra(CommandStrings.ta_pause, false), intent.getBooleanExtra(CommandStrings.ta_pausea, false)); break; - case 6: // notify art + case CommandStrings.ta_cmd_update_art: // notify art // currSongName = - // intent.getStringExtra(getResources().getString(R.string.ta_filename)); + // intent.getStringExtra(ServiceStrings.ta_filename)); if (playFrag != null) playFrag.setArt(); break; - // case 7: + // case ServiceStrings.ta_cmd_unused_7: // fileFrag.localfinished=true; // break; - case 8: + case CommandStrings.ta_cmd_special_notification_finished: if (special != null) { special.setLocalFinished(true); } @@ -295,7 +296,7 @@ public void actuallyRequestPermissions() { } public void yetAnotherInit() { - needInit = Globals.initialize(TimidityActivity.this); + needInit = SettingsStorage.initialize(TimidityActivity.this); } @Override @@ -324,8 +325,7 @@ public void onRequestPermissionsResult(int requestCode, String permissions[], in if (!good) { // permission denied, boo! Disable the app. - // TODO: only disable if files are inaccessible - new AlertDialog.Builder(TimidityActivity.this).setTitle("Error").setMessage("Timidity AE cannot proceed without these permissions").setPositiveButton("OK", new OnClickListener() { + new AlertDialog.Builder(TimidityActivity.this).setTitle("Error").setMessage("Timidity AE cannot proceed without these permissions.").setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { @@ -355,28 +355,28 @@ public void onClick(DialogInterface dialog, int which) { protected void onCreate(Bundle savedInstanceState) { deadlyDeath = false; if (savedInstanceState == null) { - Globals.reloadSettings(this, getAssets()); + SettingsStorage.reloadSettings(this, getAssets()); } else { // For some reason when I kill the activity and restart it, // justtheme is true, but Globals.theme = 0 - if (!savedInstanceState.getBoolean("justtheme", false) || Globals.theme == 0) { - Globals.reloadSettings(this, getAssets()); + if (!savedInstanceState.getBoolean("justtheme", false) || SettingsStorage.theme == 0) { + SettingsStorage.reloadSettings(this, getAssets()); } } try { System.loadLibrary("timidityhelper"); } catch (UnsatisfiedLinkError e) { Log.e("Bad:", "Cannot load timidityhelper"); - Globals.nativeMidi = Globals.onlyNative = true; + SettingsStorage.nativeMidi = SettingsStorage.onlyNative = true; } if (JNIHandler.loadLib(Globals.getLibDir(this) + "libtimidityplusplus.so") < 0) { Log.e("Bad:", "Cannot load timidityplusplus"); - Globals.nativeMidi = Globals.onlyNative = true; + SettingsStorage.nativeMidi = SettingsStorage.onlyNative = true; } else { Globals.libLoaded = true; } - oldTheme = Globals.theme; - this.setTheme((Globals.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); + oldTheme = SettingsStorage.theme; + this.setTheme((SettingsStorage.theme == 1) ? android.support.v7.appcompat.R.style.Theme_AppCompat_Light_DarkActionBar : android.support.v7.appcompat.R.style.Theme_AppCompat); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Log.i("Timidity", "Initializing"); @@ -401,7 +401,7 @@ protected void onCreate(Bundle savedInstanceState) { if (tmp != null) fileFrag = (FileBrowserFragment) tmp; if (!isMyServiceRunning(MusicService.class)) { - Globals.reloadSettings(this, getAssets()); + SettingsStorage.reloadSettings(this, getAssets()); initCallback2(); if (viewPager != null) { if (viewPager.getCurrentItem() == 1) { @@ -429,7 +429,7 @@ protected void onCreate(Bundle savedInstanceState) { if (activityReceiver != null) { // Create an intent filter to listen to the broadcast sent with the // action "ACTION_STRING_ACTIVITY" - IntentFilter intentFilter = new IntentFilter(getResources().getString(R.string.ta_rec)); + IntentFilter intentFilter = new IntentFilter(CommandStrings.ta_rec); // Map the intent filter to the receiver registerReceiver(activityReceiver, intentFilter); } @@ -482,15 +482,15 @@ public void onPageSelected(int index) { menuButton.setIcon(R.drawable.ic_menu_agenda); menuButton.setTitle(getResources().getString(R.string.view)); menuButton.setTitleCondensed(getResources().getString(R.string.viewcon)); - menuButton.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); - menuButton.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton.setVisible((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); + menuButton.setEnabled((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); } if (menuButton2 != null) { menuButton2.setIcon(R.drawable.ic_menu_info_details); menuButton2.setTitle(getResources().getString(R.string.playback)); menuButton2.setTitleCondensed(getResources().getString(R.string.playbackcon)); - menuButton2.setVisible((!JNIHandler.type) && Globals.isPlaying == 0); - menuButton2.setEnabled((!JNIHandler.type) && Globals.isPlaying == 0); + menuButton2.setVisible((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); + menuButton2.setEnabled((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying); } getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setHomeButtonEnabled(false); @@ -551,7 +551,7 @@ public void initCallback() { if (f != null) trueExt++; } - if ((permissions == null || permissions.isEmpty()) && Globals.shouldLolNag && trueExt > 1) { + if ((permissions == null || permissions.isEmpty()) && SettingsStorage.shouldExtStorageNag && trueExt > 1) { new AlertDialog.Builder(this).setTitle("SD Card Access").setCancelable(false).setMessage("Would you like to give Timidity AE write access to your external sd card? This is recommended if you're converting files or would like to place Timidity AE's data directory there. Problems may occur if a directory other than the root of your SD card is selected.").setPositiveButton("Yes", new OnClickListener() { @Override @@ -564,7 +564,7 @@ public void onClick(DialogInterface dialog, int which) { @Override public void onClick(DialogInterface dialog, int which) { - Globals.prefs.edit().putBoolean("shouldLolNag", Globals.shouldLolNag = false).commit(); + SettingsStorage.disableLollipopStorageNag(); initCallback2(); } @@ -578,7 +578,7 @@ public void onClick(DialogInterface dialog, int which) { } else { for (UriPermission permission : permissions) { if (permission.isReadPermission() && permission.isWritePermission()) { - Globals.theFold = permission.getUri(); + DocumentFileUtils.docFileDevice = permission.getUri(); } } @@ -590,9 +590,9 @@ public void onClick(DialogInterface dialog, int which) { } public void initCallback2() { - int x = JNIHandler.init(Globals.dataFolder + "timidity/", "timidity.cfg", Globals.mono, Globals.defSamp, Globals.sixteen, Globals.buff, Globals.aRate, Globals.preserveSilence, false, Globals.freeInsts); + int x = JNIHandler.init(SettingsStorage.dataFolder + "timidity/", "timidity.cfg", SettingsStorage.channelMode, SettingsStorage.defaultResamp, SettingsStorage.sixteenBit, SettingsStorage.bufferSize, SettingsStorage.audioRate, SettingsStorage.preserveSilence, false, SettingsStorage.freeInsts); if (x != 0 && x != -99) { - Globals.nativeMidi = true; + SettingsStorage.nativeMidi = true; Toast.makeText(this, String.format(getResources().getString(R.string.tcfg_error), x), Toast.LENGTH_LONG).show(); } handleIntentData(getIntent()); @@ -617,7 +617,7 @@ public void handleIntentData(Intent in) { if (dotPosition != -1) { extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US); if (extension != null) { - if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + if ((SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { files.add(ff.getPath()); if (ff.getPath().equals(data)) @@ -694,7 +694,7 @@ public void handleIntentData(Intent in) { if (dotPosition != -1) { extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US); if (extension != null) { - if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + if ((SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { files.add(ff.getPath()); if (ff.getPath().equals(Globals.getExternalCacheDir(this).getAbsolutePath() + '/' + filename)) @@ -716,7 +716,6 @@ public void handleIntentData(Intent in) { } } else { - System.out.println(in.getDataString()); Toast.makeText(this, getResources().getString(R.string.intErr2) + " (" + in.getData().getScheme() + ")", Toast.LENGTH_SHORT).show(); } } @@ -732,7 +731,7 @@ public void downloadFinished(String data, String theFilename) { if (dotPosition != -1) { extension = (name.substring(dotPosition)).toLowerCase(Locale.US); if (extension != null) { - if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + if ((SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { files.add(name); stop(); @@ -796,7 +795,7 @@ public boolean onOptionsItemSelected(MenuItem item) { fileFrag.setSelection(x); break; case 1: - if (playFrag != null && !JNIHandler.type) { + if (playFrag != null && !JNIHandler.isMediaPlayerFormat) { playFrag.incrementInterface(); } /* * else{ Toast.makeText(this, "Non midi file", @@ -813,11 +812,11 @@ public boolean onOptionsItemSelected(MenuItem item) { switch (mode) { case 0: if (fileFrag != null) - fileFrag.getDir(Globals.defaultFolder); + fileFrag.getDir(SettingsStorage.homeFolder); break; case 1: if (playFrag != null) { - if ((!JNIHandler.type) && Globals.isPlaying == 0) { + if ((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying) { playFrag.showMidiDialog(); } /* * else{ Toast.makeText(this, "Non midi file", @@ -835,8 +834,8 @@ public boolean onOptionsItemSelected(MenuItem item) { } else if (item.getItemId() == R.id.quit) { deadlyDeath = true; Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_stop); sendBroadcast(new_intent); stopService(new Intent(this, MusicService.class)); unregisterReceiver(activityReceiver); @@ -871,7 +870,7 @@ public void onBackPressed() { if (!fileFrag.currPath.matches("[/]+")) { fileFrag.getDir(new File(fileFrag.currPath).getParent().toString()); } else { - if (Globals.useDefaultBack) { + if (SettingsStorage.useDefaultBack) { super.onBackPressed(); return; } @@ -879,7 +878,7 @@ public void onBackPressed() { } break; case 1: - if (Globals.useDefaultBack) { + if (SettingsStorage.useDefaultBack) { super.onBackPressed(); return; } @@ -889,7 +888,7 @@ public void onBackPressed() { if (plistFrag.mode) plistFrag.getPlaylists(null); else { - if (Globals.useDefaultBack) { + if (SettingsStorage.useDefaultBack) { super.onBackPressed(); return; } @@ -911,19 +910,19 @@ public void selectedSong(ArrayList files, int songNumber, boolean begin, // plistFrag.getListView().setItemChecked(songNumber, true); Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_stop); sendBroadcast(new_intent); new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 0); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_load_plist_play); if (fileFrag != null) { - new_intent.putExtra(getResources().getString(R.string.msrv_currfold), fileFrag.currPath); + new_intent.putExtra(CommandStrings.msrv_currfold, fileFrag.currPath); } - new_intent.putExtra(getResources().getString(R.string.msrv_songnum), songNumber); - new_intent.putExtra(getResources().getString(R.string.msrv_begin), begin); - new_intent.putExtra(getResources().getString(R.string.msrv_dlplist), dontloadplist); + new_intent.putExtra(CommandStrings.msrv_songnum, songNumber); + new_intent.putExtra(CommandStrings.msrv_begin, begin); + new_intent.putExtra(CommandStrings.msrv_dlplist, dontloadplist); sendBroadcast(new_intent); } @@ -943,13 +942,13 @@ public int getCount() { public Fragment getItem(int position) { switch (position) { case 0: - fileFrag = FileBrowserFragment.create(Globals.defaultFolder); + fileFrag = FileBrowserFragment.create(SettingsStorage.homeFolder); return fileFrag; case 1: playFrag = PlayerFragment.create(); return playFrag; case 2: - plistFrag = PlaylistFragment.create(Globals.dataFolder + "playlists/"); + plistFrag = PlaylistFragment.create(SettingsStorage.dataFolder + "playlists/"); return plistFrag; default: return null; @@ -1000,69 +999,69 @@ public void needPlaylistBackCallback(boolean yes, boolean current) { // This is painful. public void play() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 1); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_play); sendBroadcast(new_intent); } public void pause() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 2); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_pause); sendBroadcast(new_intent); } public void next() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 3); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_next); sendBroadcast(new_intent); } public void prev() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 4); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_prev); sendBroadcast(new_intent); } public void stop() { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_stop); sendBroadcast(new_intent); } public void loop(int mode) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 6); - new_intent.putExtra(getResources().getString(R.string.msrv_loopmode), mode); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_loop_mode); + new_intent.putExtra(CommandStrings.msrv_loopmode, mode); sendBroadcast(new_intent); } public void shuffle(int mode) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 7); - new_intent.putExtra(getResources().getString(R.string.msrv_shufmode), mode); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_shuf_mode); + new_intent.putExtra(CommandStrings.msrv_shufmode, mode); sendBroadcast(new_intent); } public void seek(int time) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 9); - new_intent.putExtra(getResources().getString(R.string.msrv_seektime), time); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_seek); + new_intent.putExtra(CommandStrings.msrv_seektime, time); sendBroadcast(new_intent); } public void writeFile(String input, String output) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 14); - new_intent.putExtra(getResources().getString(R.string.msrv_infile), input); - new_intent.putExtra(getResources().getString(R.string.msrv_outfile), output); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_write_new); + new_intent.putExtra(CommandStrings.msrv_infile, input); + new_intent.putExtra(CommandStrings.msrv_outfile, output); sendBroadcast(new_intent); } @@ -1071,7 +1070,7 @@ public void writeFile(String input, String output) { protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == 1) { - if (oldTheme != Globals.theme) { + if (oldTheme != SettingsStorage.theme) { Intent intent = getIntent(); intent.putExtra("justtheme", true); intent.putExtra("needservice", false); @@ -1099,9 +1098,9 @@ public void loadCfg() { public void loadCfg(String path) { Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17); - new_intent.putExtra(getResources().getString(R.string.msrv_infile), path); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_load_cfg); + new_intent.putExtra(CommandStrings.msrv_infile, path); sendBroadcast(new_intent); } diff --git a/src/com/xperia64/timidityae/gui/TimidityAEWidgetProvider.java b/src/com/xperia64/timidityae/gui/TimidityAEWidgetProvider.java index 73e8e1d..487a164 100755 --- a/src/com/xperia64/timidityae/gui/TimidityAEWidgetProvider.java +++ b/src/com/xperia64/timidityae/gui/TimidityAEWidgetProvider.java @@ -14,6 +14,8 @@ import com.xperia64.timidityae.R; import com.xperia64.timidityae.TimidityActivity; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; import android.annotation.SuppressLint; import android.app.PendingIntent; @@ -39,15 +41,11 @@ public class TimidityAEWidgetProvider extends AppWidgetProvider { @Override public void onEnabled(Context context) { - //Log.v("toggle_widget","Enabled is being called"); AppWidgetManager mgr = AppWidgetManager.getInstance(context); - //retrieve a ref to the manager so we can pass a view update Intent i = new Intent(context, TimidityActivity.class); - //i.setClassName("com.xperia64.timidityae", "com.xperia64.timidityae.TimidityActivity"); PendingIntent myPI = PendingIntent.getActivity(context, 99, i, 0); - //intent to start service // Get the layout for the App Widget RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); @@ -123,7 +121,7 @@ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] a Display display = wm.getDefaultDisplay(); Point size=getDisplaySize(display); maxBitmap=size.x*size.y*1.5; - if((Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1)) + if((Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR1)) // TODO Seems safe maxBitmap*=4; } final int N = appWidgetIds.length; @@ -160,36 +158,36 @@ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] a Intent new_intent = new Intent(); //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), 4); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_prev); PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(context, 6, new_intent, 0); views.setOnClickPendingIntent(R.id.notPrev_widget, pendingNotificationIntent); // Play/Pause new_intent = new Intent(); //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), 13); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_play_or_pause); pendingNotificationIntent = PendingIntent.getBroadcast(context, 7, new_intent, 0); views.setOnClickPendingIntent(R.id.notPause_widget, pendingNotificationIntent); // Next new_intent = new Intent(); //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), 3); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_next); pendingNotificationIntent = PendingIntent.getBroadcast(context, 8, new_intent, 0); views.setOnClickPendingIntent(R.id.notNext_widget, pendingNotificationIntent); // Stop new_intent = new Intent(); //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); - new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), 5); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_stop); pendingNotificationIntent = PendingIntent.getBroadcast(context, 9, new_intent, 0); views.setOnClickPendingIntent(R.id.notStop_widget, pendingNotificationIntent); // Tell the AppWidgetManager to perform an upd_widgetate on the current app widget appWidgetManager.updateAppWidget(appWidgetId, views); } if(setdeath) - Globals.nukedWidgets=true; + SettingsStorage.nukedWidgets=true; super.onUpdate(context, appWidgetManager, appWidgetIds); } } diff --git a/src/com/xperia64/timidityae/gui/dialogs/FileBrowserDialog.java b/src/com/xperia64/timidityae/gui/dialogs/FileBrowserDialog.java index 0e54529..c36347c 100755 --- a/src/com/xperia64/timidityae/gui/dialogs/FileBrowserDialog.java +++ b/src/com/xperia64/timidityae/gui/dialogs/FileBrowserDialog.java @@ -18,7 +18,7 @@ import com.xperia64.timidityae.R; import com.xperia64.timidityae.util.FileComparator; -import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.SettingsStorage; import android.annotation.SuppressLint; import android.app.Activity; @@ -48,24 +48,25 @@ public class FileBrowserDialog implements OnItemClickListener { String msg; FileBrowserDialogListener onSelectedCallback; AlertDialog ddd; + public interface FileBrowserDialogListener { public void setItem(String path, int type); + public void write(); + public void ignore(); } boolean closeImmediately; // Should the dialog be closed immediately after selecting the file? @SuppressLint("InflateParams") - public void create(int type, String extensions, FileBrowserDialogListener onSelectedCallback, - Activity context, LayoutInflater layoutInflater, boolean closeImmediately, String path, String msg) - { + public void create(int type, String extensions, FileBrowserDialogListener onSelectedCallback, Activity context, LayoutInflater layoutInflater, boolean closeImmediately, String path, String msg) { this.onSelectedCallback = onSelectedCallback; - this.msg=msg; + this.msg = msg; this.context = context; this.extensions = extensions; this.type = type; // A command for later reference. 0 is files, otherwise - // folders + // folders this.closeImmediately = closeImmediately; // Close immediately after selecting a file/folder AlertDialog.Builder b = new AlertDialog.Builder(context); fbdLayout = (LinearLayout) layoutInflater.inflate(R.layout.list, null); @@ -73,41 +74,31 @@ public void create(int type, String extensions, FileBrowserDialogListener onSele fbdList.setOnItemClickListener(this); b.setView(fbdLayout); b.setCancelable(false); - b.setTitle(this.context.getResources().getString( - (type == 0) ? R.string.fb_chfi : R.string.fb_chfo)); - if (!closeImmediately) - { - b.setPositiveButton(this.context.getResources().getString(R.string.done), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) - { - FileBrowserDialog.this.onSelectedCallback.write(); - } - }); + b.setTitle(this.context.getResources().getString((type == 0) ? R.string.fb_chfi : R.string.fb_chfo)); + if (!closeImmediately) { + b.setPositiveButton(this.context.getResources().getString(R.string.done), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + FileBrowserDialog.this.onSelectedCallback.write(); + } + }); } - b.setNegativeButton( - context.getResources().getString(android.R.string.cancel), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) - { - FileBrowserDialog.this.onSelectedCallback.ignore(); - } - }); - if (type != 0) - { - b.setNeutralButton(this.context.getResources().getString(R.string.fb_fold), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) - { - } - }); + b.setNegativeButton(context.getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + FileBrowserDialog.this.onSelectedCallback.ignore(); + } + }); + if (type != 0) { + b.setNeutralButton(this.context.getResources().getString(R.string.fb_fold), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + } + }); } - if(path==null) + if (path == null) path = Environment.getExternalStorageDirectory().getAbsolutePath(); - else if(!new File(path).exists()) + else if (!new File(path).exists()) path = Environment.getExternalStorageDirectory().getAbsolutePath(); getDir(path); ddd = b.create(); @@ -116,44 +107,35 @@ else if(!new File(path).exists()) if (theButton != null) theButton.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) - { + public void onClick(View v) { FileBrowserDialog.this.onSelectedCallback.setItem(currPath, FileBrowserDialog.this.type); - if (FileBrowserDialog.this.closeImmediately) - { + if (FileBrowserDialog.this.closeImmediately) { ddd.dismiss(); } } }); } - public void getDir(String dirPath) - { + public void getDir(String dirPath) { currPath = dirPath; fname = new ArrayList(); path = new ArrayList(); - if (currPath != null) - { + if (currPath != null) { File f = new File(currPath); - if (f.exists()) - { + if (f.exists()) { File[] files = f.listFiles(); - if (files.length > 0) - { - if (files != null) - { + if (files.length > 0) { + if (files != null) { Arrays.sort(files, new FileComparator()); } - if (!currPath.matches("[/]+")) - { + if (!currPath.matches("[/]+")) { fname.add("../"); // Thank you Marshmallow. // Disallowing access to /storage/emulated has now prevent billions of hacking attempts daily. - if(new File(f.getParent()).canRead()) - { + if (new File(f.getParent()).canRead()) { path.add(f.getParent() + "/"); - }else{ + } else { path.add("/"); } } @@ -162,54 +144,39 @@ public void getDir(String dirPath) { File file = files[i]; - if ((!file.getName().startsWith(".") && !Globals.showHiddenFiles) - || Globals.showHiddenFiles) - { - if (file.isFile() && type == 0) - { - int dotPosition = file.getName().lastIndexOf( - "."); + if ((!file.getName().startsWith(".") && !SettingsStorage.showHiddenFiles) || SettingsStorage.showHiddenFiles) { + if (file.isFile() && type == 0) { + int dotPosition = file.getName().lastIndexOf("."); String extension = ""; - if (dotPosition != -1) - { - extension = (file.getName() - .substring(dotPosition)) - .toLowerCase(Locale.US); - if (extension != null) - { - - if (extensions.contains("*" + extension - + "*")) - { + if (dotPosition != -1) { + extension = (file.getName().substring(dotPosition)).toLowerCase(Locale.US); + if (extension != null) { + + if (extensions.contains("*" + extension + "*")) { path.add(file.getAbsolutePath()); fname.add(file.getName()); } - } else if (file.getName().endsWith("/")) - { + } else if (file.getName().endsWith("/")) { path.add(file.getAbsolutePath() + "/"); fname.add(file.getName() + "/"); } } - } else if (file.isDirectory()) - { + } else if (file.isDirectory()) { path.add(file.getAbsolutePath() + "/"); fname.add(file.getName() + "/"); } } } - } else - { - if (!currPath.matches("[/]+")) - { + } else { + if (!currPath.matches("[/]+")) { fname.add("../"); path.add(f.getParent() + "/"); } } - ArrayAdapter fileList = new ArrayAdapter( - context, R.layout.row, fname); + ArrayAdapter fileList = new ArrayAdapter(context, R.layout.row, fname); fbdList.setFastScrollEnabled(true); fbdList.setAdapter(fileList); } @@ -217,34 +184,29 @@ public void getDir(String dirPath) } @Override - public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) - { + public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { File file = new File(path.get(arg2)); System.out.println(path.get(arg2)); - if (file.isDirectory()) - { - if (file.canRead()) - { + if (file.isDirectory()) { + if (file.canRead()) { getDir(path.get(arg2)); - } else - { - new AlertDialog.Builder(context) - .setIcon(R.drawable.ic_launcher) - .setTitle( String.format("[%1$s] %2$s", file.getName(), context.getResources().getString(R.string.fb_cread))) - .setPositiveButton(context.getResources().getString(android.R.string.ok), - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which){} - }).show(); + } else { + AlertDialog.Builder unreadableDialog = new AlertDialog.Builder(context); + unreadableDialog = unreadableDialog.setIcon(R.drawable.ic_launcher); + unreadableDialog = unreadableDialog.setTitle(String.format("[%1$s] %2$s", file.getName(), context.getResources().getString(R.string.fb_cread))); + unreadableDialog = unreadableDialog.setPositiveButton(context.getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + } + }); + unreadableDialog.show(); } - } else - { - if (file.canRead()) - { - Toast.makeText(context, String.format("%1$s '%2$s'", msg, fname.get(arg2)),Toast.LENGTH_SHORT).show(); + } else { + if (file.canRead()) { + Toast.makeText(context, String.format("%1$s '%2$s'", msg, fname.get(arg2)), Toast.LENGTH_SHORT).show(); onSelectedCallback.setItem(file.getAbsolutePath(), type); - if(closeImmediately) + if (closeImmediately) ddd.dismiss(); } } diff --git a/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java b/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java index b808356..1796174 100755 --- a/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/FileBrowserFragment.java @@ -21,6 +21,8 @@ import com.xperia64.timidityae.TimidityActivity; import com.xperia64.timidityae.util.FileComparator; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; import android.app.AlertDialog; import android.content.Context; @@ -51,7 +53,7 @@ public interface ActionFileBackListener { public static FileBrowserFragment create(String fold) { Bundle args = new Bundle(); - args.putString(Globals.currFoldKey, fold); + args.putString(CommandStrings.currFoldKey, fold); FileBrowserFragment fragment = new FileBrowserFragment(); fragment.setArguments(args); return fragment; @@ -61,7 +63,7 @@ public static FileBrowserFragment create(String fold) { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) - currPath = getArguments().getString(Globals.currFoldKey); + currPath = getArguments().getString(CommandStrings.currFoldKey); if (currPath == null) currPath = Environment.getExternalStorageDirectory().getAbsolutePath(); else if (!new File(currPath).exists()) @@ -93,8 +95,8 @@ public void onAttach(Context activity) { } if (Globals.shouldRestore) { Intent new_intent = new Intent(); - new_intent.setAction(getActivity().getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getActivity().getResources().getString(R.string.msrv_cmd), 10); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_get_fold); getActivity().sendBroadcast(new_intent); } } @@ -112,15 +114,15 @@ public void getDir(String dirPath) { Arrays.sort(files, new FileComparator()); // System.out.println(currPath); - if (!currPath.matches("[/]+")) { - fname.add("../"); + if (!currPath.matches(Globals.repeatedSeparatorString)) { + fname.add(Globals.parentString); // Thank you Marshmallow. // Disallowing access to /storage/emulated has now // prevent billions of hacking attempts daily. if (new File(f.getParent()).canRead()) { - path.add(f.getParent() + "/"); + path.add(f.getParent() + File.separator); } else { - path.add("/"); + path.add(File.separator); } mCallback.needFileBackCallback(true); } else { @@ -128,7 +130,7 @@ public void getDir(String dirPath) { } for (int i = 0; i < files.length; i++) { File file = files[i]; - if ((!file.getName().startsWith(".") && !Globals.showHiddenFiles) || Globals.showHiddenFiles) { + if ((!file.getName().startsWith(".") && !SettingsStorage.showHiddenFiles) || SettingsStorage.showHiddenFiles) { if (file.isFile()) { int dotPosition = file.getName().lastIndexOf("."); String extension = ""; @@ -136,26 +138,26 @@ public void getDir(String dirPath) { extension = (file.getName().substring(dotPosition)).toLowerCase(Locale.US); if (extension != null) { - if ((Globals.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + if ((SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { path.add(file.getAbsolutePath()); fname.add(file.getName()); } - } else if (file.getName().endsWith("/")) { - path.add(file.getAbsolutePath() + "/"); - fname.add(file.getName() + "/"); + } else if (file.getName().endsWith(File.separator)) { + path.add(file.getAbsolutePath() + File.separator); + fname.add(file.getName() + File.separator); } } } else { - path.add(file.getAbsolutePath() + "/"); - fname.add(file.getName() + "/"); + path.add(file.getAbsolutePath() + File.separator); + fname.add(file.getName() + File.separator); } } } } else { - if (!currPath.matches("[/]+")) { - fname.add("../"); - path.add(f.getParent() + "/"); + if (!currPath.matches(Globals.repeatedSeparatorString)) { + fname.add(Globals.parentString); + path.add(f.getParent() + File.separator); } } @@ -165,7 +167,6 @@ public void getDir(String dirPath) { @Override public boolean onItemLongClick(AdapterView l, View v, final int position, long id) { - System.out.println("Derp" + "Drip"); if (Globals.isMidi(path.get(position))) { ((TimidityActivity) getActivity()).dynExport(path.get(position), false); return true; @@ -182,23 +183,26 @@ public boolean onItemLongClick(AdapterView l, View v, final int position, lon @Override public void onListItemClick(ListView l, View v, int position, long id) { File file = new File(path.get(position)); - System.out.println(path.get(position)); if (file.isDirectory()) { if (file.canRead()) { getDir(path.get(position)); } else { - new AlertDialog.Builder(getActivity()).setIcon(R.drawable.ic_launcher).setTitle(String.format("[%1$s] %2$s", file.getName(), getResources().getString(R.string.fb_cread))).setPositiveButton(getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { + AlertDialog.Builder unreadableDialog = new AlertDialog.Builder(getActivity()); + unreadableDialog = unreadableDialog.setIcon(R.drawable.ic_launcher); + unreadableDialog = unreadableDialog.setTitle(String.format("[%1$s] %2$s", file.getName(), getActivity().getResources().getString(R.string.fb_cread))); + unreadableDialog = unreadableDialog.setPositiveButton(getActivity().getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } - }).show(); + }); + unreadableDialog.show(); } } else { if (file.canRead()) { ArrayList files = new ArrayList(); int firstFile = -1; for (int i = 0; i < path.size(); i++) { - if (!path.get(i).endsWith("/")) { + if (!path.get(i).endsWith(File.separator)) { files.add(path.get(i)); if (firstFile == -1) { firstFile = i; @@ -213,6 +217,6 @@ public void onClick(DialogInterface dialog, int which) { @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - outState.putString(Globals.currFoldKey, currPath); + outState.putString(CommandStrings.currFoldKey, currPath); } } diff --git a/src/com/xperia64/timidityae/gui/fragments/LyricFragment.java b/src/com/xperia64/timidityae/gui/fragments/LyricFragment.java index 83c83d8..28529cc 100755 --- a/src/com/xperia64/timidityae/gui/fragments/LyricFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/LyricFragment.java @@ -24,21 +24,18 @@ import com.xperia64.timidityae.R; public class LyricFragment extends Fragment { - TextView lyrics; - ScrollView scrollContainer; - boolean ready; + private TextView lyrics; + private ScrollView scrollContainer; + private boolean ready; // TODO Make lyrics shiny-er @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - ready = false; View root = inflater.inflate(R.layout.lyrical_fragment, container, false); lyrics = (TextView) root.findViewById(R.id.lyrics); scrollContainer = (ScrollView) root.findViewById(R.id.lyric_holder); - return root; - } @Override diff --git a/src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java b/src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java index a362bcb..56f302b 100755 --- a/src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/PlayerFragment.java @@ -51,16 +51,19 @@ import com.xperia64.timidityae.JNIHandler; import com.xperia64.timidityae.R; import com.xperia64.timidityae.TimidityActivity; +import com.xperia64.timidityae.util.DocumentFileUtils; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; @SuppressLint("Recycle") public class PlayerFragment extends Fragment { - - public boolean shouldAdvance=true; - public int loopMode=1; - public int shuffleMode=0; + + public boolean shouldAdvance = true; + public int loopMode = 1; + public int shuffleMode = 0; boolean firstSelection; - boolean sliding=false; + boolean sliding = false; // public TimidityActivity mActivity; // @@ -85,27 +88,29 @@ public class PlayerFragment extends Fragment { int totalSeconds; int currMinutes; int currSeconds; - int fragMode=0; // 0 = AlbumArt, 1 = midi controls, 2 = Kareoke - boolean ffrw=false; - boolean enabledControls=false; - boolean canEnablePlay=true; + int fragMode = 0; // 0 = AlbumArt, 1 = midi controls, 2 = Kareoke + boolean ffrw = false; + boolean enabledControls = false; + boolean canEnablePlay = true; boolean updaterPlacid = false; // public AlertDialog ddd; TextView tempo; TextView pitch; TextView voices; + // public static PlayerFragment create() { PlayerFragment fragment = new PlayerFragment(); return fragment; - } + } + @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - mActivity=(TimidityActivity) getActivity(); + super.onCreate(savedInstanceState); + mActivity = (TimidityActivity) getActivity(); } - + Handler seekHandler = new Handler(); Runnable seekbarUpdater = new Runnable() { @@ -114,329 +119,309 @@ public void run() { seekUpdation(); } }; - Runnable lyricUpdater = new Runnable() - { + Runnable lyricUpdater = new Runnable() { @Override - public void run() - { + public void run() { lyricUpdation(); } }; - public void lyricUpdation() - { - if(Globals.isPlaying==0) - { - if(!JNIHandler.type&&fragMode==2) - { + + public void lyricUpdation() { + if (JNIHandler.isPlaying) { + if (!JNIHandler.isMediaPlayerFormat && fragMode == 2) { lyrical.updateLyrics(); } - seekHandler.postDelayed(lyricUpdater,10); + seekHandler.postDelayed(lyricUpdater, 10); } - + } + public void seekUpdation() { - if(Globals.isPlaying==0&&isAdded()) - { - if(!JNIHandler.type) - { - if(JNIHandler.mAudioTrack!=null) - { - if((JNIHandler.exceptional&1)!=0) - { + if (JNIHandler.isPlaying && isAdded()) { + if (!JNIHandler.isMediaPlayerFormat) { + if (JNIHandler.mAudioTrack != null) { + if ((JNIHandler.exceptional & 1) != 0) { Toast.makeText(getActivity(), "Error initializing AudioTrack. Try decreasing the buffer size.", Toast.LENGTH_LONG).show(); - shouldAdvance=false; - canEnablePlay=true; + shouldAdvance = false; + canEnablePlay = true; mActivity.stop(); } - try{ - if(!enabledControls&&(JNIHandler.mAudioTrack.getPlaybackHeadPosition()>=500)) - { - enabledControls=true; - canEnablePlay=true; - fastForwardButton.setEnabled(true); - rewindButton.setEnabled(true); - trackBar.setEnabled(true); - playButton.setEnabled(true); - } - }catch(Exception e) - { - + try { + if (!enabledControls && (JNIHandler.mAudioTrack.getPlaybackHeadPosition() >= 500)) { + enabledControls = true; + canEnablePlay = true; + fastForwardButton.setEnabled(true); + rewindButton.setEnabled(true); + trackBar.setEnabled(true); + playButton.setEnabled(true); + } + } catch (Exception e) { + } } - }else{ - enabledControls=true; - canEnablePlay=true; + } else { + enabledControls = true; + canEnablePlay = true; fastForwardButton.setEnabled(true); rewindButton.setEnabled(true); trackBar.setEnabled(true); playButton.setEnabled(true); } - if(fragMode==1) - { + if (fragMode == 1) { tracky.updateList(); } - if(ddd!=null&&ddd.isShowing()) - { - if(tempo!=null) - tempo.setText(String.format(getResources().getString(R.string.mop_tempo),JNIHandler.ttr, (int) (500000 / (double) JNIHandler.tt * 120 * (double) JNIHandler.ttr / 100 + 0.5))); - if(pitch!=null) - pitch.setText(String.format(getResources().getString(R.string.mop_pitch),((JNIHandler.koffset>0)?"+":"")+Integer.toString(JNIHandler.koffset))); - if(voices!=null) + if (ddd != null && ddd.isShowing()) { + if (tempo != null) + tempo.setText(String.format(getResources().getString(R.string.mop_tempo), JNIHandler.playbackPercentage, (int) (500000 / (double) JNIHandler.playbackTempo * 120 * (double) JNIHandler.playbackPercentage / 100 + 0.5))); + if (pitch != null) + pitch.setText(String.format(getResources().getString(R.string.mop_pitch), ((JNIHandler.keyOffset > 0) ? "+" : "") + Integer.toString(JNIHandler.keyOffset))); + if (voices != null) voices.setText(String.format(getResources().getString(R.string.mop_voice), JNIHandler.voice, JNIHandler.maxvoice)); } - try { //NOPE - if(JNIHandler.mMediaPlayer!=null&&JNIHandler.type&&JNIHandler.mMediaPlayer.isPlaying()) // Are these evaluated in order? I hope so - { - JNIHandler.currTime=JNIHandler.mMediaPlayer.getCurrentPosition(); - }}catch (Exception e) {} - if(getActivity()!=null&&!sliding) - { - updaterPlacid=false; + try { // NOPE + if (JNIHandler.mMediaPlayer != null && JNIHandler.isMediaPlayerFormat && JNIHandler.mMediaPlayer.isPlaying()) // Are these evaluated in order? I hope so + { + JNIHandler.currTime = JNIHandler.mMediaPlayer.getCurrentPosition(); + } + } catch (Exception e) { + } + if (getActivity() != null && !sliding) { + updaterPlacid = false; totalMinutes = 0; - totalSeconds = JNIHandler.maxTime; + totalSeconds = JNIHandler.maxTime; currMinutes = 0; currSeconds = JNIHandler.currTime; - if(JNIHandler.type) - { - totalSeconds /= 1000; // ms to s - currSeconds /= 1000; - } - totalMinutes=totalSeconds/60; - totalSeconds%=60; - currMinutes=currSeconds/60; - currSeconds%=60; - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - trackBar.setMax(JNIHandler.maxTime); - trackBar.setProgress(JNIHandler.currTime); - trackBar.invalidate(); - - timeCounter.setText(String.format("%d:%02d/%d:%02d",currMinutes,currSeconds,totalMinutes,totalSeconds)); - timeCounter.invalidate(); - } - }); - seekHandler.postDelayed(seekbarUpdater, 500); - }else{ - updaterPlacid=true; + if (JNIHandler.isMediaPlayerFormat) { + totalSeconds /= 1000; // ms to s + currSeconds /= 1000; + } + totalMinutes = totalSeconds / 60; + totalSeconds %= 60; + currMinutes = currSeconds / 60; + currSeconds %= 60; + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + trackBar.setMax(JNIHandler.maxTime); + trackBar.setProgress(JNIHandler.currTime); + trackBar.invalidate(); + + timeCounter.setText(String.format("%d:%02d/%d:%02d", currMinutes, currSeconds, totalMinutes, totalSeconds)); + timeCounter.invalidate(); + } + }); + seekHandler.postDelayed(seekbarUpdater, 500); + } else { + updaterPlacid = true; } } } - + @Override - public void onAttach(Context activity) - { + public void onAttach(Context activity) { super.onAttach(activity); - if(Globals.shouldRestore) - { - Intent new_intent = new Intent(); - new_intent.setAction(getActivity().getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getActivity().getResources().getString(R.string.msrv_cmd), 11); - getActivity().sendBroadcast(new_intent); - } + if (Globals.shouldRestore) { + Intent new_intent = new Intent(); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_get_info); + getActivity().sendBroadcast(new_intent); + } } + @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { - View v = inflater.inflate(R.layout.player, container, false); - previousButton = (ImageButton) v.findViewById(R.id.previousButton); - rewindButton = (ImageButton) v.findViewById(R.id.rewindButton); - playButton = (ImageButton) v.findViewById(R.id.playButton); - fastForwardButton = (ImageButton) v.findViewById(R.id.fastForwardButton); - nextButton = (ImageButton) v.findViewById(R.id.nextButton); - shuffleButton = (ImageButton) v.findViewById(R.id.shuffleButton); - loopButton = (ImageButton) v.findViewById(R.id.loopButton); - stopButton = (ImageButton) v.findViewById(R.id.stopButton); - trackBar = (SeekBar) v.findViewById(R.id.seekBar); - songTitle = (TextView) v.findViewById(R.id.songTitle); - timeCounter = (TextView) v.findViewById(R.id.timeCount); - subContainer = (FrameLayout) v.findViewById(R.id.midiContainer); - return v; - } - public void pauseStop(boolean cmd, final boolean arg) - { - if(cmd) // pause + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.player, container, false); + previousButton = (ImageButton) v.findViewById(R.id.previousButton); + rewindButton = (ImageButton) v.findViewById(R.id.rewindButton); + playButton = (ImageButton) v.findViewById(R.id.playButton); + fastForwardButton = (ImageButton) v.findViewById(R.id.fastForwardButton); + nextButton = (ImageButton) v.findViewById(R.id.nextButton); + shuffleButton = (ImageButton) v.findViewById(R.id.shuffleButton); + loopButton = (ImageButton) v.findViewById(R.id.loopButton); + stopButton = (ImageButton) v.findViewById(R.id.stopButton); + trackBar = (SeekBar) v.findViewById(R.id.seekBar); + songTitle = (TextView) v.findViewById(R.id.songTitle); + timeCounter = (TextView) v.findViewById(R.id.timeCount); + subContainer = (FrameLayout) v.findViewById(R.id.midiContainer); + return v; + } + + public void pauseStop(boolean cmd, final boolean arg) { + if (cmd) // pause { - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - playButton.setImageResource((arg)?R.drawable.ic_media_play:R.drawable.ic_media_pause); - } - }); - - }else{ // stop - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - trackBar.setProgress(0); - trackBar.setMax(0); - trackBar.setEnabled(false); - rewindButton.setEnabled(false); - fastForwardButton.setEnabled(false); - if(canEnablePlay) - { - playButton.setEnabled(true); - } - playButton.setImageResource(R.drawable.ic_media_play); - } - }); + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + playButton.setImageResource((arg) ? R.drawable.ic_media_play : R.drawable.ic_media_pause); + } + }); + + } else { // stop + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + trackBar.setProgress(0); + trackBar.setMax(0); + trackBar.setEnabled(false); + rewindButton.setEnabled(false); + fastForwardButton.setEnabled(false); + if (canEnablePlay) { + playButton.setEnabled(true); + } + playButton.setImageResource(R.drawable.ic_media_play); + } + }); } } + @SuppressLint("Recycle") @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); FragmentManager fm = getFragmentManager(); - FragmentTransaction ft = fm.beginTransaction(); + FragmentTransaction ft = fm.beginTransaction(); - fm.beginTransaction(); + fm.beginTransaction(); artsy = new ArtFragment(); ft.replace(R.id.midiContainer, artsy); - ft.commit(); - previousButton.setOnClickListener(new OnClickListener(){ + ft.commit(); + previousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - shouldAdvance=false; - canEnablePlay=false; + shouldAdvance = false; + canEnablePlay = false; playButton.setEnabled(false); mActivity.prev(); } }); rewindButton.setEnabled(false); - rewindButton.setOnClickListener(new OnClickListener(){ + rewindButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - ffrw=true; - int to = trackBar.getProgress()-(JNIHandler.type?3000:3); - to=(to>trackBar.getMax()?trackBar.getMax():to<0?0:to); + ffrw = true; + int to = trackBar.getProgress() - (JNIHandler.isMediaPlayerFormat ? 3000 : 3); + to = (to > trackBar.getMax() ? trackBar.getMax() : to < 0 ? 0 : to); trackBar.setProgress(to); } }); - rewindButton.setOnLongClickListener(new OnLongClickListener(){ + rewindButton.setOnLongClickListener(new OnLongClickListener() { private Handler mHandler = new Handler(); int count; int mult; + @Override public boolean onLongClick(View arg0) { - count=0; - mult=1; - ffrw=true; + count = 0; + mult = 1; + ffrw = true; mHandler.post(mAction); return true; } + Runnable mAction = new Runnable() { - @Override public void run() { - sliding=true; - int to = trackBar.getProgress()-(3*mult*(JNIHandler.type?1000:1)); - to=(to>trackBar.getMax()?trackBar.getMax():to<0?0:to); + @Override + public void run() { + sliding = true; + int to = trackBar.getProgress() - (3 * mult * (JNIHandler.isMediaPlayerFormat ? 1000 : 1)); + to = (to > trackBar.getMax() ? trackBar.getMax() : to < 0 ? 0 : to); trackBar.setProgress(to); - if(rewindButton.isPressed()) - { - if(count++>5) - { - count=0; + if (rewindButton.isPressed()) { + if (count++ > 5) { + count = 0; mult++; } mHandler.postDelayed(this, 500); - } - else - { - sliding=false; - if(!JNIHandler.type) - mActivity.seek(trackBar.getProgress()); + } else { + sliding = false; + if (!JNIHandler.isMediaPlayerFormat) + mActivity.seek(trackBar.getProgress()); seekUpdation(); } - } - }; - + } + }; + }); playButton.setEnabled(false); // > - playButton.setOnClickListener(new OnClickListener(){ + playButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - if(Globals.isPlaying==0) - { + if (JNIHandler.isPlaying) { mActivity.pause(); - }else{ + } else { arg0.setEnabled(false); mActivity.play(); } } }); fastForwardButton.setEnabled(false); - fastForwardButton.setOnClickListener(new OnClickListener(){ + fastForwardButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - ffrw=true; - int to = trackBar.getProgress()+(JNIHandler.type?3000:3); - to=(to>trackBar.getMax()?trackBar.getMax():to<0?0:to); + ffrw = true; + int to = trackBar.getProgress() + (JNIHandler.isMediaPlayerFormat ? 3000 : 3); + to = (to > trackBar.getMax() ? trackBar.getMax() : to < 0 ? 0 : to); trackBar.setProgress(to); } }); - fastForwardButton.setOnLongClickListener(new OnLongClickListener(){ + fastForwardButton.setOnLongClickListener(new OnLongClickListener() { private Handler mHandler = new Handler(); int count; int mult; + @Override public boolean onLongClick(View arg0) { count = 0; mult = 1; - ffrw=true; + ffrw = true; mHandler.post(mAction); return true; } + Runnable mAction = new Runnable() { - @Override public void run() { - sliding=true; - int to = trackBar.getProgress()+(3*mult*(JNIHandler.type?1000:1)); - to=(to>trackBar.getMax()?trackBar.getMax():to<0?0:to); + @Override + public void run() { + sliding = true; + int to = trackBar.getProgress() + (3 * mult * (JNIHandler.isMediaPlayerFormat ? 1000 : 1)); + to = (to > trackBar.getMax() ? trackBar.getMax() : to < 0 ? 0 : to); trackBar.setProgress(to); - if(fastForwardButton.isPressed()) - { - if(count++>5) - { - count=0; + if (fastForwardButton.isPressed()) { + if (count++ > 5) { + count = 0; mult++; } mHandler.postDelayed(this, 500); - } - else - { - sliding=false; - if(!JNIHandler.type) - mActivity.seek(trackBar.getProgress()); + } else { + sliding = false; + if (!JNIHandler.isMediaPlayerFormat) + mActivity.seek(trackBar.getProgress()); seekUpdation(); } - } - }; - + } + }; + }); - nextButton.setOnClickListener(new OnClickListener(){ + nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - shouldAdvance=false; - canEnablePlay=false; + shouldAdvance = false; + canEnablePlay = false; playButton.setEnabled(false); mActivity.next(); } }); - shuffleButton.setOnClickListener(new OnClickListener(){ + shuffleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - if(++shuffleMode>2) - shuffleMode=0; + if (++shuffleMode > 2) + shuffleMode = 0; int shufRes = R.drawable.ic_menu_forward; - switch(shuffleMode) - { + switch (shuffleMode) { case 0: shufRes = R.drawable.ic_menu_forward; break; @@ -451,137 +436,133 @@ public void onClick(View arg0) { mActivity.shuffle(shuffleMode); } }); - loopButton.setOnClickListener(new OnClickListener(){ + loopButton.setOnClickListener(new OnClickListener() { @Override - public void onClick(final View arg0) - { - if(++loopMode>2){loopMode=0;} - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - switch(loopMode) - { - case 0: - ((ImageButton) arg0).setImageResource(R.drawable.ic_menu_forward); - break; - case 1: - ((ImageButton) arg0).setImageResource(R.drawable.ic_menu_refresh); - break; - case 2: - ((ImageButton) arg0).setImageResource(R.drawable.ic_menu_rotate); - break; - } - } - }); + public void onClick(final View arg0) { + if (++loopMode > 2) { + loopMode = 0; + } + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + switch (loopMode) { + case 0: + ((ImageButton) arg0).setImageResource(R.drawable.ic_menu_forward); + break; + case 1: + ((ImageButton) arg0).setImageResource(R.drawable.ic_menu_refresh); + break; + case 2: + ((ImageButton) arg0).setImageResource(R.drawable.ic_menu_rotate); + break; + } + } + }); mActivity.loop(loopMode); } }); - stopButton.setOnClickListener(new OnClickListener(){ + stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - shouldAdvance=false; - canEnablePlay=true; + shouldAdvance = false; + canEnablePlay = true; mActivity.stop(); } }); trackBar.setEnabled(false); - trackBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() - { + trackBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) { - if(arg2||ffrw) - { - if(arg0.isEnabled()&&(JNIHandler.type||ffrw)) - { + if (arg2 || ffrw) { + if (arg0.isEnabled() && (JNIHandler.isMediaPlayerFormat || ffrw)) { mActivity.seek(arg1); } - if(!fastForwardButton.isPressed()&&!rewindButton.isPressed()) - ffrw=false; + if (!fastForwardButton.isPressed() && !rewindButton.isPressed()) + ffrw = false; totalMinutes = 0; - totalSeconds = arg0.getMax(); + totalSeconds = arg0.getMax(); currMinutes = 0; currSeconds = arg1; - if(JNIHandler.type) - { - totalSeconds /= 1000; // ms to s - currSeconds /= 1000; - } - totalMinutes=totalSeconds/60; - totalSeconds%=60; - currMinutes=currSeconds/60; - currSeconds%=60; - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - - timeCounter.setText(String.format("%d:%02d/%d:%02d",currMinutes,currSeconds,totalMinutes,totalSeconds)); - timeCounter.invalidate(); - } - }); + if (JNIHandler.isMediaPlayerFormat) { + totalSeconds /= 1000; // ms to s + currSeconds /= 1000; + } + totalMinutes = totalSeconds / 60; + totalSeconds %= 60; + currMinutes = currSeconds / 60; + currSeconds %= 60; + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + + timeCounter.setText(String.format("%d:%02d/%d:%02d", currMinutes, currSeconds, totalMinutes, totalSeconds)); + timeCounter.invalidate(); + } + }); } } - @Override public void onStartTrackingTouch(SeekBar arg0) {sliding=true; } - @Override public void onStopTrackingTouch(SeekBar arg0) { - - sliding=false; - if(!JNIHandler.type) - mActivity.seek(arg0.getProgress()); - if(updaterPlacid) seekUpdation();} - + + @Override + public void onStartTrackingTouch(SeekBar arg0) { + sliding = true; + } + + @Override + public void onStopTrackingTouch(SeekBar arg0) { + + sliding = false; + if (!JNIHandler.isMediaPlayerFormat) + mActivity.seek(arg0.getProgress()); + if (updaterPlacid) + seekUpdation(); + } + }); - + trackBar.setIndeterminate(false); - ((TimidityActivity)getActivity()).readyForInit(); + ((TimidityActivity) getActivity()).readyForInit(); } - - public void play(final int seekBarTime, final String title, final int shuffleMode, final int loopMode) - { - enabledControls=false; - canEnablePlay=false; + + public void play(final int seekBarTime, final String title, final int shuffleMode, final int loopMode) { + enabledControls = false; + canEnablePlay = false; playButton.setEnabled(false); - if(tracky!=null) + if (tracky != null) tracky.reset(); - - if(ddd!=null) - { - if(ddd.isShowing()) - { + + if (ddd != null) { + if (ddd.isShowing()) { ddd.dismiss(); - ddd=null; + ddd = null; } } - this.shuffleMode=shuffleMode; - this.loopMode=loopMode; - if(getActivity()!=null) - { - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - playButton.setImageResource(R.drawable.ic_media_pause); - trackBar.setMax(seekBarTime); - trackBar.setProgress(0); - songTitle.setText(title); - seekUpdation(); - if(!JNIHandler.type)lyricUpdation(); - switch(loopMode) - { - case 0: - loopButton.setImageResource(R.drawable.ic_menu_forward); - break; - case 1: - loopButton.setImageResource(R.drawable.ic_menu_refresh); - break; - case 2: - loopButton.setImageResource(R.drawable.ic_menu_rotate); - break; - } - int shufRes = R.drawable.ic_menu_forward; - switch(shuffleMode) - { + this.shuffleMode = shuffleMode; + this.loopMode = loopMode; + if (getActivity() != null) { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + playButton.setImageResource(R.drawable.ic_media_pause); + trackBar.setMax(seekBarTime); + trackBar.setProgress(0); + songTitle.setText(title); + seekUpdation(); + if (!JNIHandler.isMediaPlayerFormat) + lyricUpdation(); + switch (loopMode) { + case 0: + loopButton.setImageResource(R.drawable.ic_menu_forward); + break; + case 1: + loopButton.setImageResource(R.drawable.ic_menu_refresh); + break; + case 2: + loopButton.setImageResource(R.drawable.ic_menu_rotate); + break; + } + int shufRes = R.drawable.ic_menu_forward; + switch (shuffleMode) { case 0: shufRes = R.drawable.ic_menu_forward; break; @@ -593,128 +574,123 @@ public void run() break; } shuffleButton.setImageResource(shufRes); - } - }); - if(JNIHandler.type&&fragMode!=0) - { - FragmentManager fm = getFragmentManager(); - FragmentTransaction ft = fm.beginTransaction(); - fragMode=0; - fm.beginTransaction(); - artsy = new ArtFragment(); - ft.replace(R.id.midiContainer, artsy); - ft.commitAllowingStateLoss(); - } + } + }); + if (JNIHandler.isMediaPlayerFormat && fragMode != 0) { + FragmentManager fm = getFragmentManager(); + FragmentTransaction ft = fm.beginTransaction(); + fragMode = 0; + fm.beginTransaction(); + artsy = new ArtFragment(); + ft.replace(R.id.midiContainer, artsy); + ft.commitAllowingStateLoss(); + } } } - public void play(final int seekBarTime, final String title) - { - enabledControls=false; - canEnablePlay=false; + + public void play(final int seekBarTime, final String title) { + enabledControls = false; + canEnablePlay = false; playButton.setEnabled(false); - if(tracky!=null) + if (tracky != null) tracky.reset(); - - if(ddd!=null) - { - if(ddd.isShowing()) - { + + if (ddd != null) { + if (ddd.isShowing()) { ddd.dismiss(); - ddd=null; + ddd = null; } } - if(getActivity()!=null) - { - getActivity().runOnUiThread(new Runnable(){ - @Override - public void run() - { - playButton.setImageResource(R.drawable.ic_media_pause); - trackBar.setProgress(0); - trackBar.setMax(seekBarTime); - songTitle.setText(title); - seekUpdation(); - if(!JNIHandler.type)lyricUpdation(); - } - }); + if (getActivity() != null) { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + playButton.setImageResource(R.drawable.ic_media_pause); + trackBar.setProgress(0); + trackBar.setMax(seekBarTime); + songTitle.setText(title); + seekUpdation(); + if (!JNIHandler.isMediaPlayerFormat) + lyricUpdation(); + } + }); } - if(JNIHandler.type&&fragMode!=0) - { + if (JNIHandler.isMediaPlayerFormat && fragMode != 0) { FragmentManager fm = getFragmentManager(); - FragmentTransaction ft = fm.beginTransaction(); - fragMode=0; - fm.beginTransaction(); + FragmentTransaction ft = fm.beginTransaction(); + fragMode = 0; + fm.beginTransaction(); artsy = new ArtFragment(); ft.replace(R.id.midiContainer, artsy); - ft.commitAllowingStateLoss(); + ft.commitAllowingStateLoss(); } } + public void incrementInterface() { FragmentManager fm = getFragmentManager(); - FragmentTransaction ft = fm.beginTransaction(); + FragmentTransaction ft = fm.beginTransaction(); - fm.beginTransaction(); - if((!JNIHandler.type)&&Globals.isPlaying==0) - { - if(++fragMode>2) - fragMode=0; - }else{ - fragMode=0; + fm.beginTransaction(); + if ((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying) { + if (++fragMode > 2) + fragMode = 0; + } else { + fragMode = 0; } - switch(fragMode) - { + switch (fragMode) { case 0: artsy = new ArtFragment(); ft.replace(R.id.midiContainer, artsy); - ft.commitAllowingStateLoss(); + ft.commitAllowingStateLoss(); break; case 1: tracky = new TrackFragment(); ft.replace(R.id.midiContainer, tracky); - ft.commitAllowingStateLoss(); + ft.commitAllowingStateLoss(); break; case 2: lyrical = new LyricFragment(); ft.replace(R.id.midiContainer, lyrical); - ft.commitAllowingStateLoss(); - break; + ft.commitAllowingStateLoss(); + break; } } + public void setInterface(int which) { FragmentManager fm = getFragmentManager(); - FragmentTransaction ft = fm.beginTransaction(); - fragMode=which; - fm.beginTransaction(); - if((!JNIHandler.type)&&Globals.isPlaying==0) - { - if(fragMode>2) - fragMode=0; - }else{ - fragMode=0; + FragmentTransaction ft = fm.beginTransaction(); + fragMode = which; + fm.beginTransaction(); + if ((!JNIHandler.isMediaPlayerFormat) && JNIHandler.isPlaying) { + if (fragMode > 2) + fragMode = 0; + } else { + fragMode = 0; } - switch(fragMode) - { + switch (fragMode) { case 0: artsy = new ArtFragment(); ft.replace(R.id.midiContainer, artsy); - ft.commitAllowingStateLoss(); + ft.commitAllowingStateLoss(); break; case 1: tracky = new TrackFragment(); ft.replace(R.id.midiContainer, tracky); - ft.commitAllowingStateLoss(); + ft.commitAllowingStateLoss(); break; case 2: lyrical = new LyricFragment(); ft.replace(R.id.midiContainer, lyrical); - ft.commitAllowingStateLoss(); - break; + ft.commitAllowingStateLoss(); + break; } } - /*public void updateMidiDialog(boolean which[], int t, int tr, int voices) - { - - }*/ + + /* + * public void updateMidiDialog(boolean which[], int t, int tr, int voices) { + * + * } + */ @SuppressLint("InflateParams") public void showMidiDialog() { AlertDialog.Builder b = new AlertDialog.Builder(getActivity()); @@ -730,324 +706,291 @@ public void showMidiDialog() { Button loadCfg = (Button) v.findViewById(R.id.loadCfg); Button savedefCfg = (Button) v.findViewById(R.id.savedefCfg); final Button deldefCfg = (Button) v.findViewById(R.id.deldefCfg); - deldefCfg.setEnabled(new File( mActivity.currSongName+".def.tcf").exists()||new File( mActivity.currSongName+".def.tzf").exists()); + deldefCfg.setEnabled(new File(mActivity.currSongName + ".def.tcf").exists() || new File(mActivity.currSongName + ".def.tzf").exists()); tempo = (TextView) v.findViewById(R.id.tempoText); pitch = (TextView) v.findViewById(R.id.pitchText); voices = (TextView) v.findViewById(R.id.voiceText); - - tempo.setText(String.format(getResources().getString(R.string.mop_tempo),JNIHandler.ttr, (int) (500000 / (double) JNIHandler.tt * 120 * (double) JNIHandler.ttr / 100 + 0.5))); - pitch.setText(String.format(getResources().getString(R.string.mop_pitch),((JNIHandler.koffset>0)?"+":"")+Integer.toString(JNIHandler.koffset))); + + tempo.setText(String.format(getResources().getString(R.string.mop_tempo), JNIHandler.playbackPercentage, (int) (500000 / (double) JNIHandler.playbackTempo * 120 * (double) JNIHandler.playbackPercentage / 100 + 0.5))); + pitch.setText(String.format(getResources().getString(R.string.mop_pitch), ((JNIHandler.keyOffset > 0) ? "+" : "") + Integer.toString(JNIHandler.keyOffset))); voices.setText(String.format(getResources().getString(R.string.mop_voice), JNIHandler.voice, JNIHandler.maxvoice)); - speedUp.setOnClickListener(new OnClickListener(){ + speedUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - JNIHandler.controlTimidity(17,1); + JNIHandler.controlTimidity(17, 1); JNIHandler.waitUntilReady(); JNIHandler.tb++; } - + }); - slowDown.setOnClickListener(new OnClickListener(){ + slowDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - JNIHandler.controlTimidity(18,1); + JNIHandler.controlTimidity(18, 1); JNIHandler.waitUntilReady(); JNIHandler.tb--; } - + }); - keyUp.setOnClickListener(new OnClickListener(){ + keyUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - JNIHandler.controlTimidity(15,1); + JNIHandler.controlTimidity(15, 1); JNIHandler.waitUntilReady(); } - + }); - keyDown.setOnClickListener(new OnClickListener(){ + keyDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - JNIHandler.controlTimidity(16,-1); + JNIHandler.controlTimidity(16, -1); JNIHandler.waitUntilReady(); } - + }); - vplus.setOnClickListener(new OnClickListener(){ + vplus.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - JNIHandler.controlTimidity(19,5); + JNIHandler.controlTimidity(19, 5); JNIHandler.waitUntilReady(); } - + }); - vminus.setOnClickListener(new OnClickListener(){ + vminus.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - JNIHandler.controlTimidity(20,5); + JNIHandler.controlTimidity(20, 5); JNIHandler.waitUntilReady(); } - + }); - export.setOnClickListener(new OnClickListener(){ + export.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { mActivity.dynExport(true); } - + }); - saveCfg.setOnClickListener(new OnClickListener(){ + saveCfg.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { mActivity.saveCfg(); } - + }); - loadCfg.setOnClickListener(new OnClickListener(){ + loadCfg.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { mActivity.loadCfg(); } - + }); - savedefCfg.setOnClickListener(new OnClickListener(){ + savedefCfg.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - + String value1; String value2; - boolean alreadyExists = (new File(mActivity.currSongName+".def.tcf").exists()||new File(mActivity.currSongName+".def.tzf").exists()); - boolean aWrite=true; - String needRename1 = null; - String needRename2 = null; - String probablyTheRoot = ""; - String probablyTheDirectory = ""; - try{ - if(Globals.compressCfg) - new FileOutputStream(mActivity.currSongName+".def.tzf",true).close(); - else - new FileOutputStream(mActivity.currSongName+".def.tcf",true).close(); - }catch(FileNotFoundException e) - { - aWrite=false; - } catch (IOException e) - { + boolean alreadyExists = (new File(mActivity.currSongName + ".def.tcf").exists() || new File(mActivity.currSongName + ".def.tzf").exists()); + boolean aWrite = true; + String needRename1 = null; + String needRename2 = null; + String probablyTheRoot = ""; + String probablyTheDirectory = ""; + try { + if (SettingsStorage.compressCfg) + new FileOutputStream(mActivity.currSongName + ".def.tzf", true).close(); + else + new FileOutputStream(mActivity.currSongName + ".def.tcf", true).close(); + } catch (FileNotFoundException e) { + aWrite = false; + } catch (IOException e) { e.printStackTrace(); } - final boolean canWrite = aWrite; - if(!alreadyExists&&canWrite) - { - new File(mActivity.currSongName+".def.tcf").delete(); - new File(mActivity.currSongName+".def.tzf").delete(); - } - - if(canWrite&&new File(mActivity.currSongName).canWrite()) - { - value1=mActivity.currSongName+(Globals.compressCfg?".def.tzf":".def.tcf"); - value2=mActivity.currSongName+(Globals.compressCfg?".def.tcf":".def.tzf"); - }else if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null) - { - //TODO - // Write the file to getExternalFilesDir, then move it with the Uri - // We need to tell JNIHandler that movement is needed. - // This is pretty much done now? - String[] tmp = Globals.getDocFilePaths(getActivity(),mActivity.currSongName); - probablyTheDirectory = tmp[0]; - probablyTheRoot = tmp[1]; - if(probablyTheDirectory.length()>1) - { - needRename1 = (mActivity.currSongName).substring(mActivity.currSongName.indexOf(probablyTheRoot)+probablyTheRoot.length())+(Globals.compressCfg?".def.tzf":".def.tcf"); - needRename2 = (mActivity.currSongName).substring(mActivity.currSongName.indexOf(probablyTheRoot)+probablyTheRoot.length())+(Globals.compressCfg?".def.tcf":".def.tzf"); - value1 = probablyTheDirectory+mActivity.currSongName.substring(mActivity.currSongName.lastIndexOf('/'))+(Globals.compressCfg?".def.tzf":".def.tcf"); - value2 = probablyTheDirectory+mActivity.currSongName.substring(mActivity.currSongName.lastIndexOf('/'))+(Globals.compressCfg?".def.tcf":".def.tzf"); - }else{ - Toast.makeText(getActivity(), "Could not write config file. Did you give Timidity write access to the root of your external sd card?" , Toast.LENGTH_SHORT).show(); + final boolean canWrite = aWrite; + if (!alreadyExists && canWrite) { + new File(mActivity.currSongName + ".def.tcf").delete(); + new File(mActivity.currSongName + ".def.tzf").delete(); + } + + if (canWrite && new File(mActivity.currSongName).canWrite()) { + value1 = mActivity.currSongName + (SettingsStorage.compressCfg ? ".def.tzf" : ".def.tcf"); + value2 = mActivity.currSongName + (SettingsStorage.compressCfg ? ".def.tcf" : ".def.tzf"); + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && DocumentFileUtils.docFileDevice != null) { + // TODO + // Write the file to getExternalFilesDir, then move it with the Uri + // We need to tell JNIHandler that movement is needed. + // This is pretty much done now? + String[] tmp = DocumentFileUtils.getExternalFilePaths(getActivity(), mActivity.currSongName); + probablyTheDirectory = tmp[0]; + probablyTheRoot = tmp[1]; + if (probablyTheDirectory.length() > 1) { + needRename1 = (mActivity.currSongName).substring(mActivity.currSongName.indexOf(probablyTheRoot) + probablyTheRoot.length()) + (SettingsStorage.compressCfg ? ".def.tzf" : ".def.tcf"); + needRename2 = (mActivity.currSongName).substring(mActivity.currSongName.indexOf(probablyTheRoot) + probablyTheRoot.length()) + (SettingsStorage.compressCfg ? ".def.tcf" : ".def.tzf"); + value1 = probablyTheDirectory + mActivity.currSongName.substring(mActivity.currSongName.lastIndexOf('/')) + (SettingsStorage.compressCfg ? ".def.tzf" : ".def.tcf"); + value2 = probablyTheDirectory + mActivity.currSongName.substring(mActivity.currSongName.lastIndexOf('/')) + (SettingsStorage.compressCfg ? ".def.tcf" : ".def.tzf"); + } else { + Toast.makeText(getActivity(), "Could not write config file. Did you give Timidity write access to the root of your external sd card?", Toast.LENGTH_SHORT).show(); return; } - }else{ - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - Toast.makeText(getActivity(), "Could not write config file. Did you give Timidity write access to the root of your external sd card?" , Toast.LENGTH_SHORT).show(); - }else{ - Toast.makeText(getActivity(), "Could not write config file. Permission denied." , Toast.LENGTH_SHORT).show(); - } - return; - } - final String finalval1 = value1; - final String finalval2 = value2; - final String needToRename1 = needRename1; - final String needToRename2 = needRename2; - final String probRoot = probablyTheRoot; - if(alreadyExists) - { + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + Toast.makeText(getActivity(), "Could not write config file. Did you give Timidity write access to the root of your external sd card?", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(getActivity(), "Could not write config file. Permission denied.", Toast.LENGTH_SHORT).show(); + } + return; + } + final String finalval1 = value1; + final String finalval2 = value2; + final String needToRename1 = needRename1; + final String needToRename2 = needRename2; + final String probRoot = probablyTheRoot; + if (alreadyExists) { AlertDialog dialog = new AlertDialog.Builder(mActivity).create(); - dialog.setTitle("Warning"); - dialog.setMessage("Overwrite default config file?"); - dialog.setCancelable(false); - dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - if(!canWrite&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - if(needToRename1!=null) - { - Globals.tryToDeleteFile(getActivity(), probRoot+needToRename1); - Globals.tryToDeleteFile(getActivity(), finalval1); - Globals.tryToDeleteFile(getActivity(), probRoot+needToRename2); - Globals.tryToDeleteFile(getActivity(), finalval2); - }else{ - Globals.tryToDeleteFile(getActivity(), finalval1); - Globals.tryToDeleteFile(getActivity(), finalval2); - } - }else{ - new File(mActivity.currSongName+".def.tcf").delete(); - new File(mActivity.currSongName+".def.tzf").delete(); - } - mActivity.setLocalFinished(false); - mActivity.saveCfgPart2(finalval1, needToRename1); - deldefCfg.setEnabled(true); - /*Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 16); - new_intent.putExtra(getResources().getString(R.string.msrv_outfile), mActivity.currSongName+".def.tcf"); - getActivity().sendBroadcast(new_intent); - deldefCfg.setEnabled(true);*/ - } - }); - dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - - - } - }); - dialog.show(); - - }else{ - /*Intent new_intent = new Intent(); - new_intent.setAction(getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 16); - new_intent.putExtra(getResources().getString(R.string.msrv_outfile), mActivity.currSongName+".def.tcf"); - getActivity().sendBroadcast(new_intent); - deldefCfg.setEnabled(true);*/ + dialog.setTitle("Warning"); + dialog.setMessage("Overwrite default config file?"); + dialog.setCancelable(false); + dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (needToRename1 != null) { + DocumentFileUtils.tryToDeleteFile(getActivity(), probRoot + needToRename1); + DocumentFileUtils.tryToDeleteFile(getActivity(), finalval1); + DocumentFileUtils.tryToDeleteFile(getActivity(), probRoot + needToRename2); + DocumentFileUtils.tryToDeleteFile(getActivity(), finalval2); + } else { + DocumentFileUtils.tryToDeleteFile(getActivity(), finalval1); + DocumentFileUtils.tryToDeleteFile(getActivity(), finalval2); + } + } else { + new File(mActivity.currSongName + ".def.tcf").delete(); + new File(mActivity.currSongName + ".def.tzf").delete(); + } + mActivity.setLocalFinished(false); + mActivity.saveCfgPart2(finalval1, needToRename1); + deldefCfg.setEnabled(true); + } + }); + dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + + } + }); + dialog.show(); + + } else { mActivity.setLocalFinished(false); mActivity.saveCfgPart2(finalval1, needToRename1); deldefCfg.setEnabled(true); } } - - + }); - - deldefCfg.setOnClickListener(new OnClickListener(){ + + deldefCfg.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { - - if(new File( mActivity.currSongName+".def.tcf").exists() || new File(mActivity.currSongName+".def.tzf").exists()) - { - boolean aWrite=true; - try{ - if(Globals.compressCfg) - new FileOutputStream(mActivity.currSongName+".def.tzf",true).close(); - else - new FileOutputStream(mActivity.currSongName+".def.tcf",true).close(); - }catch(FileNotFoundException e) - { - aWrite=false; - } catch (IOException e) - { + + if (new File(mActivity.currSongName + ".def.tcf").exists() || new File(mActivity.currSongName + ".def.tzf").exists()) { + boolean aWrite = true; + try { + if (SettingsStorage.compressCfg) + new FileOutputStream(mActivity.currSongName + ".def.tzf", true).close(); + else + new FileOutputStream(mActivity.currSongName + ".def.tcf", true).close(); + } catch (FileNotFoundException e) { + aWrite = false; + } catch (IOException e) { e.printStackTrace(); } - final boolean canWrite = aWrite; + final boolean canWrite = aWrite; AlertDialog dialog = new AlertDialog.Builder(mActivity).create(); - dialog.setTitle("Warning"); - dialog.setMessage("Really delete default config file?"); - dialog.setCancelable(false); - dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - - if(!canWrite&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - Globals.tryToDeleteFile(getActivity(), mActivity.currSongName+".def.tzf"); - Globals.tryToDeleteFile(getActivity(), mActivity.currSongName+".def.tcf"); - }else{ - new File(mActivity.currSongName+".def.tcf").delete(); - new File(mActivity.currSongName+".def.tzf").delete(); - } - deldefCfg.setEnabled(false); - } - }); - dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - - - } - }); - dialog.show(); - + dialog.setTitle("Warning"); + dialog.setMessage("Really delete default config file?"); + dialog.setCancelable(false); + dialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + + if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + DocumentFileUtils.tryToDeleteFile(getActivity(), mActivity.currSongName + ".def.tzf"); + DocumentFileUtils.tryToDeleteFile(getActivity(), mActivity.currSongName + ".def.tcf"); + } else { + new File(mActivity.currSongName + ".def.tcf").delete(); + new File(mActivity.currSongName + ".def.tzf").delete(); + } + deldefCfg.setEnabled(false); + } + }); + dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + + } + }); + dialog.show(); + } } - + }); - + final Spinner x = (Spinner) v.findViewById(R.id.resampSpinner); List arrayAdapter = new ArrayList(); - for(String yyy : Globals.sampls) + for (String yyy : Globals.sampls) arrayAdapter.add(yyy); - ArrayAdapter dataAdapter = new ArrayAdapter(getActivity(), - android.R.layout.simple_spinner_item, arrayAdapter); + ArrayAdapter dataAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item, arrayAdapter); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); x.setAdapter(dataAdapter); - firstSelection=true; - x.setOnItemSelectedListener(new OnItemSelectedListener(){ + firstSelection = true; + x.setOnItemSelectedListener(new OnItemSelectedListener() { @Override - public void onItemSelected(AdapterView arg0, View arg1, - int pos, long id) { - if(firstSelection) - firstSelection=false; - else{ - JNIHandler.setResampleTimidity(JNIHandler.currsamp=pos); - JNIHandler.seekTo(JNIHandler.currTime); + public void onItemSelected(AdapterView arg0, View arg1, int pos, long id) { + if (firstSelection) + firstSelection = false; + else { + JNIHandler.setResampleTimidity(JNIHandler.currsamp = pos); + JNIHandler.seekTo(JNIHandler.currTime); } } @Override public void onNothingSelected(AdapterView arg0) { - + } - + }); x.setSelection(JNIHandler.currsamp); if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) - v.setBackgroundColor(Globals.theme==1?Color.WHITE:Color.BLACK); - + v.setBackgroundColor(SettingsStorage.theme == 1 ? Color.WHITE : Color.BLACK); + b.setView(v); - b.setPositiveButton("OK", new DialogInterface.OnClickListener() - { + b.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - + } }); b.setTitle(getActivity().getResources().getString(R.string.mop)); - ddd=b.create(); + ddd = b.create(); ddd.show(); - + } - public void setArt() - { - if(fragMode==0&&artsy!=null&&getActivity()!=null) - { + + public void setArt() { + if (fragMode == 0 && artsy != null && getActivity() != null) { artsy.setArt(Globals.currArt, getActivity()); } } diff --git a/src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java b/src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java index 0f25d22..9b94bf9 100755 --- a/src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/PlaylistFragment.java @@ -26,8 +26,11 @@ import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog; import com.xperia64.timidityae.gui.dialogs.FileBrowserDialog.FileBrowserDialogListener; +import com.xperia64.timidityae.util.DocumentFileUtils; import com.xperia64.timidityae.util.FileComparator; import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.CommandStrings; +import com.xperia64.timidityae.util.SettingsStorage; import com.xperia64.timidityae.R; import com.xperia64.timidityae.TimidityActivity; @@ -49,11 +52,10 @@ //import android.widget.TextView; import android.widget.Toast; - public class PlaylistFragment extends ListFragment implements FileBrowserDialogListener { - + String playlistDir; - boolean gotPlaylists=false; + boolean gotPlaylists = false; ActionPlaylistBackListener mCallback; ArrayList path; ArrayList fname; @@ -61,410 +63,383 @@ public class PlaylistFragment extends ListFragment implements FileBrowserDialogL ArrayList vola; public String plistName; String tmpName; - int loki=-1; + int loki = -1; public int highlightMe = -1; - public boolean mode=false; + public boolean mode = false; boolean dontReloadPlist = false; - public interface ActionPlaylistBackListener{ + + public interface ActionPlaylistBackListener { public void needPlaylistBackCallback(boolean yes, boolean current); } + public static PlaylistFragment create(String fold) { Bundle args = new Bundle(); - args.putString(Globals.currPlistDirectory, fold); + args.putString(CommandStrings.currPlistDirectory, fold); PlaylistFragment fragment = new PlaylistFragment(); fragment.setArguments(args); return fragment; - } + } + @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if(getArguments()!=null) - playlistDir = getArguments().getString(Globals.currPlistDirectory); - if(playlistDir==null) - playlistDir="/"; + super.onCreate(savedInstanceState); + if (getArguments() != null) + playlistDir = getArguments().getString(CommandStrings.currPlistDirectory); + if (playlistDir == null) + playlistDir = File.separator; // TODO this should not be root. } + @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) - { - View v = inflater.inflate(R.layout.list, container, false); - return v; - } + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.list, container, false); + return v; + } + @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - if(!gotPlaylists) - { - gotPlaylists=true; + if (!gotPlaylists) { + gotPlaylists = true; getPlaylists(null); } getListView().setOnItemLongClickListener(new OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView arg0, View arg1, - final int pos, long id) { - if(!mode) - { - AlertDialog.Builder builderSingle = new AlertDialog.Builder( - getActivity()); - builderSingle.setIcon(R.drawable.ic_launcher); - builderSingle.setTitle(getActivity().getResources().getString((pos==0)?R.string.plist_save2:R.string.plist_mod)); - builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - - } - }); - if(pos!=0) - { - builderSingle.setNeutralButton(getResources().getString(R.string.plist_del), new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - AlertDialog.Builder builderDouble = new AlertDialog.Builder( - getActivity()).setIcon(R.drawable.ic_launcher).setTitle(String.format(getActivity().getResources().getString(R.string.plist_del2), fname.get(pos))); - builderDouble.setPositiveButton(android.R.string.yes,new DialogInterface.OnClickListener() { - + @Override + public boolean onItemLongClick(AdapterView arg0, View arg1, final int pos, long id) { + if (!mode) { + AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity()); + builderSingle.setIcon(R.drawable.ic_launcher); + builderSingle.setTitle(getActivity().getResources().getString((pos == 0) ? R.string.plist_save2 : R.string.plist_mod)); + builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + + } + }); + if (pos != 0) { + builderSingle.setNeutralButton(getResources().getString(R.string.plist_del), new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { - File f = new File(path.get(pos)); - if(f.exists()) - { - String[] x = null; - try{ - new FileOutputStream(path.get(pos),true).close(); - }catch(FileNotFoundException e) - { - x=Globals.getDocFilePaths(getActivity(), f.getAbsolutePath()); - } catch (IOException e) - { - e.printStackTrace(); + AlertDialog.Builder builderDouble = new AlertDialog.Builder(getActivity()).setIcon(R.drawable.ic_launcher).setTitle(String.format(getActivity().getResources().getString(R.string.plist_del2), fname.get(pos))); + builderDouble.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + File f = new File(path.get(pos)); + if (f.exists()) { + String[] x = null; + try { + new FileOutputStream(path.get(pos), true).close(); + } catch (FileNotFoundException e) { + x = DocumentFileUtils.getExternalFilePaths(getActivity(), f.getAbsolutePath()); + } catch (IOException e) { + e.printStackTrace(); + } + + if (x != null) { + DocumentFileUtils.tryToDeleteFile(getActivity(), path.get(pos)); + } else { + f.delete(); + } + } + getPlaylists(null); + dialog.dismiss(); } - - if(x!=null) - { - Globals.tryToDeleteFile(getActivity(), path.get(pos)); - }else{ - f.delete(); - } - } - getPlaylists(null); - dialog.dismiss(); - } - }); - builderDouble.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}); - builderDouble.show(); - } - }); - builderSingle.setPositiveButton(getResources().getString(R.string.plist_ren), new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); - - alert.setTitle(String.format(getResources().getString(R.string.plist_ren2), fname.get(pos))); - - final EditText input = new EditText(getActivity()); - alert.setView(input); - - alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - File f = new File(path.get(pos)); - File f2 = new File(path.get(pos).substring(0,path.get(pos).lastIndexOf('/')+1)+value+".tpl"); - if(f.exists()) - { - if(f2.exists()) - { - Toast.makeText(getActivity(), getResources().getString(R.string.plist_ex), Toast.LENGTH_SHORT).show(); - }else{ - String[] x = null; - try{ - new FileOutputStream(f.getAbsolutePath(),true).close(); - }catch(FileNotFoundException e) - { - x=Globals.getDocFilePaths(getActivity(), f.getAbsolutePath()); - } catch (IOException e) - { - e.printStackTrace(); - } - - if(x!=null) - { - Globals.renameDocumentFile(getActivity(), f.getAbsolutePath(), f2.getAbsolutePath().substring(f2.getAbsolutePath().indexOf(x[1])+x[1].length())); - }else{ - f.renameTo(f2); - } - - - } - }else - Toast.makeText(getActivity(), getResources().getString(R.string.plist_pnf), Toast.LENGTH_SHORT).show(); - getPlaylists(null); - dialog.dismiss(); - } - + }); + builderDouble.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + builderDouble.show(); + } }); + builderSingle.setPositiveButton(getResources().getString(R.string.plist_ren), new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); + + alert.setTitle(String.format(getResources().getString(R.string.plist_ren2), fname.get(pos))); + + final EditText input = new EditText(getActivity()); + alert.setView(input); + + alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + String value = input.getText().toString(); + File f = new File(path.get(pos)); + File f2 = new File(path.get(pos).substring(0, path.get(pos).lastIndexOf(File.separator) + 1) + value + ".tpl"); + if (f.exists()) { + if (f2.exists()) { + Toast.makeText(getActivity(), getResources().getString(R.string.plist_ex), Toast.LENGTH_SHORT).show(); + } else { + String[] x = null; + try { + new FileOutputStream(f.getAbsolutePath(), true).close(); + } catch (FileNotFoundException e) { + x = DocumentFileUtils.getExternalFilePaths(getActivity(), f.getAbsolutePath()); + } catch (IOException e) { + e.printStackTrace(); + } + + if (x != null) { + DocumentFileUtils.renameDocumentFile(getActivity(), f.getAbsolutePath(), f2.getAbsolutePath().substring(f2.getAbsolutePath().indexOf(x[1]) + x[1].length())); + } else { + f.renameTo(f2); + } - alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - dialog.dismiss(); - } + } + } else + Toast.makeText(getActivity(), getResources().getString(R.string.plist_pnf), Toast.LENGTH_SHORT).show(); + getPlaylists(null); + dialog.dismiss(); + } + + }); + + alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + dialog.dismiss(); + } + }); + + alert.show(); + } }); + } else { + + final EditText input2 = new EditText(getActivity()); + builderSingle.setView(input2); + builderSingle.setPositiveButton(getResources().getString(R.string.plist_save), new DialogInterface.OnClickListener() { - alert.show(); + @Override + public void onClick(DialogInterface dialog, int which) { + if (input2.getText() != null) { + if (!TextUtils.isEmpty(input2.getText().toString())) { + tmpName = playlistDir + File.separator + input2.getText().toString() + ".tpl"; + vola = currPlist; + write(); + } + } + } + }); } - }); - }else{ - - final EditText input2 = new EditText(getActivity()); - builderSingle.setView(input2); - builderSingle.setPositiveButton(getResources().getString(R.string.plist_save), new DialogInterface.OnClickListener() { - + builderSingle.show(); + return true; + } else if (!plistName.equals("CURRENT")) { + AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity()); + + builderSingle.setIcon(R.drawable.ic_launcher); + builderSingle.setTitle(getResources().getString(R.string.plist_modit)); + final ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity(), android.R.layout.select_dialog_item); + arrayAdapter.add(getResources().getString(R.string.plist_ds)); + arrayAdapter.add(getResources().getString(R.string.plist_addcsh)); + arrayAdapter.add(getResources().getString(R.string.plist_addsh)); + arrayAdapter.add(getResources().getString(R.string.plist_addfh)); + arrayAdapter.add(getResources().getString(R.string.plist_addfth)); + builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + + builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { - if(input2.getText()!=null) - { - if(!TextUtils.isEmpty(input2.getText().toString())) - { - tmpName=playlistDir+"/"+input2.getText().toString()+".tpl"; - vola=currPlist; + vola = parsePlist(tmpName = plistName); + loki = pos; + switch (which) { + case 0: + setItem(null, -1); + write(); + break; + case 1: + if (((TimidityActivity) getActivity()).currSongName != null) { + setItem(((TimidityActivity) getActivity()).currSongName, 0); write(); } + break; + case 2: + new FileBrowserDialog().create(0, (SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles), PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, SettingsStorage.homeFolder, getActivity().getResources().getString(R.string.fb_add)); + break; + case 3: + new FileBrowserDialog().create(1, null, PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, SettingsStorage.homeFolder, getActivity().getResources().getString(R.string.fb_add)); + break; + case 4: + new FileBrowserDialog().create(2, null, PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, SettingsStorage.homeFolder, getActivity().getResources().getString(R.string.fb_add)); + break; } } - } - ); - } - builderSingle.show(); - return true; - }else if(!plistName.equals("CURRENT")){ - AlertDialog.Builder builderSingle = new AlertDialog.Builder( - getActivity()); - - builderSingle.setIcon(R.drawable.ic_launcher); - builderSingle.setTitle(getResources().getString(R.string.plist_modit)); - final ArrayAdapter arrayAdapter = new ArrayAdapter( - getActivity(), - android.R.layout.select_dialog_item); - arrayAdapter.add(getResources().getString(R.string.plist_ds)); - arrayAdapter.add(getResources().getString(R.string.plist_addcsh)); - arrayAdapter.add(getResources().getString(R.string.plist_addsh)); - arrayAdapter.add(getResources().getString(R.string.plist_addfh)); - arrayAdapter.add(getResources().getString(R.string.plist_addfth)); - builderSingle.setNegativeButton(android.R.string.cancel, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - - builderSingle.setAdapter(arrayAdapter, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - vola=parsePlist(tmpName=plistName); - loki=pos; - switch(which) - { - case 0: - setItem(null, -1); - write(); - break; - case 1: - if(((TimidityActivity)getActivity()).currSongName!=null) - { - setItem(((TimidityActivity)getActivity()).currSongName, 0); - write(); - } - break; - case 2: - new FileBrowserDialog().create( 0, (Globals.showVideos?Globals.musicVideoFiles:Globals.musicFiles), PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, Globals.defaultFolder, getActivity().getResources().getString(R.string.fb_add)); - break; - case 3: - new FileBrowserDialog().create( 1, null, PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, Globals.defaultFolder, getActivity().getResources().getString(R.string.fb_add)); - break; - case 4: - new FileBrowserDialog().create( 2, null, PlaylistFragment.this,getActivity(), getActivity().getLayoutInflater(), false, Globals.defaultFolder, getActivity().getResources().getString(R.string.fb_add)); - break; - } - } - }); - builderSingle.show(); - return true; - } + }); + builderSingle.show(); + return true; + } return true; - } - }); + } + }); } + @Override - public void onAttach(Context activity) - { + public void onAttach(Context activity) { super.onAttach(activity); try { - mCallback = (ActionPlaylistBackListener) activity; - } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() - + " must implement ActionPlaylistBackListener"); - } - if(Globals.shouldRestore&&(Globals.plist==null||Globals.plist.size()==0)) - { - Intent new_intent = new Intent(); - new_intent.setAction(getActivity().getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(getActivity().getResources().getString(R.string.msrv_cmd), 12); - getActivity().sendBroadcast(new_intent); - } + mCallback = (ActionPlaylistBackListener) activity; + } catch (ClassCastException e) { + throw new ClassCastException(activity.toString() + " must implement ActionPlaylistBackListener"); + } + if (Globals.shouldRestore && (Globals.plist == null || Globals.plist.size() == 0)) { + Intent new_intent = new Intent(); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_get_plist); + getActivity().sendBroadcast(new_intent); + } } - public void getPlaylists(final String which) - { - if(which==null) // Root playlist dir. + + public void getPlaylists(final String which) { + if (which == null) // Root playlist dir. { - mode=false; + mode = false; mCallback.needPlaylistBackCallback(false, false); fname = new ArrayList(); - path = new ArrayList(); + path = new ArrayList(); File f = new File(playlistDir); - fname.add("[ "+getResources().getString(R.string.plist_curr)+" ]"); + fname.add("[ " + getResources().getString(R.string.plist_curr) + " ]"); path.add("CURRENT"); - if(f.exists()) - { - File[] files = f.listFiles(); - if (files!=null&&files.length>0){ - if(files != null) - { - Arrays.sort(files, new FileComparator()); - } - mCallback.needPlaylistBackCallback(false, false); - for(int i=0; i < files.length; i++) + if (f.exists()) { + File[] files = f.listFiles(); + if (files != null && files.length > 0) { + if (files != null) { + Arrays.sort(files, new FileComparator()); + } + mCallback.needPlaylistBackCallback(false, false); + for (int i = 0; i < files.length; i++) - { + { - if (files[i].isFile()){ - int dotPosition = files[i].getName().lastIndexOf('.'); - String extension=""; - if (dotPosition != -1) { - extension = (files[i].getName().substring(dotPosition)).toLowerCase(Locale.US); - if(extension!=null){ - if(Globals.playlistFiles.contains("*"+extension+"*")){ - fname.add(files[i].getName().substring(0,files[i].getName().lastIndexOf('.'))); + if (files[i].isFile()) { + int dotPosition = files[i].getName().lastIndexOf('.'); + String extension = ""; + if (dotPosition != -1) { + extension = (files[i].getName().substring(dotPosition)).toLowerCase(Locale.US); + if (extension != null) { + if (Globals.playlistFiles.contains("*" + extension + "*")) { + fname.add(files[i].getName().substring(0, files[i].getName().lastIndexOf('.'))); path.add(files[i].getAbsolutePath()); } } + } } } } } - } - }else{ // An actual playlist + } else { // An actual playlist mCallback.needPlaylistBackCallback(true, which.equals("CURRENT")); - mode=true; + mode = true; path = new ArrayList(); fname = new ArrayList(); - if(which.equals("CURRENT")) // current playlist + if (which.equals("CURRENT")) // current playlist { - if(currPlist!=null) - { - if(currPlist.size()>0) - { + if (currPlist != null) { + if (currPlist.size() > 0) { dontReloadPlist = true; - for(String xx:currPlist) - { + for (String xx : currPlist) { path.add(xx); - fname.add(xx.substring(xx.lastIndexOf('/')+1, xx.length())); + fname.add(xx.substring(xx.lastIndexOf('/') + 1, xx.length())); } } } - }else{ // Another playlist + } else { // Another playlist dontReloadPlist = false; - vola = path=parsePlist(which); - for(String name : path) - { - fname.add(name.substring(name.lastIndexOf('/')+1)); + vola = path = parsePlist(which); + for (String name : path) { + fname.add(name.substring(name.lastIndexOf('/') + 1)); } } } - ArrayAdapter fileList; - if(which!=null&&which.equals("CURRENT")) - { - fileList = new ArrayAdapter(getActivity(),R.layout.row,fname){ - - /* @Override - public View getView(int position, View convertView, ViewGroup parent) - { - final View renderer = super.getView(position, convertView, parent); - if(Globals.defaultListColor==-1) - { - Globals.defaultListColor = Globals.getBackgroundColor(((TextView)renderer)); - } - if (position == highlightMe) - { - //TODO Choose a nicer color in settings? - renderer.setBackgroundColor(0xFF00CC00); - }else{ - renderer.setBackgroundColor(Globals.defaultListColor); - } - //renderer.postInvalidate(); - return renderer; - }*/ + ArrayAdapter fileList; + if (which != null && which.equals("CURRENT")) { + fileList = new ArrayAdapter(getActivity(), R.layout.row, fname) { + + // @formatter:off + /*@Override + public View getView(int position, View convertView, ViewGroup parent) { + final View renderer = super.getView(position, convertView, parent); + if (Globals.defaultListColor == -1) { + Globals.defaultListColor = Globals.getBackgroundColor(((TextView) renderer)); + } + if (position == highlightMe) { + // TODO Choose a nicer color in settings? + renderer.setBackgroundColor(0xFF00CC00); + } else { + renderer.setBackgroundColor(Globals.defaultListColor); + } + renderer.postInvalidate(); + return renderer; + }*/ + // @formatter:on + }; - }else{ - fileList = new ArrayAdapter(getActivity(),R.layout.row,fname); + } else { + fileList = new ArrayAdapter(getActivity(), R.layout.row, fname); } - - - - //fileList.notifyDataSetChanged(); - //getListView().setFastScrollEnabled(true); - //getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); - /* if(which!=null&&which.equals("CURRENT")&&highlightMe!=-1) - { - System.out.println("Selected: "+highlightMe); - fileList.setSelector(R.color.listSelection); - getListView().setItemChecked(highlightMe, true); - }*/ - setListAdapter(fileList); + + // @formatter:off + // fileList.notifyDataSetChanged(); + // getListView().setFastScrollEnabled(true); + // getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); + /* + if(which!=null&&which.equals("CURRENT")&&highlightMe!=-1) { + System.out.println("Selected: "+highlightMe); + fileList.setSelector(R.color.listSelection); + getListView().setItemChecked(highlightMe, true); + } + */ + // @formatter:on + setListAdapter(fileList); } - public ArrayList parsePlist(String path) - { - ArrayList plist = new ArrayList(); - try{ - FileInputStream fstream = new FileInputStream(path); - DataInputStream in = new DataInputStream(fstream); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - String strLine; - - while ((strLine = br.readLine()) != null) { - if(!TextUtils.isEmpty(strLine)) - plist.add(strLine); - - } - in.close(); - }catch (Exception e){//Catch exception if any - System.err.println("Error: " + e.getMessage()); - } + + public ArrayList parsePlist(String path) { + ArrayList plist = new ArrayList(); + try { + FileInputStream fstream = new FileInputStream(path); + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String strLine; + + while ((strLine = br.readLine()) != null) { + if (!TextUtils.isEmpty(strLine)) + plist.add(strLine); + + } + in.close(); + } catch (Exception e) {// Catch exception if any + System.err.println("Error: " + e.getMessage()); + } return plist; } + @Override public void onListItemClick(ListView l, View v, int position, long id) { - if(mode) - { - ((TimidityActivity)getActivity()).selectedSong(path, position, true, true, dontReloadPlist); - }else{ - getPlaylists(plistName=path.get(position)); + if (mode) { + ((TimidityActivity) getActivity()).selectedSong(path, position, true, true, dontReloadPlist); + } else { + getPlaylists(plistName = path.get(position)); } } + @Override public void setItem(String path, int type) { - - switch(type) - { + + switch (type) { case -1: vola.remove(loki); break; @@ -473,262 +448,235 @@ public void setItem(String path, int type) { break; case 1: File f = new File(path); - - if(f.exists()&&f.isDirectory()) - { + + if (f.exists() && f.isDirectory()) { File[] files = f.listFiles(); Arrays.sort(files, new FileComparator()); - for(File ff : files) - { - if(ff!=null) - { - if(ff.isFile()) - { - int dotPosition = ff.getName().lastIndexOf('.'); - String extension=""; - if (dotPosition != -1) - { - extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US); - if(extension!=null) - { - if((Globals.showVideos?Globals.musicVideoFiles:Globals.musicFiles).contains("*"+extension+"*")) - { - vola.add(loki++, ff.getAbsolutePath()); - } - } + for (File ff : files) { + if (ff != null) { + if (ff.isFile()) { + int dotPosition = ff.getName().lastIndexOf('.'); + String extension = ""; + if (dotPosition != -1) { + extension = (ff.getName().substring(dotPosition)).toLowerCase(Locale.US); + if (extension != null) { + if ((SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + vola.add(loki++, ff.getAbsolutePath()); + } } } } } + } } break; case 2: - ArrayList fff = walk(new File(path)); - for(File foo : fff) - { - if(foo!=null) - { - if(foo.isFile()) - { + ArrayList fff = recurseFolder(new File(path)); + for (File foo : fff) { + if (foo != null) { + if (foo.isFile()) { int dotPosition = foo.getName().lastIndexOf('.'); - String extension=""; + String extension = ""; if (dotPosition != -1) { extension = (foo.getName().substring(dotPosition)).toLowerCase(Locale.US); - if(extension!=null){ - if((Globals.showVideos?Globals.musicVideoFiles:Globals.musicFiles).contains("*"+extension+"*")) - { - vola.add(loki++, foo.getAbsolutePath()); - } - } + if (extension != null) { + if ((SettingsStorage.showVideos ? Globals.musicVideoFiles : Globals.musicFiles).contains("*" + extension + "*")) { + vola.add(loki++, foo.getAbsolutePath()); } + } + } } } } break; } - + } - public void add() - { - if(mode) - { - vola=parsePlist(tmpName=plistName); - AlertDialog.Builder builderSingle = new AlertDialog.Builder( - getActivity()); - loki=vola.size(); - - builderSingle.setIcon(R.drawable.ic_launcher); - builderSingle.setTitle(getResources().getString(R.string.plist_addto)); - final ArrayAdapter arrayAdapter = new ArrayAdapter( - getActivity(), - android.R.layout.select_dialog_item); - arrayAdapter.add(getResources().getString(R.string.plist_addcs)); - arrayAdapter.add(getResources().getString(R.string.plist_adds)); - arrayAdapter.add(getResources().getString(R.string.plist_addf)); - arrayAdapter.add(getResources().getString(R.string.plist_addft)); - builderSingle.setNegativeButton(android.R.string.cancel, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - - builderSingle.setAdapter(arrayAdapter, - new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface dialog, int which) { - vola=parsePlist(plistName); - switch(which) - { - case 0: - setItem(((TimidityActivity)getActivity()).currSongName, 0); - write(); - break; - case 1: - new FileBrowserDialog().create( 0, (((Globals.showVideos)?Globals.musicVideoFiles:Globals.musicFiles)), PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, Globals.defaultFolder, getActivity().getResources().getString(R.string.fb_add)); - break; - case 2: - new FileBrowserDialog().create( 1, null, PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, Globals.defaultFolder, getActivity().getResources().getString(R.string.fb_add)); - break; - case 3: - new FileBrowserDialog().create( 2, null, PlaylistFragment.this,getActivity(), getActivity().getLayoutInflater(), false, Globals.defaultFolder, getActivity().getResources().getString(R.string.fb_add)); - break; - } - } - }); - builderSingle.show(); - }else{ + + public void add() { + if (mode) { + vola = parsePlist(tmpName = plistName); + AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity()); + loki = vola.size(); + + builderSingle.setIcon(R.drawable.ic_launcher); + builderSingle.setTitle(getResources().getString(R.string.plist_addto)); + final ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity(), android.R.layout.select_dialog_item); + arrayAdapter.add(getResources().getString(R.string.plist_addcs)); + arrayAdapter.add(getResources().getString(R.string.plist_adds)); + arrayAdapter.add(getResources().getString(R.string.plist_addf)); + arrayAdapter.add(getResources().getString(R.string.plist_addft)); + builderSingle.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + + builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + vola = parsePlist(plistName); + switch (which) { + case 0: + setItem(((TimidityActivity) getActivity()).currSongName, 0); + write(); + break; + case 1: + new FileBrowserDialog().create(0, (((SettingsStorage.showVideos) ? Globals.musicVideoFiles : Globals.musicFiles)), PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, SettingsStorage.homeFolder, getActivity().getResources().getString(R.string.fb_add)); + break; + case 2: + new FileBrowserDialog().create(1, null, PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, SettingsStorage.homeFolder, getActivity().getResources().getString(R.string.fb_add)); + break; + case 3: + new FileBrowserDialog().create(2, null, PlaylistFragment.this, getActivity(), getActivity().getLayoutInflater(), false, SettingsStorage.homeFolder, getActivity().getResources().getString(R.string.fb_add)); + break; + } + } + }); + builderSingle.show(); + } else { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(getResources().getString(R.string.plist_crea)); - + final EditText input = new EditText(getActivity()); alert.setView(input); alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { - + @Override public void onClick(DialogInterface dialog, int which) { - + } }); alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - File f = new File(playlistDir+value+".tpl"); - - if(!f.exists()) - { - String[] needLol = null; - try{ - new FileOutputStream(playlistDir+value+".tpl").close(); - }catch(FileNotFoundException e) - { - needLol=Globals.getDocFilePaths(getActivity(), playlistDir); - } catch (IOException e) - { - e.printStackTrace(); - } - if(needLol!=null) - { - Globals.tryToCreateFile(getActivity(), playlistDir+value+".tpl"); - }else{ - new File(playlistDir+value+".tpl").delete(); - try - { - f.createNewFile(); - } catch (IOException e) - { + public void onClick(DialogInterface dialog, int whichButton) { + String value = input.getText().toString(); + File f = new File(playlistDir + value + ".tpl"); + + if (!f.exists()) { + String[] needLol = null; + try { + new FileOutputStream(playlistDir + value + ".tpl").close(); + } catch (FileNotFoundException e) { + needLol = DocumentFileUtils.getExternalFilePaths(getActivity(), playlistDir); + } catch (IOException e) { e.printStackTrace(); } + if (needLol != null) { + DocumentFileUtils.tryToCreateFile(getActivity(), playlistDir + value + ".tpl", "timidityae/tpl"); + } else { + new File(playlistDir + value + ".tpl").delete(); + try { + f.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } } - } - - getPlaylists(null); - dialog.dismiss(); - } - + + getPlaylists(null); + dialog.dismiss(); + } + }); alert.show(); } } - public ArrayList walk( File fill ) { - - File[] files = fill.listFiles(); - Arrays.sort(files, new FileComparator()); - ArrayList filez = new ArrayList(); - for (File file : files) { - if (file.isDirectory()) { - filez.addAll(walk(file)); - } else { - filez.add(file); - } + + public ArrayList recurseFolder(File fill) { + + File[] files = fill.listFiles(); + Arrays.sort(files, new FileComparator()); + ArrayList filez = new ArrayList(); + for (File file : files) { + if (file.isDirectory()) { + filez.addAll(recurseFolder(file)); + } else { + filez.add(file); } - - return filez; - } - public void ignore() - { - vola = parsePlist(plistName); - loki=vola.size(); - } - public void write() - { - String[] needLol = null; - - try{ - new FileOutputStream(tmpName,true).close(); - }catch(FileNotFoundException e) - { - needLol=Globals.getDocFilePaths(getActivity(), tmpName); - } catch (IOException e) - { + } + + return filez; + } + + public void ignore() { + vola = parsePlist(plistName); + loki = vola.size(); + } + + public void write() { + String[] needLol = null; + + try { + new FileOutputStream(tmpName, true).close(); + } catch (FileNotFoundException e) { + needLol = DocumentFileUtils.getExternalFilePaths(getActivity(), tmpName); + } catch (IOException e) { e.printStackTrace(); - } + } - if(needLol!=null) - { - - FileWriter writer = null; - if(new File(tmpName).exists()) - Globals.tryToDeleteFile(getActivity(), tmpName); - - String probablyTheDirectory = needLol[0]; - String probablyTheRoot = needLol[1]; - String needRename = null; - String value = null; - if(probablyTheDirectory.length()>1) - { - needRename = tmpName.substring(tmpName.indexOf(probablyTheRoot)+probablyTheRoot.length()); - value = probablyTheDirectory+tmpName.substring(tmpName.lastIndexOf('/')); - }else{ - return; - } + if (needLol != null) { + + FileWriter writer = null; + if (new File(tmpName).exists()) + DocumentFileUtils.tryToDeleteFile(getActivity(), tmpName); + + String probablyTheDirectory = needLol[0]; + String probablyTheRoot = needLol[1]; + String needRename = null; + String value = null; + if (probablyTheDirectory.length() > 1) { + needRename = tmpName.substring(tmpName.indexOf(probablyTheRoot) + probablyTheRoot.length()); + value = probablyTheDirectory + tmpName.substring(tmpName.lastIndexOf('/')); + } else { + return; + } + try { + writer = new FileWriter(value); + } catch (IOException e1) { + e1.printStackTrace(); + } + for (String str : vola) { try { - writer = new FileWriter(value); - } catch (IOException e1) { - e1.printStackTrace(); - } - for(String str: vola) { - try { - writer.write(str+"\n"); - } catch (IOException e) { - e.printStackTrace(); - } - } - try { - writer.close(); + writer.write(str + "\n"); } catch (IOException e) { e.printStackTrace(); } - Globals.renameDocumentFile(getActivity(), value, needRename); - }else{ - FileWriter writer = null; - if(new File(tmpName).exists()) - Globals.tryToCreateFile(getActivity(), tmpName); + } + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + DocumentFileUtils.renameDocumentFile(getActivity(), value, needRename); + } else { + FileWriter writer = null; + if (new File(tmpName).exists()) + DocumentFileUtils.tryToCreateFile(getActivity(), tmpName, "timidityae/tpl"); + try { + writer = new FileWriter(tmpName); + } catch (IOException e1) { + e1.printStackTrace(); + } + for (String str : vola) { try { - writer = new FileWriter(tmpName); - } catch (IOException e1) { - e1.printStackTrace(); - } - for(String str: vola) { - try { - writer.write(str+"\n"); - } catch (IOException e) { - e.printStackTrace(); - } - } - try { - writer.close(); + writer.write(str + "\n"); } catch (IOException e) { e.printStackTrace(); } } - - getPlaylists(plistName); + try { + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + getPlaylists(plistName); } } diff --git a/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java b/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java index c1c4142..036c4f5 100755 --- a/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java +++ b/src/com/xperia64/timidityae/gui/fragments/TrackFragment.java @@ -39,24 +39,23 @@ import com.xperia64.timidityae.JNIHandler; import com.xperia64.timidityae.R; -import com.xperia64.timidityae.util.Globals; +import com.xperia64.timidityae.util.SettingsStorage; public class TrackFragment extends Fragment { - ArrayList localInst = new ArrayList(); - ArrayList localVol = new ArrayList(); + private ArrayList localInst = new ArrayList(); + private ArrayList localVol = new ArrayList(); - // ArrayList JNIHandler.drums = new ArrayList(); - ArrayAdapter fileList; - boolean fromUser; - ListView channelList; + private ArrayAdapter trackListAdapter; + private boolean fromUser; + private ListView trackList; // int bigCounter=6; - AlertDialog ddd; + private AlertDialog ddd; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.track_fragment, container, false); - channelList = (ListView) v.findViewById(R.id.trackList); + trackList = (ListView) v.findViewById(R.id.trackList); return v; } @@ -65,12 +64,12 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa public void onViewCreated(View view, Bundle savedInstanceState) { reset(); - fileList = new ArrayAdapter(getActivity(), R.layout.row); + trackListAdapter = new ArrayAdapter(getActivity(), R.layout.row); for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) { - fileList.add(String.format(getActivity().getResources().getString(R.string.trk_form), (getActivity().getResources().getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)), (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i))); + trackListAdapter.add(String.format(getActivity().getResources().getString(R.string.trk_form), (getActivity().getResources().getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)), (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i))); } - channelList.setAdapter(fileList); - channelList.setOnItemClickListener(new OnItemClickListener() { + trackList.setAdapter(trackListAdapter); + trackList.setOnItemClickListener(new OnItemClickListener() { @SuppressLint("InflateParams") @Override @@ -196,7 +195,7 @@ public void onCheckedChanged(CompoundButton arg0, boolean arg1) { }); if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) - v.setBackgroundColor(Globals.theme == 1 ? Color.WHITE : Color.BLACK); + v.setBackgroundColor(SettingsStorage.theme == 1 ? Color.WHITE : Color.BLACK); b.setView(v); b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @@ -207,7 +206,7 @@ public void onClick(DialogInterface dialog, int which) { JNIHandler.custVol.set(arg2, !vol.isChecked()); JNIHandler.setChannelVolumeTimidity(arg2 | (JNIHandler.custVol.get(arg2) ? 0x800 : 0x8000), volSeek.getProgress()); JNIHandler.setChannelTimidity(arg2 | (JNIHandler.custInst.get(arg2) ? 0x800 : 0x8000), instSpin.getSelectedItemPosition()); - if (!JNIHandler.paused && Globals.isPlaying == 0) + if (!JNIHandler.paused && JNIHandler.isPlaying) JNIHandler.seekTo(JNIHandler.currTime); // bigCounter=12; updateList(); @@ -245,7 +244,7 @@ public void reset() { } public void updateList() { - if (!JNIHandler.type) { + if (!JNIHandler.isMediaPlayerFormat) { // if(++bigCounter>4) // { // bigCounter=0; @@ -267,14 +266,16 @@ public void updateList() { } if (needUpdate) { // System.out.println("Need an update"); - fileList.setNotifyOnChange(false); // Prevents 'clear()' from - // clearing/resetting the - // listview - fileList.clear(); + // Prevents 'clear()' from clearing/resetting the listview + trackListAdapter.setNotifyOnChange(false); + trackListAdapter.clear(); for (int i = 0; i < JNIHandler.MAX_CHANNELS; i++) { - fileList.add(String.format(getActivity().getResources().getString(R.string.trk_form), (getActivity().getResources().getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)), (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, localVol.get(i))); + trackListAdapter.add(String.format(getActivity().getResources().getString(R.string.trk_form), + (getActivity().getResources().getString(JNIHandler.drums.get(i) ? R.string.trk_drum : R.string.trk_inst2)), + (i + 1), JNIHandler.drums.get(i) ? 0 : localInst.get(i) + 1, + localVol.get(i))); } - fileList.notifyDataSetChanged(); + trackListAdapter.notifyDataSetChanged(); } // } } diff --git a/src/com/xperia64/timidityae/util/CommandStrings.java b/src/com/xperia64/timidityae/util/CommandStrings.java new file mode 100755 index 0000000..491e984 --- /dev/null +++ b/src/com/xperia64/timidityae/util/CommandStrings.java @@ -0,0 +1,89 @@ +package com.xperia64.timidityae.util; + +public class CommandStrings { + // MusicService Broadcast Arguments + public static final String msrv_rec = "com.xperia64.timidityae.MusicService_RECEIVER"; + public static final String msrv_cmd = "com.xperia64.timidityae.MusicService_CMD"; + public static final String msrv_songnum = "com.xperia64.timidityae.MusicService_SONGNUM"; + public static final String msrv_currfold = "com.xperia64.timidityae.MusicService_CURRFOLD"; + public static final String msrv_begin = "com.xperia64.timidityae.MusicService_Begin"; + public static final String msrv_loopmode = "com.xperia64.timidityae.MusicService_LoopMode"; + public static final String msrv_shufmode = "com.xperia64.timidityae.MusicService_ShuffleMode"; + public static final String msrv_seektime = "com.xperia64.timidityae.MusicService_SeekTime"; + public static final String msrv_infile = "com.xperia64.timidityae.MusicService_InputFile"; + public static final String msrv_outfile = "com.xperia64.timidityae.MusicService_OutputFile"; + public static final String msrv_reset = "com.xperia64.timidityae.MusicService_Reset"; + public static final String msrv_dlplist = "com.xperia64.timidityae.MusicService_DontLoadPlist"; + + // MusicService Broadcast Commands + public static final int msrv_cmd_error = -5; + public static final int msrv_cmd_load_plist_play = 0; + public static final int msrv_cmd_play = 1; + public static final int msrv_cmd_pause = 2; + public static final int msrv_cmd_next = 3; + public static final int msrv_cmd_prev = 4; + public static final int msrv_cmd_stop = 5; + public static final int msrv_cmd_loop_mode = 6; + public static final int msrv_cmd_shuf_mode = 7; + // public static final int msrv_cmd_req_time = 8; // Unused + public static final int msrv_cmd_seek = 9; + public static final int msrv_cmd_get_fold = 10; + public static final int msrv_cmd_get_info = 11; + public static final int msrv_cmd_get_plist = 12; + public static final int msrv_cmd_play_or_pause = 13; // TODO: Used with the Widget + public static final int msrv_cmd_write_new = 14; + public static final int msrv_cmd_write_curr = 15; + public static final int msrv_cmd_save_cfg = 16; + public static final int msrv_cmd_load_cfg = 17; + public static final int msrv_cmd_reload_libs = 18; + + // TimidityActivity Broadcast Arguments + public static final String ta_rec = "com.xperia64.timidityae.TimidityActivity_RECEIVER"; + public static final String ta_cmd = "com.xperia64.timidityae.TimidityActivity_CMD"; + public static final String ta_filename = "com.xperia64.timidityae.TimidityActivity_FileName"; + public static final String ta_startt = "com.xperia64.timidityae.TimidityActivity_StartTime"; + public static final String ta_songttl = "com.xperia64.timidityae.TimidityActivity_SongTitle"; + public static final String ta_currpath = "com.xperia64.timidityae.TimidityActivity_CurrPath"; + public static final String ta_shufmode = "com.xperia64.timidityae.TimidityActivity_ShuffleMode"; + public static final String ta_loopmode = "com.xperia64.timidityae.TimidityActivity_LoopMode"; + public static final String ta_pause = "com.xperia64.timidityae.TimidityActivity_Pause"; + public static final String ta_pausea = "com.xperia64.timidityae.TimidityActivity_PauseArg"; + + // TimidityActivity Broadcast Commands + public static final int ta_cmd_error = -5; + public static final int ta_cmd_gui_play = 0; + public static final int ta_cmd_refresh_filebrowser = 1; + public static final int ta_cmd_load_filebrowser = 2; + public static final int ta_cmd_gui_play_full = 3; + public static final int ta_cmd_copy_plist = 4; + public static final int ta_cmd_pause_stop = 5; + public static final int ta_cmd_update_art = 6; + // public static final int ta_cmd_unused_7 = 7; + public static final int ta_cmd_special_notification_finished = 8; + + // Settings names + public static final String sett_first_run = "tplusFirstRun"; + public static final String sett_theme = "fbTheme"; + public static final String sett_show_hidden_files = "hiddenSwitch"; + public static final String sett_home_folder = "defaultPath"; + public static final String sett_data_folder = "dataDir"; + public static final String sett_man_config = "manualConfig"; + public static final String sett_default_resamp = "tplusResamp"; + public static final String sett_channel_mode = "sdlChanValue"; + public static final String sett_audio_rate = "tplusRate"; + public static final String sett_buffer_size = "tplusBuff"; + public static final String sett_show_videos = "videoSwitch"; + public static final String sett_should_ext_storage_nag = "shouldLolNag"; + public static final String sett_keep_partal_wave = "keepPartialWave"; + public static final String sett_default_back_btn = "useDefBack"; + public static final String sett_compress_midi_cfg = "compressCfg"; + public static final String sett_reshuffle_plist = "reShuffle"; + public static final String sett_free_insts = "tplusUnload"; + public static final String sett_preserve_silence = "tplusSilKey"; + public static final String sett_native_midi = "nativeMidiSwitch"; + + // Fragment Keys + public static final String currFoldKey = "CURRENT_FOLDER"; + public static final String currPlistDirectory = "CURRENT_PLIST_DIR"; + +} diff --git a/src/com/xperia64/timidityae/util/ConfigSaver.java b/src/com/xperia64/timidityae/util/ConfigSaver.java index 57bccd9..884c4c5 100755 --- a/src/com/xperia64/timidityae/util/ConfigSaver.java +++ b/src/com/xperia64/timidityae/util/ConfigSaver.java @@ -6,7 +6,7 @@ import java.io.IOException; import java.util.Locale; -import com.xperia64.timidityae.R; +import com.xperia64.timidityae.JNIHandler; import com.xperia64.timidityae.TimidityActivity; import android.app.Activity; @@ -17,7 +17,6 @@ import android.os.Build; import android.os.Environment; import android.text.InputFilter; -import android.text.Spanned; import android.widget.EditText; import android.widget.Toast; @@ -26,130 +25,127 @@ public class ConfigSaver implements TimidityActivity.SpecialAction { Activity context; String currSongName; AlertDialog alerty; + boolean localfinished; public ConfigSaver(Activity context, String currSongName) { this.context = context; this.currSongName = currSongName; } - boolean localfinished; - public void saveCfg() { localfinished = false; - if (Globals.isMidi(currSongName) && Globals.isPlaying == 0) { - AlertDialog.Builder alert = new AlertDialog.Builder(context); - - alert.setTitle("Save Cfg"); - alert.setMessage("Save a MIDI configuration file"); - InputFilter filter = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { - for (int i = start; i < end; i++) { - String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; - if (IC.contains("*" + source.charAt(i) + "*")) { - return ""; - } - } - return null; - } - }; + if (Globals.isMidi(currSongName) && JNIHandler.isPlaying) { + AlertDialog.Builder saveMidiConfigDialog = new AlertDialog.Builder(context); + + saveMidiConfigDialog.setTitle("Save Cfg"); + saveMidiConfigDialog.setMessage("Save a MIDI configuration file"); + // Set an EditText view to get user input final EditText input = new EditText(context); - input.setFilters(new InputFilter[] { filter }); - alert.setView(input); + input.setFilters(new InputFilter[] { Globals.fileNameInputFilter}); + saveMidiConfigDialog.setView(input); - alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { + saveMidiConfigDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - String value = input.getText().toString(); - if (!value.toLowerCase(Locale.US).endsWith(Globals.compressCfg ? ".tzf" : ".tcf")) { - value += (Globals.compressCfg ? ".tzf" : ".tcf"); - } - String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1); - boolean aWrite = true; - boolean alreadyExists = new File(parent + value).exists(); - String needRename = null; - String probablyTheRoot = ""; - String probablyTheDirectory = ""; - try { - new FileOutputStream(parent + value, true).close(); - } catch (FileNotFoundException e) { - aWrite = false; - } catch (IOException e) { - e.printStackTrace(); - } - if (!alreadyExists && aWrite) { - new File(parent + value).delete(); - } - if (aWrite && new File(parent).canWrite()) { - value = parent + value; - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) { - // TODO - // Write the file to getExternalFilesDir, then move it - // with the Uri - // We need to tell JNIHandler that movement is needed. - - String[] tmp = Globals.getDocFilePaths(context, parent); - probablyTheDirectory = tmp[0]; - probablyTheRoot = tmp[1]; - if (probablyTheDirectory.length() > 1) { - needRename = parent.substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value; - value = probablyTheDirectory + '/' + value; - } else { - value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; - return; - } - } else { - value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; - } - final String finalval = value; - final boolean canWrite = aWrite; - final String needToRename = needRename; - final String probRoot = probablyTheRoot; - if (new File(finalval).exists() || (new File(probRoot + needRename).exists() && needToRename != null)) { - AlertDialog dialog2 = new AlertDialog.Builder(context).create(); - dialog2.setTitle("Warning"); - dialog2.setMessage("Overwrite config file?"); - dialog2.setCancelable(false); - dialog2.setButton(DialogInterface.BUTTON_POSITIVE, context.getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - if (needToRename != null) { - Globals.tryToDeleteFile(context, probRoot + needToRename); - Globals.tryToDeleteFile(context, finalval); - } else { - Globals.tryToDeleteFile(context, finalval); - } - } else { - new File(finalval).delete(); - } - saveCfgPart2(finalval, needToRename); - } - }); - dialog2.setButton(DialogInterface.BUTTON_NEGATIVE, context.getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int buttonId) { - } - }); - dialog2.show(); - } else { - saveCfgPart2(finalval, needToRename); - } + beginConfigFileSave(input.getText().toString()); } }); - alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { + saveMidiConfigDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); - alerty = alert.show(); + alerty = saveMidiConfigDialog.show(); + } + } + + private void beginConfigFileSave(String configFileName) { + if (!configFileName.toLowerCase(Locale.US).endsWith(SettingsStorage.compressCfg ? ".tzf" : ".tcf")) { + configFileName += (SettingsStorage.compressCfg ? ".tzf" : ".tcf"); + } + String parent = currSongName.substring(0, currSongName.lastIndexOf('/') + 1); + boolean canReallyWrite = true; + boolean alreadyExists = new File(parent + configFileName).exists(); + String needRename = null; + String probablyTheRoot = ""; + String probablyTheDirectory = ""; + + // Safest way to check if we truly have write access to a file. + // We will be touching this file anyway. + // File.canWrite() lies with Lollipop's storage handling. + try { + new FileOutputStream(parent + configFileName, true).close(); + } catch (FileNotFoundException e) { + canReallyWrite = false; + } catch (IOException e) { + e.printStackTrace(); + } + // Delete the test file if it was created and didn't actually exist. + if (!alreadyExists && canReallyWrite) { + new File(parent + configFileName).delete(); + } + if (canReallyWrite && new File(parent).canWrite()) { + configFileName = parent + configFileName; + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && DocumentFileUtils.docFileDevice != null) { + // TODO + // Write the file to getExternalFilesDir, then move it + // with the Uri + // We need to tell JNIHandler that movement is needed. + + String[] tmp = DocumentFileUtils.getExternalFilePaths(context, parent); + probablyTheDirectory = tmp[0]; + probablyTheRoot = tmp[1]; + if (probablyTheDirectory.length() > 1) { + needRename = parent.substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + configFileName; + configFileName = probablyTheDirectory + '/' + configFileName; + } else { + configFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + configFileName; + return; + } + } else { + configFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + configFileName; + } + final String finalval = configFileName; + final boolean canWrite = canReallyWrite; + final String needToRename = needRename; + final String probRoot = probablyTheRoot; + if (new File(finalval).exists() || (new File(probRoot + needRename).exists() && needToRename != null)) { + AlertDialog deletionDialog = new AlertDialog.Builder(context).create(); + deletionDialog.setTitle("Warning"); + deletionDialog.setMessage("Overwrite config file?"); + deletionDialog.setCancelable(false); + deletionDialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getResources().getString(android.R.string.yes), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (needToRename != null) { + DocumentFileUtils.tryToDeleteFile(context, probRoot + needToRename); + DocumentFileUtils.tryToDeleteFile(context, finalval); + } else { + DocumentFileUtils.tryToDeleteFile(context, finalval); + } + } else { + new File(finalval).delete(); + } + saveCfgPart2(finalval, needToRename); + } + }); + deletionDialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getResources().getString(android.R.string.no), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int buttonId) { + } + }); + deletionDialog.show(); + } else { + saveCfgPart2(finalval, needToRename); } } public void saveCfgPart2(final String finalval, final String needToRename) { Intent new_intent = new Intent(); - new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), 16); - new_intent.putExtra(context.getResources().getString(R.string.msrv_outfile), finalval); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, CommandStrings.msrv_cmd_save_cfg); + new_intent.putExtra(CommandStrings.msrv_outfile, finalval); context.sendBroadcast(new_intent); final ProgressDialog prog; prog = new ProgressDialog(context); @@ -178,8 +174,8 @@ public void run() { context.runOnUiThread(new Runnable() { public void run() { String trueName = finalval; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null && needToRename != null) { - if (Globals.renameDocumentFile(context, finalval, needToRename)) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && DocumentFileUtils.docFileDevice != null && needToRename != null) { + if (DocumentFileUtils.renameDocumentFile(context, finalval, needToRename)) { trueName = needToRename; } else { trueName = "Error"; @@ -188,8 +184,8 @@ public void run() { Toast.makeText(context, "Wrote " + trueName, Toast.LENGTH_SHORT).show(); prog.dismiss(); Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(context.getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(context.getResources().getString(R.string.ta_cmd), 1); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_refresh_filebrowser); context.sendBroadcast(outgoingIntent); } }); diff --git a/src/com/xperia64/timidityae/util/DocumentFileUtils.java b/src/com/xperia64/timidityae/util/DocumentFileUtils.java new file mode 100755 index 0000000..00f15b9 --- /dev/null +++ b/src/com/xperia64/timidityae/util/DocumentFileUtils.java @@ -0,0 +1,212 @@ +package com.xperia64.timidityae.util; + +import java.io.File; +import java.io.IOException; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.net.Uri; +import android.os.Build; +import android.support.v4.provider.DocumentFile; +import android.util.Log; + +public class DocumentFileUtils { + + /** + * The DocumentFileUtils class is used to simplify some operations related to API21+'s external storage access. + */ + + public static Uri docFileDevice=null; + + + private static String fixRepeatedSeparator(String filename) + { + return filename.replaceAll(Globals.repeatedSeparatorString, File.separator); + } + + public static boolean tryToDeleteFile(Context c, String filename) { + filename = fixRepeatedSeparator(filename); + if (new File(filename).exists()) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && docFileDevice != null) { + DocumentFile df = DocumentFile.fromTreeUri(c, docFileDevice); + String split[] = filename.split("/"); + int i; + for (i = 0; i < split.length; i++) { + // Did we find the document file? + if (split[i].equals(df.getName())) { + i++; + break; + } + } + while (i < split.length) { + df = df.findFile(split[i++]); + // upper.append("../"); + if (df == null) { + Log.e("TimidityAE Globals", "Delete file error (file not found)"); + return false; + } + } + // Why on earth is DocumentFile's delete method recursive by default? + // Seriously. I wiped my sd card twice because of this. + if (df != null && df.isFile() && !df.isDirectory()) { + df.delete(); + }else{ + Log.e("TimidityAE Globals", "Delete file error (file not found)"); + return false; + } + } else { + new File(filename).delete(); + } + return true; + } + return false; + } + + public static boolean tryToCreateFile(Context context, String filename, String mimetype) { + filename = fixRepeatedSeparator(filename); + if (!(new File(filename).exists())) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && docFileDevice != null) { + DocumentFile df = DocumentFile.fromTreeUri(context, docFileDevice); + String split[] = filename.split("/"); + int i; + for (i = 0; i < split.length; i++) { + if (split[i].equals(df.getName())) { + i++; + break; + } + } + while (i < split.length - 1) { + df = df.findFile(split[i++]); + if (df == null) { + Log.e("TimidityAE Globals", "Create file error."); + return false; + } + } + if (df != null) { + df.createFile(mimetype, split[split.length - 1]); + }else{ + return false; + } + } else { + try { + new File(filename).createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + } + return true; // I guess if it exists already it's technically created + } + + + /** + * Renames/moves a file using the DocumentFile class. + * This is intended for use with API21+ external storage access. + * The existing file must be on the same filesystem as the existing file. + * + * @param context the android context + * @param from the full path to the original file + * @param subTo the path to the new file without the mount point prefix + * @return whether the operation was successful + */ + public static boolean renameDocumentFile(Context context, String from, String subTo) { + // From is the full path + // subTo is the path without the device prefix. + // So /storage/sdcard1/folder/file.mid should be folder/file.mid + if (docFileDevice == null) + return false; + from = fixRepeatedSeparator(from); + subTo = fixRepeatedSeparator(subTo); + DocumentFile df = DocumentFile.fromTreeUri(context, docFileDevice); + String split[] = from.split(File.separator); + int i; + + // Locate the filesystem-relative path by comparing it to the + // DocumentFile root directory. + for (i = 0; i < split.length; i++) { + if (split[i].equals(df.getName())) { + i++; + break; + } + } + StringBuilder upper = new StringBuilder(); + while (i < split.length) { + df = df.findFile(split[i++]); + upper.append(Globals.parentString); // Usually "../" + if (df == null) { + Log.e("TimidityAE Globals", "Rename file error."); + break; + } + } + if (df != null && upper.length() > 3) { + // DocumentFile's rename renames in the context of the current working directory. + // The relative root directory must be specified in terms of many "../" + return df.renameTo(upper.substring(0, upper.length() - 3) + subTo); + } + return false; + } + + + /** + * This method attempts to find the temporary folder on the filesystem containing parent. + * + * + * @param context the android context + * @param parent the parent directory of the file we want + * @return + */ + @SuppressLint("NewApi") + public static String[] getExternalFilePaths(Context context, String parent) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) + return null; // Error. + + parent = fixRepeatedSeparator(parent); + String probablyTheDirectory = ""; + String probablyTheRoot = ""; + File par = new File(parent); + String absoluteParent = par.getAbsolutePath(); + // Ensure that this ends with a separator + // This helps edge cases such as files on root directories of filesystems. + // Where we have folders like /storage/sdcard/ and /storage/sdcard1/ + if(!absoluteParent.endsWith(File.separator)) + { + absoluteParent = absoluteParent+File.separator; + } + File[] x = context.getExternalFilesDirs(null); + for (File f : x) { + if (f != null) { + String ex = f.getAbsolutePath(); + String ss1; + String ss2; + int lastmatch = 1; + while (lastmatch < absoluteParent.length() && lastmatch < ex.length()) { + ss1 = ex.substring(0, lastmatch + 1); + ss2 = absoluteParent.substring(0, lastmatch + 1); + if (ss1.equals(ss2)) { + lastmatch++; + } else { + break; + } + } + String theRoot = absoluteParent.substring(0, lastmatch); + File testFile = new File(theRoot); + // The root must have the path of a folder, exist, and actually be a folder + if (!theRoot.endsWith(File.separator) || !testFile.exists() || !testFile.isDirectory()) { + continue; + } else { + probablyTheDirectory = ex; + probablyTheRoot = theRoot; + break; + } + } + } + String[] rets = new String[2]; + rets[0] = probablyTheDirectory; + rets[1] = probablyTheRoot; + return rets; + } + + + +} diff --git a/src/com/xperia64/timidityae/util/Globals.java b/src/com/xperia64/timidityae/util/Globals.java index ac49751..be80549 100755 --- a/src/com/xperia64/timidityae/util/Globals.java +++ b/src/com/xperia64/timidityae/util/Globals.java @@ -11,16 +11,11 @@ ******************************************************************************/ package com.xperia64.timidityae.util; -import java.io.BufferedReader; -import java.io.DataInputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Field; import java.net.HttpURLConnection; @@ -32,38 +27,25 @@ import javax.net.ssl.HttpsURLConnection; import com.xperia64.timidityae.JNIHandler; -import com.xperia64.timidityae.ObjectSerializer; -import com.xperia64.timidityae.R; import com.xperia64.timidityae.TimidityActivity; import android.annotation.SuppressLint; import android.annotation.TargetApi; -import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; -import android.media.AudioFormat; -import android.media.AudioTrack; -import android.net.Uri; import android.os.AsyncTask; import android.os.Build; -import android.os.Environment; import android.os.PowerManager; -import android.preference.PreferenceManager; -import android.support.v4.provider.DocumentFile; -import android.util.Log; -import android.util.SparseIntArray; +import android.text.InputFilter; +import android.text.Spanned; import android.widget.TextView; import android.widget.Toast; public class Globals { public static boolean libLoaded = false; -public static int isPlaying = 1; // Active low. public static ArrayList plist; // Because arguments don't like big things. public static ArrayList tmpplist; // I'm lazy. public static Bitmap currArt; @@ -71,13 +53,33 @@ public class Globals { public static final String autoSoundfontHeader="#<--------Config Generated By Timidity AE (DO NOT MODIFY)-------->"; +public static String repeatedSeparatorString = String.format("[%c]+",File.separatorChar); +public static String parentString = ".."+File.separator; +public static char[] invalidChars = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '"', ':' }; + + // Fragment Keys -public static String currFoldKey="CURRENT_FOLDER"; -public static String currPlistDirectory="CURRENT_PLIST_DIR"; +//public static String currFoldKey="CURRENT_FOLDER"; +//public static String currPlistDirectory="CURRENT_PLIST_DIR"; public static boolean shouldRestore=false; // Resampling Algorithms public static String[] sampls = {"Cubic Spline","Lagrange","Gaussian","Newton","Linear","None"}; // File filters + + + +public static InputFilter fileNameInputFilter = new InputFilter() { + public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { + for (int i = start; i < end; i++) { + for (int o = 0; o < Globals.invalidChars.length; o++) { + if (source.charAt(i) == Globals.invalidChars[o]) { + return ""; + } + } + } + return null; + } +}; public static String musicFiles = "*.mid*.smf*.kar*.mod*.xm*.s3m*.it*.669*.amf*.dsm*.far*.gdm*.imf*.med*.mtm*.stm*.stx*.ult*.uni*.mp3*.m4a*.wav*.ogg*.flac*"; public static String musicVideoFiles = musicFiles+".mp4*.3gp*"; public static String playlistFiles = "*.tpl*"; @@ -131,7 +133,7 @@ public static String getLibDir(Context c) String s = c.getApplicationInfo().nativeLibraryDir; if(!s.endsWith(File.separator)) { - s+="/"; + s+=File.separator; } return s; }else{ @@ -139,692 +141,24 @@ public static String getLibDir(Context c) } } -public static int[] validRates(boolean stereo, boolean sixteen) -{ - ArrayList valid = new ArrayList(); - for (int rate : new int[] {8000, 11025, 16000, 22050, 44100, 48000, 88200, 96000}) { - - int bufferSize = AudioTrack.getMinBufferSize(rate, (stereo)?AudioFormat.CHANNEL_OUT_STEREO:AudioFormat.CHANNEL_OUT_MONO, (sixteen)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT); - if (bufferSize > 0) { - //System.out.println(rate+" "+bufferSize); - // buffer size is valid, Sample rate supported - valid.add(rate); - } - } - int[] rates = new int[valid.size()]; - for(int i = 0; i buffers = new HashMap(); - for(int rate : rates) - { - buffers.put(rate, AudioTrack.getMinBufferSize(rate, (stereo)?AudioFormat.CHANNEL_OUT_STEREO:AudioFormat.CHANNEL_OUT_MONO, (sixteen)?AudioFormat.ENCODING_PCM_16BIT:AudioFormat.ENCODING_PCM_8BIT)); - } - return buffers;*/ -} -/*public static boolean canWrite(String path) -{ - if(!path.endsWith("/")) - { - return false; - } - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - Random r = new Random(); - // Generate a random unique temporary file. - File f = new File(path+r.nextInt(1000000)); - while(f.exists()) - { - f = new File(path+r.nextInt(1000000)); - try - { - Thread.sleep(10); - } catch (InterruptedException e) - { - e.printStackTrace(); - } - } - try - { - f.createNewFile(); - } catch (IOException e) - { - return false; - } - if(f.exists()) - f.delete(); - return true; - }else{ - return new File(path).canWrite(); - } -}*/ -/*public static boolean canWrite(DocumentFile path) -{ - return false; -}*/ - - public static int probablyFresh=0; public static final int NOTIFICATION_ID = 13901858; -//---------SETTINGS STORAGE---------- -public static SharedPreferences prefs; -public static boolean firstRun; -public static int theme; // 1 = Light, 2 = Dark -public static boolean showHiddenFiles; -public static String defaultFolder; -public static String dataFolder; -public static boolean manConfig; -public static int defSamp; -public static boolean shouldLolNag; -//public static ArrayList soundfonts; // this list should only be touched in SettingsActivity -public static int mono; // 0 = stereo downsampled to mono, 1 = timidity-synthesized mono, 2 = stereo, 3 = downsampled to mono then copied to stereo? -public static boolean sixteen; -public static int aRate; -public static int buff; -public static boolean nativeMidi; -public static boolean keepWav; -public static boolean onlyNative=false; -public static boolean showVideos; -public static boolean useDefaultBack=false; -public static boolean compressCfg = true; -//public static AssetManager assets; -public static boolean nukedWidgets=false; -public static Uri theFold=null; -public static boolean reShuffle = false; -public static boolean preserveSilence = true; -public static boolean freeInsts = true; public static boolean phoneState = true; -public static void reloadSettings(Activity c, AssetManager assets) -{ - - prefs = PreferenceManager - .getDefaultSharedPreferences(c); - firstRun = prefs.getBoolean("tplusFirstRun", true); - theme = Integer.parseInt(prefs.getString("fbTheme", "1")); - showHiddenFiles = prefs.getBoolean("hiddenSwitch", false); - defaultFolder = prefs.getString("defaultPath", Environment.getExternalStorageDirectory().getAbsolutePath()); - dataFolder = prefs.getString("dataDir", Environment.getExternalStorageDirectory()+"/TimidityAE/"); - manConfig = prefs.getBoolean("manualConfig", false); - JNIHandler.currsamp = defSamp = Integer.parseInt(prefs.getString("tplusResamp", "0")); - mono = Integer.parseInt(prefs.getString("sdlChanValue", "2")); - sixteen = true;//prefs.getString("tplusBits", "16").equals("16"); - aRate = Integer.parseInt(prefs.getString("tplusRate", Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM)))); - buff = Integer.parseInt(prefs.getString("tplusBuff", "192000")); - showVideos=prefs.getBoolean("videoSwitch", true); - shouldLolNag=prefs.getBoolean("shouldLolNag", true); - keepWav=prefs.getBoolean("keepPartialWav",false); - useDefaultBack=prefs.getBoolean("useDefBack", false); - compressCfg=prefs.getBoolean("compressCfg", true); - reShuffle=prefs.getBoolean("reShuffle",false); - freeInsts=prefs.getBoolean("tplusUnload", true); - preserveSilence=prefs.getBoolean("tplusSilKey", true); - if(!onlyNative) - nativeMidi = prefs.getBoolean("nativeMidiSwitch", false); - else - nativeMidi = true; - -} -//----------------------------------- - -public static boolean isMidi(String songTitle) -{ - return !(songTitle.toLowerCase(Locale.US).endsWith(".mp3") - || songTitle.toLowerCase(Locale.US).endsWith(".m4a") - || songTitle.toLowerCase(Locale.US).endsWith(".wav") - || songTitle.toLowerCase(Locale.US).endsWith(".ogg") - || songTitle.toLowerCase(Locale.US).endsWith(".flac") - || songTitle.toLowerCase(Locale.US).endsWith(".mp4") - || songTitle.toLowerCase(Locale.US).endsWith(".3gp") - || (Globals.nativeMidi - &&(songTitle.toLowerCase(Locale.US).endsWith(".mid") - || songTitle.toLowerCase(Locale.US).endsWith(".kar") - || songTitle.toLowerCase(Locale.US).endsWith(".smf")))); -} -public static boolean initialize(final Activity a) -{ - if(firstRun) - { - final File rootStorage = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/TimidityAE/"); - if(!rootStorage.exists()) - { - rootStorage.mkdir(); - } - File playlistDir=new File(rootStorage.getAbsolutePath()+"/playlists/"); - if(!playlistDir.exists()) - { - playlistDir.mkdir(); - } - File tcfgDir=new File(rootStorage.getAbsolutePath()+"/timidity/"); - if(!tcfgDir.exists()) - { - tcfgDir.mkdir(); - } - File sfDir=new File(rootStorage.getAbsolutePath()+"/soundfonts/"); - if(!sfDir.exists()) - { - sfDir.mkdir(); - } - updateBuffers(updateRates()); - aRate = Integer.parseInt(prefs.getString("tplusRate", Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM)))); - buff = Integer.parseInt(prefs.getString("tplusBuff", "192000")); // This is usually a safe number, but should probably do a test or something - migrateFrom1X(rootStorage); - final Editor eee = prefs.edit(); - firstRun=false; - eee.putBoolean("tplusFirstRun", false); - eee.putString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath()+"/TimidityAE/"); - if(new File(dataFolder+"/timidity/timidity.cfg").exists()) - { - if(manConfig = !cfgIsAuto(dataFolder+"/timidity/timidity.cfg")) - { - eee.putBoolean("manConfig", true); - }else{ - eee.putBoolean("manConfig", false); - ArrayList soundfonts = new ArrayList(); - FileInputStream fstream = null; - try { - fstream = new FileInputStream(dataFolder+"/timidity/timidity.cfg"); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - // Get the object of DataInputStream - DataInputStream in = new DataInputStream(fstream); - BufferedReader br = new BufferedReader(new InputStreamReader(in)); - //Read File Line By Line - try { - br.readLine(); // skip first line - } catch (IOException e) { - e.printStackTrace(); - } - String line; - try { - while((line=br.readLine())!=null) - { - if(line.indexOf("soundfont \"")>=0&&line.lastIndexOf('"')>=0) - { - try{ - String st=line.substring(line.indexOf("soundfont \"")+11,line.lastIndexOf('"')); - soundfonts.add(st); - }catch (ArrayIndexOutOfBoundsException e1) - { - e1.printStackTrace(); - } - - } - } - } catch (IOException e) { - e.printStackTrace(); - } - try { - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - try { - eee.putString("tplusSoundfonts", ObjectSerializer.serialize(soundfonts)); - } catch (IOException e) { - e.printStackTrace(); - } - } - eee.commit(); - return true; - }else{ - // Should probably check if 8rock11e exists no matter what - eee.putBoolean("manConfig", false); - - AsyncTask task = new AsyncTask() { - - ProgressDialog pd; - @Override - protected void onPreExecute() { - pd = new ProgressDialog(a); - pd.setTitle(a.getResources().getString(R.string.extract)); - pd.setMessage(a.getResources().getString(R.string.extract_sum)); - pd.setCancelable(false); - pd.setIndeterminate(true); - pd.show(); - } - - @Override - protected Void doInBackground(Void... arg0) { - - if(extract8Rock(a)!=777) - { - Toast.makeText(a, "Could not extrct default soundfont", Toast.LENGTH_SHORT).show(); - } - return null; - } - - @Override - protected void onPostExecute(Void result) { - if(pd!=null) - pd.dismiss(); - ArrayList tmpConfig = new ArrayList(); - tmpConfig.add(rootStorage.getAbsolutePath()+"/soundfonts/8Rock11e.sf2"); - try { - eee.putString("tplusSoundfonts", ObjectSerializer.serialize(tmpConfig)); - } catch (IOException e) { - e.printStackTrace(); - } - eee.commit(); - writeCfg(a, rootStorage.getAbsolutePath()+"/timidity/timidity.cfg",tmpConfig); - ((TimidityActivity)a).initCallback(); - } - - }; - task.execute((Void[])null); - return false; - } - - - - }else{ - return true; - } -} -public static void migrateFrom1X(File newData) +public static boolean isMidi(String songFileName) { - File oldPlists = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/com.xperia64.timidityae/playlists/"); - if(oldPlists.exists()) - { - if(oldPlists.isDirectory()) - { - for(File f : oldPlists.listFiles()) - { - if(f.getName().toLowerCase(Locale.US).endsWith(".tpl")) - { - f.renameTo(new File(newData.getAbsolutePath()+"/playlists/"+f.getName())); - } - } - } - } - File oldSoundfonts = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/com.xperia64.timidityae/soundfonts/"); - if(oldSoundfonts.exists()) - { - if(oldSoundfonts.isDirectory()) - { - for(File f : oldSoundfonts.listFiles()) - { - if(f.getName().toLowerCase(Locale.US).endsWith(".sf2")||f.getName().toLowerCase(Locale.US).endsWith(".sfark")) - { - f.renameTo(new File(newData.getAbsolutePath()+"/soundfonts/"+f.getName())); - } - } - } - } + return !(songFileName.toLowerCase(Locale.US).endsWith(".mp3") + || songFileName.toLowerCase(Locale.US).endsWith(".m4a") + || songFileName.toLowerCase(Locale.US).endsWith(".wav") + || songFileName.toLowerCase(Locale.US).endsWith(".ogg") + || songFileName.toLowerCase(Locale.US).endsWith(".flac") + || songFileName.toLowerCase(Locale.US).endsWith(".mp4") + || songFileName.toLowerCase(Locale.US).endsWith(".3gp") + || (SettingsStorage.nativeMidi + &&(songFileName.toLowerCase(Locale.US).endsWith(".mid") + || songFileName.toLowerCase(Locale.US).endsWith(".kar") + || songFileName.toLowerCase(Locale.US).endsWith(".smf")))); } -public static void writeCfg(Context c, String path, ArrayList soundfonts) -{ - if(path==null) - { - Toast.makeText(c, "Configuration path null (3)", Toast.LENGTH_LONG).show(); - return; - } - if(soundfonts==null) - { - Toast.makeText(c, "Soundfonts null (4)", Toast.LENGTH_LONG).show(); - return; - } - if(path.contains("//")) - { - path = path.replace("//", "/"); - } - if(!manConfig) - { - String[] needLol = null; - try{ - new FileOutputStream(path,true).close(); - }catch(FileNotFoundException e) - { - needLol=getDocFilePaths(c, path); - } catch (IOException e) - { - e.printStackTrace(); - } - - if(needLol!=null&&Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) - { - if(theFold!=null) - { - String probablyTheDirectory = needLol[0]; - String probablyTheRoot = needLol[1]; - String needRename = null; - String value = null; - if(probablyTheDirectory.length()>1) - { - needRename = path.substring(path.indexOf(probablyTheRoot)+probablyTheRoot.length()); - value = probablyTheDirectory+path.substring(path.lastIndexOf('/')); - }else{ - return; - } - if(new File(path).exists()) - { - if(cfgIsAuto(path)||new File(path).length()<=0) - { - Globals.tryToDeleteFile(c, path); - }else{ - Toast.makeText(c, "Renaming manually edited cfg... (7)", Toast.LENGTH_LONG).show(); - renameDocumentFile(c, path, needRename+".manualTimidityCfg."+Long.toString(System.currentTimeMillis())); - } - } - - FileWriter fw = null; - try { - fw = new FileWriter(value,false); - } catch (IOException e) { - e.printStackTrace(); - } - try { - fw.write(autoSoundfontHeader+"\n"); - } catch (IOException e) { - e.printStackTrace(); - } - - for(String s : soundfonts) - { - try { - fw.write((s.startsWith("#")?"#":"")+"soundfont \""+s+"\"\n"); - } catch (IOException e) { - e.printStackTrace(); - } - } - try { - fw.close(); - } catch (IOException e) { - e.printStackTrace(); - } - Globals.renameDocumentFile(c, value, needRename); - }else{ - Toast.makeText(c, "Could not write configuration file. Does Timidity AE have write access to the data folder? (1)", Toast.LENGTH_LONG).show(); - } - - - }else{ - - File theConfig = new File(path); - if(theConfig.exists()) // It should exist if we got here. - { - if(!theConfig.canWrite()) - { - Toast.makeText(c, "Could not write configuration file. Does Timidity AE have write access to the data folder? (2)", Toast.LENGTH_LONG).show(); - return; - } - if(cfgIsAuto(path)||theConfig.length()<=0) // Negative file length? Who knows. - { - theConfig.delete(); // Auto config, safe to delete - }else{ - Toast.makeText(c, "Renaming manually edited cfg... (6)", Toast.LENGTH_LONG).show(); - theConfig.renameTo(new File(path+".manualTimidityCfg."+Long.toString(System.currentTimeMillis()))); // manual config, rename for later - } - } - FileWriter fw = null; - try { - fw = new FileWriter(path,false); - } catch (IOException e) { - - e.printStackTrace(); - } - try { - fw.write(autoSoundfontHeader+"\n"); - } catch (IOException e) { - e.printStackTrace(); - } - - for(String s : soundfonts) - { - if(s==null) - continue; - try { - fw.write((s.startsWith("#")?"#":"")+"soundfont \""+s+"\"\n"); - } catch (IOException e) { - e.printStackTrace(); - } - } - try { - fw.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } -} -@SuppressLint("NewApi") -public static String[] getDocFilePaths(Context c, String parent) -{ - if(Build.VERSION.SDK_INT3) - { - return xx.renameTo(upper.substring(0, upper.length()-3)+subTo); - } - return false; -} -public static void tryToDeleteFile(Context c, String filename) -{ - filename = filename.replace("//", "/"); - if(new File(filename).exists()) - { - if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP&& Globals.theFold!=null) - { - DocumentFile df = DocumentFile.fromTreeUri(c, theFold); - String split[] = filename.split("/"); - int i; - for(i = 0; i=Build.VERSION_CODES.LOLLIPOP&&theFold!=null) - { - DocumentFile df = DocumentFile.fromTreeUri(c, theFold); - String split[] = filename.split("/"); - int i; - for(i = 0; i1) { - needRename = dataFolder.substring(dataFolder.indexOf(probablyTheRoot)+probablyTheRoot.length())+"/soundfonts/8Rock11e.sf2"; + needRename = SettingsStorage.dataFolder.substring(SettingsStorage.dataFolder.indexOf(probablyTheRoot)+probablyTheRoot.length())+"/soundfonts/8Rock11e.sf2"; value = probablyTheDirectory+'/'+"8Rock11e.sfArk"; value2 = probablyTheDirectory+'/'+"8Rock11e.sf2"; }else{ @@ -890,16 +224,16 @@ public static int extract8Rock(Context c) e.printStackTrace(); } JNIHandler.decompressSFArk(value, "8Rock11e.sf2"); - renameDocumentFile(c, value2, needRename); - tryToDeleteFile(c,value); + DocumentFileUtils.renameDocumentFile(c, value2, needRename); + DocumentFileUtils.tryToDeleteFile(c,value); }else{ - File f = new File(Globals.dataFolder+"/soundfonts/8Rock11e.sfArk"); + File f = new File(SettingsStorage.dataFolder+"/soundfonts/8Rock11e.sfArk"); if (f!=null) if(f.exists()) f.delete(); OutputStream out = null; try { - out = new FileOutputStream( Globals.dataFolder+"/soundfonts/8Rock11e.sfArk" ); + out = new FileOutputStream( SettingsStorage.dataFolder+"/soundfonts/8Rock11e.sfArk" ); } catch (FileNotFoundException e) { e.printStackTrace(); } @@ -923,9 +257,9 @@ public static int extract8Rock(Context c) } catch (IOException e) { e.printStackTrace(); } - JNIHandler.decompressSFArk(Globals.dataFolder+"/soundfonts/8Rock11e.sfArk", "8Rock11e.sf2"); + JNIHandler.decompressSFArk(SettingsStorage.dataFolder+"/soundfonts/8Rock11e.sfArk", "8Rock11e.sf2"); //System.out.println("decompresed sfark"); - new File(Globals.dataFolder+"/soundfonts/8Rock11e.sfArk").delete(); + new File(SettingsStorage.dataFolder+"/soundfonts/8Rock11e.sfArk").delete(); } return 777; diff --git a/src/com/xperia64/timidityae/ObjectSerializer.java b/src/com/xperia64/timidityae/util/ObjectSerializer.java similarity index 95% rename from src/com/xperia64/timidityae/ObjectSerializer.java rename to src/com/xperia64/timidityae/util/ObjectSerializer.java index cc29ccd..87f0a98 100755 --- a/src/com/xperia64/timidityae/ObjectSerializer.java +++ b/src/com/xperia64/timidityae/util/ObjectSerializer.java @@ -16,7 +16,7 @@ * limitations under the License. */ -package com.xperia64.timidityae; +package com.xperia64.timidityae.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/src/com/xperia64/timidityae/util/SettingsStorage.java b/src/com/xperia64/timidityae/util/SettingsStorage.java index 0d7d100..714276b 100755 --- a/src/com/xperia64/timidityae/util/SettingsStorage.java +++ b/src/com/xperia64/timidityae/util/SettingsStorage.java @@ -1,5 +1,461 @@ package com.xperia64.timidityae.util; +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Locale; + +import com.xperia64.timidityae.JNIHandler; +import com.xperia64.timidityae.R; +import com.xperia64.timidityae.TimidityActivity; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.app.ProgressDialog; +import android.app.UiModeManager; +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.content.res.AssetManager; +import android.content.res.Configuration; +import android.media.AudioFormat; +import android.media.AudioTrack; +import android.os.AsyncTask; +import android.os.Build; +import android.os.Environment; +import android.preference.PreferenceManager; +import android.util.SparseIntArray; +import android.widget.Toast; + public class SettingsStorage { + // ---------SETTINGS STORAGE---------- + private static SharedPreferences prefs; // The preferences used by this class + public static boolean firstRun; + public static int theme; // 1 = Light, 2 = Dark + public static boolean showHiddenFiles; + public static String homeFolder; + public static String dataFolder; + public static boolean manualConfig; + public static int defaultResamp; + public static boolean shouldExtStorageNag; + public static int channelMode; // 0 = stereo downsampled to mono, 1 = timidity-synthesized mono, 2 = stereo + public static boolean sixteenBit; + public static int audioRate; + public static boolean nativeMidi; + public static int bufferSize; + public static boolean keepPartialWav; + public static boolean onlyNative; + public static boolean showVideos; + public static boolean useDefaultBack; + public static boolean compressCfg = true; + public static boolean nukedWidgets; + public static boolean reShuffle; + public static boolean preserveSilence = true; + public static boolean freeInsts = true; + public static boolean isTV; + + @SuppressLint("NewApi") + public static void reloadSettings(Activity c, AssetManager assets) { + + prefs = PreferenceManager.getDefaultSharedPreferences(c); + firstRun = prefs.getBoolean(CommandStrings.sett_first_run, true); + theme = Integer.parseInt(prefs.getString(CommandStrings.sett_theme, "1")); + showHiddenFiles = prefs.getBoolean(CommandStrings.sett_show_hidden_files, false); + homeFolder = prefs.getString(CommandStrings.sett_home_folder, Environment.getExternalStorageDirectory().getAbsolutePath()); + dataFolder = prefs.getString(CommandStrings.sett_data_folder, Environment.getExternalStorageDirectory() + "/TimidityAE/"); + manualConfig = prefs.getBoolean(CommandStrings.sett_man_config, false); + JNIHandler.currsamp = defaultResamp = Integer.parseInt(prefs.getString(CommandStrings.sett_default_resamp, "0")); + channelMode = Integer.parseInt(prefs.getString(CommandStrings.sett_channel_mode, "2")); + sixteenBit = true;// prefs.getString("tplusBits", "16").equals("16"); + audioRate = Integer.parseInt(prefs.getString(CommandStrings.sett_audio_rate, Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM)))); + bufferSize = Integer.parseInt(prefs.getString(CommandStrings.sett_buffer_size, "192000")); + showVideos = prefs.getBoolean(CommandStrings.sett_show_videos, true); + shouldExtStorageNag = prefs.getBoolean(CommandStrings.sett_should_ext_storage_nag, true); + keepPartialWav = prefs.getBoolean(CommandStrings.sett_keep_partal_wave, false); + useDefaultBack = prefs.getBoolean(CommandStrings.sett_default_back_btn, false); + compressCfg = prefs.getBoolean(CommandStrings.sett_compress_midi_cfg, true); + reShuffle = prefs.getBoolean(CommandStrings.sett_reshuffle_plist, false); + freeInsts = prefs.getBoolean(CommandStrings.sett_free_insts, true); + preserveSilence = prefs.getBoolean(CommandStrings.sett_preserve_silence, true); + if (!onlyNative) + nativeMidi = prefs.getBoolean(CommandStrings.sett_native_midi, false); + else + nativeMidi = true; + UiModeManager uiModeManager = (UiModeManager) c.getSystemService(Context.UI_MODE_SERVICE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { + isTV = (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION); + } + + } + // ----------------------------------- + + public static int[] updateRates() { + if (prefs != null) { + int[] values = validRates(prefs.getString(CommandStrings.sett_channel_mode, "2").equals("2"), true); + CharSequence[] hz = new CharSequence[values.length]; + CharSequence[] hzItems = new CharSequence[values.length]; + boolean validRate = false; + for (int i = 0; i < values.length; i++) { + hz[i] = Integer.toString(values[i]) + "Hz"; + hzItems[i] = Integer.toString(values[i]); + if (prefs.getString("tplusRate", Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))).equals(hzItems[i])) { + validRate = true; + break; + } + } + + if (!validRate) + prefs.edit().putString("tplusRate", Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))).commit(); + + return values; + } + return null; + } + + public static boolean updateBuffers(int[] rata) { + if (rata != null) { + SparseIntArray buffMap = validBuffers(rata, prefs.getString(CommandStrings.sett_channel_mode, "2").equals("2"), true); + int realMin = buffMap.get(Integer.parseInt(prefs.getString(CommandStrings.sett_audio_rate, Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))))); + if (bufferSize < realMin) { + prefs.edit().putString(CommandStrings.sett_buffer_size, Integer.toString(bufferSize = realMin)).commit(); + return false; + } + } + return true; + } + + public static void disableLollipopStorageNag() { + prefs.edit().putBoolean(CommandStrings.sett_should_ext_storage_nag, shouldExtStorageNag = false).commit(); + } + + public static boolean initialize(final Activity a) { + if (firstRun) { + final File rootStorage = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/"); + + // Create TimidityAE's default data folder + if (!rootStorage.exists()) { + rootStorage.mkdir(); + } + // Create the playlist folder + File playlistDir = new File(rootStorage.getAbsolutePath() + "/playlists/"); + if (!playlistDir.exists()) { + playlistDir.mkdir(); + } + File tcfgDir = new File(rootStorage.getAbsolutePath() + "/timidity/"); + if (!tcfgDir.exists()) { + tcfgDir.mkdir(); + } + File sfDir = new File(rootStorage.getAbsolutePath() + "/soundfonts/"); + if (!sfDir.exists()) { + sfDir.mkdir(); + } + updateBuffers(updateRates()); + audioRate = Integer.parseInt(prefs.getString("tplusRate", Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM)))); + // This is usually a safe number, but should probably do a test or something + bufferSize = Integer.parseInt(prefs.getString("tplusBuff", "192000")); + migrateFrom1X(rootStorage); + final Editor eee = prefs.edit(); + firstRun = false; + eee.putBoolean("tplusFirstRun", false); + eee.putString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/"); + if (new File(dataFolder + "/timidity/timidity.cfg").exists()) { + if (manualConfig = !cfgIsAuto(dataFolder + "/timidity/timidity.cfg")) { + eee.putBoolean("manConfig", true); + } else { + eee.putBoolean("manConfig", false); + ArrayList soundfonts = new ArrayList(); + FileInputStream fstream = null; + try { + fstream = new FileInputStream(dataFolder + "/timidity/timidity.cfg"); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + // Get the object of DataInputStream + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + // Read File Line By Line + try { + br.readLine(); // skip first line + } catch (IOException e) { + e.printStackTrace(); + } + String line; + try { + while ((line = br.readLine()) != null) { + if (line.indexOf("soundfont \"") >= 0 && line.lastIndexOf('"') >= 0) { + try { + String st = line.substring(line.indexOf("soundfont \"") + 11, line.lastIndexOf('"')); + soundfonts.add(st); + } catch (ArrayIndexOutOfBoundsException e1) { + e1.printStackTrace(); + } + + } + } + } catch (IOException e) { + e.printStackTrace(); + } + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + try { + eee.putString("tplusSoundfonts", ObjectSerializer.serialize(soundfonts)); + } catch (IOException e) { + e.printStackTrace(); + } + } + eee.commit(); + return true; + } else { + // Should probably check if 8rock11e exists no matter what + eee.putBoolean("manConfig", false); + + AsyncTask task = new AsyncTask() { + + ProgressDialog pd; + + @Override + protected void onPreExecute() { + pd = new ProgressDialog(a); + pd.setTitle(a.getResources().getString(R.string.extract)); + pd.setMessage(a.getResources().getString(R.string.extract_sum)); + pd.setCancelable(false); + pd.setIndeterminate(true); + pd.show(); + } + + @Override + protected Void doInBackground(Void... arg0) { + + if (Globals.extract8Rock(a) != 777) { + Toast.makeText(a, "Could not extrct default soundfont", Toast.LENGTH_SHORT).show(); + } + return null; + } + + @Override + protected void onPostExecute(Void result) { + if (pd != null) + pd.dismiss(); + ArrayList tmpConfig = new ArrayList(); + tmpConfig.add(rootStorage.getAbsolutePath() + "/soundfonts/8Rock11e.sf2"); + try { + eee.putString("tplusSoundfonts", ObjectSerializer.serialize(tmpConfig)); + } catch (IOException e) { + e.printStackTrace(); + } + eee.commit(); + writeCfg(a, rootStorage.getAbsolutePath() + "/timidity/timidity.cfg", tmpConfig); + ((TimidityActivity) a).initCallback(); + } + + }; + task.execute((Void[]) null); + return false; + } + + } else { + return true; + } + } + + // This can probably be removed soon. + public static void migrateFrom1X(File newData) { + File oldPlists = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.xperia64.timidityae/playlists/"); + if (oldPlists.exists()) { + if (oldPlists.isDirectory()) { + for (File f : oldPlists.listFiles()) { + if (f.getName().toLowerCase(Locale.US).endsWith(".tpl")) { + f.renameTo(new File(newData.getAbsolutePath() + "/playlists/" + f.getName())); + } + } + } + } + File oldSoundfonts = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.xperia64.timidityae/soundfonts/"); + if (oldSoundfonts.exists()) { + if (oldSoundfonts.isDirectory()) { + for (File f : oldSoundfonts.listFiles()) { + if (f.getName().toLowerCase(Locale.US).endsWith(".sf2") || f.getName().toLowerCase(Locale.US).endsWith(".sfark")) { + f.renameTo(new File(newData.getAbsolutePath() + "/soundfonts/" + f.getName())); + } + } + } + } + } + + public static void writeCfg(Context c, String path, ArrayList soundfonts) { + if (path == null) { + Toast.makeText(c, "Configuration path null (3)", Toast.LENGTH_LONG).show(); + return; + } + if (soundfonts == null) { + Toast.makeText(c, "Soundfonts null (4)", Toast.LENGTH_LONG).show(); + return; + } + path = path.replaceAll("[/]+", "/"); + if (!manualConfig) { + String[] needLol = null; + try { + new FileOutputStream(path, true).close(); + } catch (FileNotFoundException e) { + needLol = DocumentFileUtils.getExternalFilePaths(c, path); + } catch (IOException e) { + e.printStackTrace(); + } + + if (needLol != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (DocumentFileUtils.docFileDevice != null) { + String probablyTheDirectory = needLol[0]; + String probablyTheRoot = needLol[1]; + String needRename = null; + String value = null; + if (probablyTheDirectory.length() > 1) { + needRename = path.substring(path.indexOf(probablyTheRoot) + probablyTheRoot.length()); + value = probablyTheDirectory + path.substring(path.lastIndexOf('/')); + } else { + return; + } + if (new File(path).exists()) { + if (cfgIsAuto(path) || new File(path).length() <= 0) { + DocumentFileUtils.tryToDeleteFile(c, path); + } else { + Toast.makeText(c, "Renaming manually edited cfg... (7)", Toast.LENGTH_LONG).show(); + DocumentFileUtils.renameDocumentFile(c, path, needRename + ".manualTimidityCfg." + Long.toString(System.currentTimeMillis())); + } + } + + FileWriter fw = null; + try { + fw = new FileWriter(value, false); + } catch (IOException e) { + e.printStackTrace(); + } + try { + fw.write(Globals.autoSoundfontHeader + "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + + for (String s : soundfonts) { + try { + fw.write((s.startsWith("#") ? "#" : "") + "soundfont \"" + s + "\"\n"); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + DocumentFileUtils.renameDocumentFile(c, value, needRename); + } else { + Toast.makeText(c, "Could not write configuration file. Does Timidity AE have write access to the data folder? (1)", Toast.LENGTH_LONG).show(); + } + + } else { + + File theConfig = new File(path); + if (theConfig.exists()) // It should exist if we got here. + { + if (!theConfig.canWrite()) { + Toast.makeText(c, "Could not write configuration file. Does Timidity AE have write access to the data folder? (2)", Toast.LENGTH_LONG).show(); + return; + } + if (cfgIsAuto(path) || theConfig.length() <= 0) // Negative file length? Who knows. + { + theConfig.delete(); // Auto config, safe to delete + } else { + Toast.makeText(c, "Renaming manually edited cfg... (6)", Toast.LENGTH_LONG).show(); + theConfig.renameTo(new File(path + ".manualTimidityCfg." + Long.toString(System.currentTimeMillis()))); // manual config, rename for later + } + } + FileWriter fw = null; + try { + fw = new FileWriter(path, false); + } catch (IOException e) { + + e.printStackTrace(); + } + try { + fw.write(Globals.autoSoundfontHeader + "\n"); + } catch (IOException e) { + e.printStackTrace(); + } + + for (String s : soundfonts) { + if (s == null) + continue; + try { + fw.write((s.startsWith("#") ? "#" : "") + "soundfont \"" + s + "\"\n"); + } catch (IOException e) { + e.printStackTrace(); + } + } + try { + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + public static boolean cfgIsAuto(String path) { + String firstLine = ""; + try { + FileInputStream fstream = new FileInputStream(path); + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + firstLine = br.readLine(); + + in.close(); + } catch (Exception e) { + } + if (firstLine != null) + return firstLine.contains(Globals.autoSoundfontHeader); + return false; + } + + public static int[] validRates(boolean stereo, boolean sixteen) { + ArrayList valid = new ArrayList(); + for (int rate : new int[] { 8000, 11025, 16000, 22050, 44100, 48000, 88200, 96000 }) { + + int bufferSize = AudioTrack.getMinBufferSize(rate, (stereo) ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO, (sixteen) ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT); + if (bufferSize > 0) { + // System.out.println(rate+" "+bufferSize); + // buffer size is valid, Sample rate supported + valid.add(rate); + } + } + int[] rates = new int[valid.size()]; + for (int i = 0; i < rates.length; i++) + rates[i] = valid.get(i); + return rates; + } + + public static SparseIntArray validBuffers(int[] rates, boolean stereo, boolean sixteen) { + SparseIntArray buffers = new SparseIntArray(); + for (int rate : rates) { + buffers.put(rate, AudioTrack.getMinBufferSize(rate, (stereo) ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO, (sixteen) ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT)); + } + return buffers; + } + /* + * public static boolean canWrite(String path) { if(!path.endsWith("/")) { return false; } if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) { Random r = new Random(); // Generate a random unique temporary file. File f = new File(path+r.nextInt(1000000)); while(f.exists()) { f = new File(path+r.nextInt(1000000)); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } try { f.createNewFile(); } catch (IOException e) { return false; } if(f.exists()) + * f.delete(); return true; }else{ return new File(path).canWrite(); } } + */ + /* + * public static boolean canWrite(DocumentFile path) { return false; } + */ } diff --git a/src/com/xperia64/timidityae/util/WavSaver.java b/src/com/xperia64/timidityae/util/WavSaver.java index fcd3468..6ddf638 100755 --- a/src/com/xperia64/timidityae/util/WavSaver.java +++ b/src/com/xperia64/timidityae/util/WavSaver.java @@ -18,7 +18,7 @@ import android.os.Build; import android.os.Environment; import android.text.InputFilter; -import android.text.Spanned; +import android.util.Log; import android.widget.EditText; import android.widget.Toast; @@ -37,25 +37,14 @@ public WavSaver(Activity context, String currSongName, boolean playingExport) { public void dynExport() { localfinished = false; - if (Globals.isMidi(currSongName) && (Globals.isPlaying == 0 || !playingExport)) { + if (Globals.isMidi(currSongName) && (JNIHandler.isPlaying || !playingExport)) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle(context.getResources().getString(R.string.dynex_alert1)); alert.setMessage(context.getResources().getString(R.string.dynex_alert1_msg)); - InputFilter filter = new InputFilter() { - public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { - for (int i = start; i < end; i++) { - String IC = "*/*\n*\r*\t*\0*\f*`*?***\\*<*>*|*\"*:*"; - if (IC.contains("*" + source.charAt(i) + "*")) { - return ""; - } - } - return null; - } - }; final EditText input = new EditText(context); - input.setFilters(new InputFilter[] { filter }); + input.setFilters(new InputFilter[] { Globals.fileNameInputFilter }); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @@ -82,12 +71,14 @@ public void onClick(DialogInterface dialog, int whichButton) { if (aWrite && new File(parent).canWrite()) { value = parent + value; - } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null) { - String[] tmp = Globals.getDocFilePaths(context, parent); + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && DocumentFileUtils.docFileDevice != null) { + String[] tmp = DocumentFileUtils.getExternalFilePaths(context, parent); probablyTheDirectory = tmp[0]; probablyTheRoot = tmp[1]; + if (probablyTheDirectory.length() > 1) { needRename = parent.substring(parent.indexOf(probablyTheRoot) + probablyTheRoot.length()) + value; + Log.i("WavSaver","needRename is "+needRename); value = probablyTheDirectory + '/' + value; } else { value = Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + value; @@ -108,10 +99,10 @@ public void onClick(DialogInterface dialog, int whichButton) { public void onClick(DialogInterface dialog, int buttonId) { if (!canWrite && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (needToRename != null) { - Globals.tryToDeleteFile(context, probRoot + needToRename); - Globals.tryToDeleteFile(context, finalval); + DocumentFileUtils.tryToDeleteFile(context, probRoot + needToRename); + DocumentFileUtils.tryToDeleteFile(context, finalval); } else { - Globals.tryToDeleteFile(context, finalval); + DocumentFileUtils.tryToDeleteFile(context, finalval); } } else { new File(finalval).delete(); @@ -144,12 +135,12 @@ public void onClick(DialogInterface dialog, int whichButton) { public void saveWavPart2(final String finalval, final String needToRename) { Intent new_intent = new Intent(); - new_intent.setAction(context.getResources().getString(R.string.msrv_rec)); - new_intent.putExtra(context.getResources().getString(R.string.msrv_cmd), playingExport ? 15 : 14); + new_intent.setAction(CommandStrings.msrv_rec); + new_intent.putExtra(CommandStrings.msrv_cmd, playingExport ? CommandStrings.msrv_cmd_write_curr : CommandStrings.msrv_cmd_write_new); if (!playingExport) { - new_intent.putExtra(context.getResources().getString(R.string.msrv_infile), currSongName); + new_intent.putExtra(CommandStrings.msrv_infile, currSongName); } - new_intent.putExtra(context.getResources().getString(R.string.msrv_outfile), finalval); + new_intent.putExtra(CommandStrings.msrv_outfile, finalval); context.sendBroadcast(new_intent); final ProgressDialog prog; prog = new ProgressDialog(context); @@ -182,13 +173,13 @@ public void run() { context.runOnUiThread(new Runnable() { public void run() { Toast.makeText(context, "Conversion canceled", Toast.LENGTH_SHORT).show(); - if (!Globals.keepWav) { + if (!SettingsStorage.keepPartialWav) { if (new File(finalval).exists()) new File(finalval).delete(); } else { Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(context.getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(context.getResources().getString(R.string.ta_cmd), 1); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_refresh_filebrowser); context.sendBroadcast(outgoingIntent); } } @@ -198,8 +189,8 @@ public void run() { context.runOnUiThread(new Runnable() { public void run() { String trueName = finalval; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Globals.theFold != null && needToRename != null) { - if (Globals.renameDocumentFile(context, finalval, needToRename)) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && DocumentFileUtils.docFileDevice != null && needToRename != null) { + if (DocumentFileUtils.renameDocumentFile(context, finalval, needToRename)) { trueName = needToRename; } else { trueName = "Error"; @@ -208,8 +199,8 @@ public void run() { Toast.makeText(context, "Wrote " + trueName, Toast.LENGTH_SHORT).show(); prog.dismiss(); Intent outgoingIntent = new Intent(); - outgoingIntent.setAction(context.getResources().getString(R.string.ta_rec)); - outgoingIntent.putExtra(context.getResources().getString(R.string.ta_cmd), 1); + outgoingIntent.setAction(CommandStrings.ta_rec); + outgoingIntent.putExtra(CommandStrings.ta_cmd, CommandStrings.ta_cmd_refresh_filebrowser); context.sendBroadcast(outgoingIntent); } }); From 47d47eeaa2e1fa8e331a87d3e52bae0f321de473 Mon Sep 17 00:00:00 2001 From: xperia64 Date: Mon, 22 Feb 2016 22:06:38 -0500 Subject: [PATCH 03/20] Update to 2.7.0, swap branches --- AndroidManifest.xml | 4 +- jni/helper/helper.c | 22 +- jni/timidity/Android.mk | 1 - jni/timidity/opensl_io.c | 534 ------------- jni/timidity/opensl_io.h | 121 --- res/drawable-hdpi/ic_menu_moreoverflow.png | Bin 0 -> 982 bytes res/drawable-mdpi/ic_menu_moreoverflow.png | Bin 0 -> 854 bytes res/drawable-xhdpi/ic_menu_moreoverflow.png | Bin 0 -> 1204 bytes res/drawable-xxhdpi/ic_menu_moreoverflow.png | Bin 0 -> 1985 bytes res/layout-v14/list_reorder.xml | 14 + res/layout-v14/row_menu.xml | 29 + res/layout-v21/music_notification.xml | 4 +- res/layout-v21/settings_toolbar.xml | 11 +- res/layout/filebrowser.xml | 62 +- res/layout/fragment_page.xml | 6 +- res/layout/list.xml | 26 +- res/layout/lyrical_fragment.xml | 27 +- res/layout/main.xml | 3 +- res/layout/midi_options.xml | 344 ++++---- res/layout/music_notification.xml | 16 +- res/layout/player.xml | 8 +- res/layout/row.xml | 18 +- res/layout/row_check.xml | 36 +- res/layout/settings_toolbar.xml | 10 +- res/layout/track_dialog.xml | 137 ++-- res/layout/track_fragment.xml | 21 +- res/layout/widget_layout.xml | 8 +- res/menu/main_menu.xml | 42 +- res/values-sw600dp/dimens.xml | 2 +- res/values-sw720dp-land/dimens.xml | 2 +- res/values-v11/styles.xml | 2 +- res/values-v14/dimens.xml | 4 +- res/values-v14/styles.xml | 2 +- res/values/colors.xml | 8 +- res/values/dimens.xml | 3 +- res/values/strings.xml | 752 +++++++++--------- res/values/styles.xml | 4 +- res/xml-v14/settings.xml | 147 ++++ res/xml-v21/settings.xml | 277 ++++--- res/xml/settings.xml | 262 +++--- res/xml/timidity_widget.xml | 14 +- .../xperia64/timidityae/DummyActivity.java | 2 + src/com/xperia64/timidityae/JNIHandler.java | 43 +- src/com/xperia64/timidityae/MusicService.java | 396 ++++----- .../xperia64/timidityae/SettingsActivity.java | 32 +- .../xperia64/timidityae/TimidityActivity.java | 355 ++++++--- .../timidityae/gui/DynamicListView.java | 615 ++++++++++++++ .../timidityae/gui/StableArrayAdapter.java | 124 +++ .../gui/TimidityAEWidgetProvider.java | 2 +- .../gui/dialogs/FileBrowserDialog.java | 13 + .../gui/fragments/FileBrowserFragment.java | 29 +- .../gui/fragments/PlayerFragment.java | 172 ++-- .../gui/fragments/PlaylistFragment.java | 585 ++++++++------ .../timidityae/util/CommandStrings.java | 140 +++- .../xperia64/timidityae/util/ConfigSaver.java | 14 +- .../timidityae/util/DocumentFileUtils.java | 4 +- .../timidityae/util/DownloadTask.java | 206 +++++ src/com/xperia64/timidityae/util/Globals.java | 303 ++----- .../timidityae/util/SettingsStorage.java | 9 +- .../xperia64/timidityae/util/WavSaver.java | 18 +- 60 files changed, 3365 insertions(+), 2680 deletions(-) delete mode 100755 jni/timidity/opensl_io.c delete mode 100755 jni/timidity/opensl_io.h create mode 100755 res/drawable-hdpi/ic_menu_moreoverflow.png create mode 100755 res/drawable-mdpi/ic_menu_moreoverflow.png create mode 100755 res/drawable-xhdpi/ic_menu_moreoverflow.png create mode 100755 res/drawable-xxhdpi/ic_menu_moreoverflow.png create mode 100755 res/layout-v14/list_reorder.xml create mode 100755 res/layout-v14/row_menu.xml create mode 100755 res/xml-v14/settings.xml create mode 100755 src/com/xperia64/timidityae/gui/DynamicListView.java create mode 100755 src/com/xperia64/timidityae/gui/StableArrayAdapter.java create mode 100755 src/com/xperia64/timidityae/util/DownloadTask.java diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 6852a27..9169064 100755 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,8 +1,8 @@ NewGlobalRef(env, tmp); pushClazz = (*env)->NewGlobalRef(env,(*env)->FindClass(env, "com/xperia64/timidityae/JNIHandler")); pushBuffit=(*env)->GetStaticMethodID(env, pushClazz, "buffit", "([BI)V"); - flushId=(*env)->GetStaticMethodID(env, pushClazz, "flushIt", "()V"); + flushId=(*env)->GetStaticMethodID(env, pushClazz, "flushTrack", "()V"); buffId=(*env)->GetStaticMethodID(env, pushClazz, "bufferSize", "()I"); - controlId=(*env)->GetStaticMethodID(env, pushClazz, "controlMe", "(I)V"); + controlId=(*env)->GetStaticMethodID(env, pushClazz, "controlCallback", "(I)V"); buffId=(*env)->GetStaticMethodID(env, pushClazz, "bufferSize", "()I"); rateId=(*env)->GetStaticMethodID(env, pushClazz, "getRate", "()I"); - finishId=(*env)->GetStaticMethodID(env, pushClazz, "finishIt", "()V"); - seekInitId=(*env)->GetStaticMethodID(env, pushClazz, "initSeeker", "(I)V"); - updateSeekId=(*env)->GetStaticMethodID(env, pushClazz, "updateSeeker", "(II)V"); + finishId=(*env)->GetStaticMethodID(env, pushClazz, "finishCallback", "()V"); + seekInitId=(*env)->GetStaticMethodID(env, pushClazz, "initSeekBar", "(I)V"); + updateSeekId=(*env)->GetStaticMethodID(env, pushClazz, "updateSeekBar", "(II)V"); pushLyricId=(*env)->GetStaticMethodID(env, pushClazz, "updateLyrics", "([B)V"); updateMaxChanId=(*env)->GetStaticMethodID(env, pushClazz, "updateMaxChannels", "(I)V"); updateProgId=(*env)->GetStaticMethodID(env, pushClazz, "updateProgramInfo", "(II)V"); @@ -360,11 +360,11 @@ Java_com_xperia64_timidityae_JNIHandler_loadSongTimidity(JNIEnv * env, jobject // Don't you just love JNI+threading? // Must be called once to open output. Thank you mac_main for the NULL file list thing - if(!itIsDone) + if(!outputOpen) { setMaxChannels((int)MAX_CHANNELS); (*timidity_play)(0, NULL); - itIsDone=1; + outputOpen=1; } int main_ret; char *filez[1]; @@ -373,7 +373,7 @@ Java_com_xperia64_timidityae_JNIHandler_loadSongTimidity(JNIEnv * env, jobject filez[0]=(char*)(*env)->GetStringUTFChars(env, song, &isCopy); //main_ret = timidity_play_main(1, filez); (*ext_play_list)(1,filez); -(*env)->ReleaseStringUTFChars(env, song, filez[0]); + (*env)->ReleaseStringUTFChars(env, song, filez[0]); finishAE(); //(*theGoodEnv)->DeleteLocalRef(theGoodEnv, pushClazz); diff --git a/jni/timidity/Android.mk b/jni/timidity/Android.mk index 3aa7303..ef96022 100755 --- a/jni/timidity/Android.mk +++ b/jni/timidity/Android.mk @@ -39,7 +39,6 @@ LOCAL_SRC_FILES+= mod.c LOCAL_SRC_FILES+= mod2midi.c LOCAL_SRC_FILES+= modmid_a.c LOCAL_SRC_FILES+= mt19937ar.c -#LOCAL_SRC_FILES+= opensl_io.c LOCAL_SRC_FILES+= optcode.c LOCAL_SRC_FILES+= output.c LOCAL_SRC_FILES+= playmidi.c diff --git a/jni/timidity/opensl_io.c b/jni/timidity/opensl_io.c deleted file mode 100755 index 23189e5..0000000 --- a/jni/timidity/opensl_io.c +++ /dev/null @@ -1,534 +0,0 @@ -/* -opensl_io.c: -Android OpenSL input/output module -Copyright (c) 2012, Victor Lazzarini -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include "opensl_io.h" -#define CONV16BIT 32768 -#define CONVMYFLT (1./32768.) -#include -#include -#include -#include -static void* createThreadLock(void); -static int waitThreadLock(void *lock); -static void notifyThreadLock(void *lock); -static void destroyThreadLock(void *lock); -static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context); -static void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context); -// creates the OpenSL ES audio engine -static SLresult openSLCreateEngine(OPENSL_STREAM *p) -{ - SLresult result; - // create engine - result = slCreateEngine(&(p->engineObject), 0, NULL, 0, NULL, NULL); - if(result != SL_RESULT_SUCCESS) goto engine_end; - - // realize the engine - result = (*p->engineObject)->Realize(p->engineObject, SL_BOOLEAN_FALSE); - if(result != SL_RESULT_SUCCESS) goto engine_end; - - // get the engine interface, which is needed in order to create other objects - result = (*p->engineObject)->GetInterface(p->engineObject, SL_IID_ENGINE, &(p->engineEngine)); - if(result != SL_RESULT_SUCCESS) goto engine_end; - - engine_end: - return result; -} - -// opens the OpenSL ES device for output -static SLresult openSLPlayOpen(OPENSL_STREAM *p) -{ - SLresult result; - SLuint32 sr = p->sr; - SLuint32 channels = p->outchannels; - - if(channels){ - // configure audio source - SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; - - switch(sr){ - - case 8000: - sr = SL_SAMPLINGRATE_8; - break; - case 11025: - sr = SL_SAMPLINGRATE_11_025; - break; - case 16000: - sr = SL_SAMPLINGRATE_16; - break; - case 22050: - sr = SL_SAMPLINGRATE_22_05; - break; - case 24000: - sr = SL_SAMPLINGRATE_24; - break; - case 32000: - sr = SL_SAMPLINGRATE_32; - break; - case 44100: - sr = SL_SAMPLINGRATE_44_1; - break; - case 48000: - sr = SL_SAMPLINGRATE_48; - break; - case 64000: - sr = SL_SAMPLINGRATE_64; - break; - case 88200: - sr = SL_SAMPLINGRATE_88_2; - break; - case 96000: - sr = SL_SAMPLINGRATE_96; - break; - case 192000: - sr = SL_SAMPLINGRATE_192; - break; - default: - return -1; - } - - const SLInterfaceID ids[] = {SL_IID_VOLUME}; - const SLboolean req[] = {SL_BOOLEAN_FALSE}; - result = (*p->engineEngine)->CreateOutputMix(p->engineEngine, &(p->outputMixObject), 1, ids, req); - if(result != SL_RESULT_SUCCESS) goto end_openaudio; - - // realize the output mix - result = (*p->outputMixObject)->Realize(p->outputMixObject, SL_BOOLEAN_FALSE); - - int speakers; - if(channels > 1) - speakers = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - else speakers = SL_SPEAKER_FRONT_CENTER; - SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM,channels, sr, - SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, - speakers, SL_BYTEORDER_LITTLEENDIAN}; - - SLDataSource audioSrc = {&loc_bufq, &format_pcm}; - - // configure audio sink - SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, p->outputMixObject}; - SLDataSink audioSnk = {&loc_outmix, NULL}; - - // create audio player - const SLInterfaceID ids1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean req1[] = {SL_BOOLEAN_TRUE}; - result = (*p->engineEngine)->CreateAudioPlayer(p->engineEngine, &(p->bqPlayerObject), &audioSrc, &audioSnk, - 1, ids1, req1); - if(result != SL_RESULT_SUCCESS) goto end_openaudio; - - // realize the player - result = (*p->bqPlayerObject)->Realize(p->bqPlayerObject, SL_BOOLEAN_FALSE); - if(result != SL_RESULT_SUCCESS) goto end_openaudio; - - // get the play interface - result = (*p->bqPlayerObject)->GetInterface(p->bqPlayerObject, SL_IID_PLAY, &(p->bqPlayerPlay)); - if(result != SL_RESULT_SUCCESS) goto end_openaudio; - - // get the buffer queue interface - result = (*p->bqPlayerObject)->GetInterface(p->bqPlayerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &(p->bqPlayerBufferQueue)); - if(result != SL_RESULT_SUCCESS) goto end_openaudio; - - // register callback on the buffer queue - result = (*p->bqPlayerBufferQueue)->RegisterCallback(p->bqPlayerBufferQueue, bqPlayerCallback, p); - if(result != SL_RESULT_SUCCESS) goto end_openaudio; - - // set the player's state to playing - result = (*p->bqPlayerPlay)->SetPlayState(p->bqPlayerPlay, SL_PLAYSTATE_PLAYING); - - end_openaudio: - return result; - } - return SL_RESULT_SUCCESS; -} - -// Open the OpenSL ES device for input -static SLresult openSLRecOpen(OPENSL_STREAM *p){ - - SLresult result; - SLuint32 sr = p->sr; - SLuint32 channels = p->inchannels; - - if(channels){ - - switch(sr){ - - case 8000: - sr = SL_SAMPLINGRATE_8; - break; - case 11025: - sr = SL_SAMPLINGRATE_11_025; - break; - case 16000: - sr = SL_SAMPLINGRATE_16; - break; - case 22050: - sr = SL_SAMPLINGRATE_22_05; - break; - case 24000: - sr = SL_SAMPLINGRATE_24; - break; - case 32000: - sr = SL_SAMPLINGRATE_32; - break; - case 44100: - sr = SL_SAMPLINGRATE_44_1; - break; - case 48000: - sr = SL_SAMPLINGRATE_48; - break; - case 64000: - sr = SL_SAMPLINGRATE_64; - break; - case 88200: - sr = SL_SAMPLINGRATE_88_2; - break; - case 96000: - sr = SL_SAMPLINGRATE_96; - break; - case 192000: - sr = SL_SAMPLINGRATE_192; - break; - default: - return -1; - } - - // configure audio source - SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, - SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; - SLDataSource audioSrc = {&loc_dev, NULL}; - - // configure audio sink - int speakers; - if(channels > 1) - speakers = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - else speakers = SL_SPEAKER_FRONT_CENTER; - SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; - SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, channels, sr, - SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, - speakers, SL_BYTEORDER_LITTLEENDIAN}; - SLDataSink audioSnk = {&loc_bq, &format_pcm}; - - // create audio recorder - // (requires the RECORD_AUDIO permission) - const SLInterfaceID id[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean req[1] = {SL_BOOLEAN_TRUE}; - result = (*p->engineEngine)->CreateAudioRecorder(p->engineEngine, &(p->recorderObject), &audioSrc, - &audioSnk, 1, id, req); - if (SL_RESULT_SUCCESS != result) goto end_recopen; - - // realize the audio recorder - result = (*p->recorderObject)->Realize(p->recorderObject, SL_BOOLEAN_FALSE); - if (SL_RESULT_SUCCESS != result) goto end_recopen; - - // get the record interface - result = (*p->recorderObject)->GetInterface(p->recorderObject, SL_IID_RECORD, &(p->recorderRecord)); - if (SL_RESULT_SUCCESS != result) goto end_recopen; - - // get the buffer queue interface - result = (*p->recorderObject)->GetInterface(p->recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &(p->recorderBufferQueue)); - if (SL_RESULT_SUCCESS != result) goto end_recopen; - - // register callback on the buffer queue - result = (*p->recorderBufferQueue)->RegisterCallback(p->recorderBufferQueue, bqRecorderCallback, - p); - if (SL_RESULT_SUCCESS != result) goto end_recopen; - result = (*p->recorderRecord)->SetRecordState(p->recorderRecord, SL_RECORDSTATE_RECORDING); - - end_recopen: - return result; - } - else return SL_RESULT_SUCCESS; - - -} - -// close the OpenSL IO and destroy the audio engine -static void openSLDestroyEngine(OPENSL_STREAM *p){ - - // destroy buffer queue audio player object, and invalidate all associated interfaces - if (p->bqPlayerObject != NULL) { - (*p->bqPlayerObject)->Destroy(p->bqPlayerObject); - p->bqPlayerObject = NULL; - p->bqPlayerPlay = NULL; - p->bqPlayerBufferQueue = NULL; - p->bqPlayerEffectSend = NULL; - } - - // destroy audio recorder object, and invalidate all associated interfaces - if (p->recorderObject != NULL) { - (*p->recorderObject)->Destroy(p->recorderObject); - p->recorderObject = NULL; - p->recorderRecord = NULL; - p->recorderBufferQueue = NULL; - } - - // destroy output mix object, and invalidate all associated interfaces - if (p->outputMixObject != NULL) { - (*p->outputMixObject)->Destroy(p->outputMixObject); - p->outputMixObject = NULL; - } - - // destroy engine object, and invalidate all associated interfaces - if (p->engineObject != NULL) { - (*p->engineObject)->Destroy(p->engineObject); - p->engineObject = NULL; - p->engineEngine = NULL; - } - -} - - -// open the android audio device for input and/or output -OPENSL_STREAM *android_OpenAudioDevice(int sr, int inchannels, int outchannels, int bufferframes){ - - OPENSL_STREAM *p; - p = (OPENSL_STREAM *) calloc(sizeof(OPENSL_STREAM),1); - - p->inchannels = inchannels; - p->outchannels = outchannels; - p->sr = sr; - p->inlock = createThreadLock(); - p->outlock = createThreadLock(); - - if((p->outBufSamples = bufferframes*outchannels) != 0) { - if((p->outputBuffer[0] = (short *) calloc(p->outBufSamples, sizeof(short))) == NULL || - (p->outputBuffer[1] = (short *) calloc(p->outBufSamples, sizeof(short))) == NULL) { - android_CloseAudioDevice(p); - return NULL; - } - } - - if((p->inBufSamples = bufferframes*inchannels) != 0){ - if((p->inputBuffer[0] = (short *) calloc(p->inBufSamples, sizeof(short))) == NULL || - (p->inputBuffer[1] = (short *) calloc(p->inBufSamples, sizeof(short))) == NULL){ - android_CloseAudioDevice(p); - return NULL; - } - } - - p->currentInputIndex = 0; - p->currentOutputBuffer = 0; - p->currentInputIndex = p->inBufSamples; - p->currentInputBuffer = 0; - - if(openSLCreateEngine(p) != SL_RESULT_SUCCESS) { - android_CloseAudioDevice(p); - return NULL; - } - - if(openSLRecOpen(p) != SL_RESULT_SUCCESS) { - android_CloseAudioDevice(p); - return NULL; - } - - if(openSLPlayOpen(p) != SL_RESULT_SUCCESS) { - android_CloseAudioDevice(p); - return NULL; - } - - notifyThreadLock(p->outlock); - notifyThreadLock(p->inlock); - - p->time = 0.; - return p; -} - -// close the android audio device -void android_CloseAudioDevice(OPENSL_STREAM *p){ - - if (p == NULL) - return; - - openSLDestroyEngine(p); - - if (p->inlock != NULL) { - notifyThreadLock(p->inlock); - destroyThreadLock(p->inlock); - p->inlock = NULL; - } - - if (p->outlock != NULL) { - notifyThreadLock(p->outlock); - destroyThreadLock(p->outlock); - p->inlock = NULL; - } - - if (p->outputBuffer[0] != NULL) { - free(p->outputBuffer[0]); - p->outputBuffer[0] = NULL; - } - - if (p->outputBuffer[1] != NULL) { - free(p->outputBuffer[1]); - p->outputBuffer[1] = NULL; - } - - if (p->inputBuffer[0] != NULL) { - free(p->inputBuffer[0]); - p->inputBuffer[0] = NULL; - } - - if (p->inputBuffer[1] != NULL) { - free(p->inputBuffer[1]); - p->inputBuffer[1] = NULL; - } - - free(p); -} - -// returns timestamp of the processed stream -double android_GetTimestamp(OPENSL_STREAM *p){ - return p->time; -} -int android_getOutputBuffer(OPENSL_STREAM *p) -{ - return p->currentOutputBuffer; -} - -// this callback handler is called every time a buffer finishes recording -void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context) -{ - OPENSL_STREAM *p = (OPENSL_STREAM *) context; - notifyThreadLock(p->inlock); -} - -// gets a buffer of size samples from the device -int android_AudioIn(OPENSL_STREAM *p,float *buffer,int size){ - short *inBuffer; - int i, bufsamps = p->inBufSamples, index = p->currentInputIndex; - if(p == NULL || bufsamps == 0) return 0; - - inBuffer = p->inputBuffer[p->currentInputBuffer]; - for(i=0; i < size; i++){ - if (index >= bufsamps) { - waitThreadLock(p->inlock); - (*p->recorderBufferQueue)->Enqueue(p->recorderBufferQueue, - inBuffer,bufsamps*sizeof(short)); - p->currentInputBuffer = (p->currentInputBuffer ? 0 : 1); - index = 0; - inBuffer = p->inputBuffer[p->currentInputBuffer]; - } - buffer[i] = (float) inBuffer[index++]*CONVMYFLT; - } - p->currentInputIndex = index; - if(p->outchannels == 0) p->time += (double) size/(p->sr*p->inchannels); - return i; -} - -// this callback handler is called every time a buffer finishes playing -void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) -{ - OPENSL_STREAM *p = (OPENSL_STREAM *) context; - notifyThreadLock(p->outlock); -} - -// puts a buffer of size samples to the device -int android_AudioOut(OPENSL_STREAM *p, char *buffer,int size){ - - short *outBuffer; - int i, bufsamps = p->outBufSamples, index = p->currentOutputIndex; - if(p == NULL || bufsamps == 0) return 0; - outBuffer = p->outputBuffer[p->currentOutputBuffer]; - - for(i=0; i < size; i++){ - outBuffer[index++] = (short) (((int)(char)buffer[i])*CONV16BIT); - if (index >= p->outBufSamples) { - waitThreadLock(p->outlock); - (*p->bqPlayerBufferQueue)->Enqueue(p->bqPlayerBufferQueue, - outBuffer,bufsamps*sizeof(short)); - p->currentOutputBuffer = (p->currentOutputBuffer ? 0 : 1); - index = 0; - outBuffer = p->outputBuffer[p->currentOutputBuffer]; - } - } - p->currentOutputIndex = index; - p->time += (double) size/(p->sr*p->outchannels); - return i; -} - -//---------------------------------------------------------------------- -// thread Locks -// to ensure synchronisation between callbacks and processing code -void* createThreadLock(void) -{ - threadLock *p; - p = (threadLock*) malloc(sizeof(threadLock)); - if (p == NULL) - return NULL; - memset(p, 0, sizeof(threadLock)); - if (pthread_mutex_init(&(p->m), (pthread_mutexattr_t*) NULL) != 0) { - free((void*) p); - return NULL; - } - if (pthread_cond_init(&(p->c), (pthread_condattr_t*) NULL) != 0) { - pthread_mutex_destroy(&(p->m)); - free((void*) p); - return NULL; - } - p->s = (unsigned char) 1; - - return p; -} - -int waitThreadLock(void *lock) -{ - threadLock *p; - int retval = 0; - p = (threadLock*) lock; - pthread_mutex_lock(&(p->m)); - while (!p->s) { - pthread_cond_wait(&(p->c), &(p->m)); - } - p->s = (unsigned char) 0; - pthread_mutex_unlock(&(p->m)); -} - -void notifyThreadLock(void *lock) -{ - threadLock *p; - p = (threadLock*) lock; - pthread_mutex_lock(&(p->m)); - p->s = (unsigned char) 1; - pthread_cond_signal(&(p->c)); - pthread_mutex_unlock(&(p->m)); -} - -void destroyThreadLock(void *lock) -{ - threadLock *p; - p = (threadLock*) lock; - if (p == NULL) - return; - notifyThreadLock(p); - pthread_cond_destroy(&(p->c)); - pthread_mutex_destroy(&(p->m)); - free(p); -} diff --git a/jni/timidity/opensl_io.h b/jni/timidity/opensl_io.h deleted file mode 100755 index bc0ab67..0000000 --- a/jni/timidity/opensl_io.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -opensl_io.c: -Android OpenSL input/output module header -Copyright (c) 2012, Victor Lazzarini -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef OPENSL_IO -#define OPENSL_IO - -#include -#include -#include -#include - -typedef struct threadLock_{ - pthread_mutex_t m; - pthread_cond_t c; - unsigned char s; -} threadLock; - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct opensl_stream { - - // engine interfaces - SLObjectItf engineObject; - SLEngineItf engineEngine; - - // output mix interfaces - SLObjectItf outputMixObject; - - // buffer queue player interfaces - SLObjectItf bqPlayerObject; - SLPlayItf bqPlayerPlay; - SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue; - SLEffectSendItf bqPlayerEffectSend; - - // recorder interfaces - SLObjectItf recorderObject; - SLRecordItf recorderRecord; - SLAndroidSimpleBufferQueueItf recorderBufferQueue; - - // buffer indexes - int currentInputIndex; - int currentOutputIndex; - - // current buffer half (0, 1) - int currentOutputBuffer; - int currentInputBuffer; - - // buffers - short *outputBuffer[2]; - short *inputBuffer[2]; - - // size of buffers - int outBufSamples; - int inBufSamples; - - // locks - void* inlock; - void* outlock; - - double time; - int inchannels; - int outchannels; - int sr; - -} OPENSL_STREAM; - - /* - Open the audio device with a given sampling rate (sr), input and output channels and IO buffer size - in frames. Returns a handle to the OpenSL stream - */ - OPENSL_STREAM* android_OpenAudioDevice(int sr, int inchannels, int outchannels, int bufferframes); - /* - Close the audio device - */ - void android_CloseAudioDevice(OPENSL_STREAM *p); - /* - Read a buffer from the OpenSL stream *p, of size samples. Returns the number of samples read. - */ - int android_AudioIn(OPENSL_STREAM *p, float *buffer,int size); - /* - Write a buffer to the OpenSL stream *p, of size samples. Returns the number of samples written. - */ - int android_AudioOut(OPENSL_STREAM *p, char *buffer,int size); - /* - Get the current IO block time in seconds - */ - double android_GetTimestamp(OPENSL_STREAM *p); - int android_getOutputBuffer(OPENSL_STREAM *p); -#ifdef __cplusplus -}; -#endif - -#endif // #ifndef OPENSL_IO diff --git a/res/drawable-hdpi/ic_menu_moreoverflow.png b/res/drawable-hdpi/ic_menu_moreoverflow.png new file mode 100755 index 0000000000000000000000000000000000000000..33bb5e76b66400027d06ef2ae8d53cb086c80783 GIT binary patch literal 982 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA0wn)(8}a}trX+877l!}s{b%+Ad7K3vk;OpT z1B~5HX4`=T%L*LRfizez!?|}o;XrNoJY5_^A`ZWue%@c$QRMjk{9TuGTcvC=yIi9# zO7*K%z3J^>X`F2SpT)N7(q#3$FGZU>?cW{iR(w$Z;9&Da6BSW`Bp$b@3)9}cd-M5# z-rca6w6NY;Kl0w5tK0wiTW#7so)7kX99=(`ivKB3nZVS%w6>+?X3L(oyGbVeW(*33 zor#ZI_9yUZFOc7#&T7`vWK&$8A<}sDS zYJZN)jXC#v?Xkm7=FDvk-Mk07<;B+?Ocm+LzHp?bhIf&O>?ZFN$)GJ+_1Bia*q$P= z^u-%l<}Qh**uvF;t6v4HEI-+yR90|*&Z2GqtQx$fQ=BfkERxd62y{8pbNG?Tl8LN^ zy>>!V!q_Bz5>HedzIRL}t4ieQ)0H!YmG?M1dC#2qXxol^EB3kS=EaD+ii*@KcV#pb z9;i_gv3#c^fBjxJ1EaV+gLz$u``JUTA`h}xwLeT?%$5@2WVn+quDO(7u<>N{eLVG8yt2%FJ?_wHg;Avh&^0WsqEa`e&eyR$73J0W;ubg0KBk7K+eWkO86K!6`v3FX7QZk(vwS=EcCcQj$K~&eRecQ4*jUbqMLiDh=HHZgRHa&u$xLI@BB2z9EnYtlUVO7B zD`?eo&cn;f*VtHagiZaqchUik(}DW3msO{Kw0U#YQ*Rx^gw4NH-={k!?BDB|_owiU zxZ5S3NB4hUp8mOBdmrOxuE_JT(OQ#$$zHX@HKHUXu_Vl&C_85r;@uiJ^DAvZrIGp!Q0hPpa2R-gt+kPX54X(i=}MX3yqDfvmM f3ZA)%>8U}fi7AzZCsS>JiWody{an^LB{Ts5ll7a- literal 0 HcmV?d00001 diff --git a/res/drawable-mdpi/ic_menu_moreoverflow.png b/res/drawable-mdpi/ic_menu_moreoverflow.png new file mode 100755 index 0000000000000000000000000000000000000000..e4789229d9ad558be2afdcf53baebe120429ecff GIT binary patch literal 854 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE0wix1Z>k4UOiAAEE)4(M`_JqL@;D1TB8!2v z2N=7Z%(epwmK8Xr18D^?ZvQoBE>K&Xr;B5V$MLmOW4%KHMcU@q+MO|M-?bslsO3Q6 zoRcO3O5QJ&PRK7T4gUVOEw81{LBug*d#%H*P}ADOK0$`H>>iJs}+ZSflw6?w}*}RLdBr34(sNyA&keSAe@)=N&$9OG ziM8{##I`p+IkRxR5AO#hjSq9O?;W{xHJ&{OXqLca$;nD*T8um{h@X6*yFc6LMPloG zcXq!cvF2OuB?S7e5AF!$+h(Ah@$pPW_$s~Tz zW3=%>@BY${#u>`qe+ycx&AFHTtWkc_L2cgYIrl$g9B*x1E_H9) zQ`;@>eskVG?@pfJ+xtXl#o^0OUvo%IUDE0rvcmAhGWU0?{5Okzf0-RQweiZ_POiWm zDVLQepX_PAwB0C_apiS~Ig7T%=4oHv9;R&cNW^qc*3Q*E^_wO#E!S9e_ETrdvBD{R z59WVxn{vRrb;4O5f0bRi{*tq&E?N@E*jljR^PRWf@|LGaWfgxHi!{F|UBWOUXxERU zhwd1yJ1M{UPv!b8D_A@0E-;k+UbT9k*ACvRZm!9ES!;jA`@fCfHRnrdjqb*yz$B+y z;u=wsl30>zm0Xkxq!^403=MS+OmvORLJTaej7_bKjdcyotqctKmDlY=(U6;;l9^VC zTSHx)7%NbNB*=!~{Irtt#G+IN$CUh}R0Yr6#Prml)Wnp^!jq{sKt&9mu6{1-oD!M< D;9_=8 literal 0 HcmV?d00001 diff --git a/res/drawable-xhdpi/ic_menu_moreoverflow.png b/res/drawable-xhdpi/ic_menu_moreoverflow.png new file mode 100755 index 0000000000000000000000000000000000000000..2998d659ed5526420da88da214d727deba605279 GIT binary patch literal 1204 zcmeAS@N?(olHy`uVBq!ia0vp^4j|0I0wfs{c7_5;rX+877l!}s{b%+Ad7K3vk;OpT z1B~5HX4`=T%L*LRfwTh{zxwkqZ64|%tZRx>m@zRYRV*-$7e;iUV2 z9)EoEEtit%?bd~SZ#Rk`JSr2nfQw7{@T$yuo-dPQ^-4U>rf4+XT*SXRIrq^5IsWO1 zm6KF=rTj}g-f&5!=j`$V`|9OMTi3Rp*-$foWoYE78bKX~NLkhU+6@aI>=E~w=(d8p zRb-!l$?F$P9@#Zz{(QB$8%uiZrfu26b$qQv$OCnQzHeUXZ}bWb4hM5|D$BF$Otf{I z8KELvl~`%^=dB#y4V$Z-pHC?3^@(a#^gTTxQ_xuVN>=CH#AnqF6G5(ed&ukog9^|^ zfz>&DDerVlEECQ(Ub?V-O3!5$A@A%qnH5ZrGrU`vH@nF&Fr0eoA7sYHE)k@=riN?& zgNFN8*CH5pUneEQ^ z*_JCH@T9JLclqVNW*i;Q>}l{em|^ztg3-*2^7lQz6h1t*u=-7ti}H7#gI>Q*Pi|pI zTWKWwDETW>{?}=w~|?#12p~pjzS@QIe8a zl4_M)lnSI6j0_A7bq!2(jm$y}EUk=9t&ELz4a}_!4EUAT?L^U#o1c=IR*73fU7Z*! xP=h4MhT#0PlJdl&R0hYC{G?O`&)mfH)S%SFl*+=BsWw1G44$rjF6*2UngC|F`vL#} literal 0 HcmV?d00001 diff --git a/res/drawable-xxhdpi/ic_menu_moreoverflow.png b/res/drawable-xxhdpi/ic_menu_moreoverflow.png new file mode 100755 index 0000000000000000000000000000000000000000..c3a13904bfefd17dbbe79b6d0ff512aadf7ff3aa GIT binary patch literal 1985 zcmbVNdsI_(9KXC2w-gl>N2b?-h6%g(Zex!t1I8XQX-I=~q9J3uz!kPT?=Eg&dUg;| z@mUyZgi$JmW|Acc%tuDR?16;}rlAoDY6?z5Ii6$PAy{_IKf339@9%NHpYQkk`999w zln_6EEF+Ks0KiyPtXxB{sc!KdMZY_DTSfH3q7+&xkw~YkIuZk<1|kguRYqL~ronWE z+?7r&0sy?y@gyy!Rlkbr2_r}6*5TNUW*Q9u5m7d?PM?KQU>cTzn>>;}-y?0+jY;Z`0 z%95}j2c=affHH!_z;F&6riTSEC_p#}k1rGoLqRT#z!1!Z5N;SEM0s2khQZ;7O?x8^ z>8M7o9QH+@B+l znZgMZ=(ea!BXTGSn~wA`1*2K5eqz{U8BP?PGRUSgLkI_kj7B%FA#Dq#!Tt{8nc9}5 zTr&n~Fbk1G>gjr<2aSN~+&$lsTak_iT}a||QFPgILZ4&AOq5D4VbfnY2Hb$chzLdy zAs-fUVSxyt>GNgcaIRF&lZ8uTV!}skJPV8P#7e$gAmED>0t8XOVue&F?LM2Zr zh4~{`mB~WsOnPj@FHZX%#)dx^i^@n$M-gNaL1d3~Ktd)#5tdBC49XJ2LA6ego7`u2 zc^B--@HXi0aq*)iC{TTAf|(74`U7gCua~H4CHQ(e>BU; z72SdE?UUB04^M^%Gtm=6(xWj>8@QUDxVtL3G|BeU?{BEH{9l{2Cdin0IeDM)*z75v z1*bM_WgoA6oT7#70=XnhD&?)fNWAnw4A4ULV;&KV93-hFi;nfLLnNC)_x=j&sZ6?W8Az3`j& zmEdvH8(%9N_y>=A%zg@t(m@DPyU5-nb zG&e25Q+wN|(tG#HzI;9tfPBl~PkaH-<4X(AFn_!<<|}4VrGH_7Hx&EgmcINmoLTrL z71R4cMOsI|`CgWJ13P2M1eYwwQGW0SO{L3n36&u$JO&@W?bXgac(ZO(x#zN*N7tgNioq@t6Znw`qKxq*jQ&t_g*ExnQUS?2nHB+jndfT?e#q)vP6UbOLC$~l+I z)zD>dUA8A5ZrtEUCJRsar9wT^zlIeHF8$)OrX;dlIxXVjh0z6g!}U2+<|spxJ=)vy zl+(@^gZAxsT>9w=lGQxdL~be+5~N!f(7&zo*qu`Q5SPxr{NvGs6X&xSP|wxfZ+Whd z`{Vw5?TTwBzXwJ+%A=5%yS9JBKxTC>JU6DPELyVNd1`Lg_5+&ATLv#NG`yADsXE2Da2e?9T;R~5xARV%YPS>kO|7(U19>d-1? z+pXJUS3Rok|2f*LVuQ6|?K=FjrYB`^)~3}0<8No=+FGX- + + + + + \ No newline at end of file diff --git a/res/layout-v14/row_menu.xml b/res/layout-v14/row_menu.xml new file mode 100755 index 0000000..afb24f9 --- /dev/null +++ b/res/layout-v14/row_menu.xml @@ -0,0 +1,29 @@ + + + + + + + + \ No newline at end of file diff --git a/res/layout-v21/music_notification.xml b/res/layout-v21/music_notification.xml index 3930d2b..b65a4ec 100755 --- a/res/layout-v21/music_notification.xml +++ b/res/layout-v21/music_notification.xml @@ -17,9 +17,9 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" - android:singleLine="true" - android:ellipsize="end" android:layout_toEndOf="@id/imagey" + android:ellipsize="end" + android:singleLine="true" android:text="" android:textColor="#000000" /> diff --git a/res/layout-v21/settings_toolbar.xml b/res/layout-v21/settings_toolbar.xml index a15785f..bda76bd 100755 --- a/res/layout-v21/settings_toolbar.xml +++ b/res/layout-v21/settings_toolbar.xml @@ -1,15 +1,12 @@ - - \ No newline at end of file + app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" + app:title="@string/action_settings" /> diff --git a/res/layout/filebrowser.xml b/res/layout/filebrowser.xml index 7bdb8f2..a69fe61 100755 --- a/res/layout/filebrowser.xml +++ b/res/layout/filebrowser.xml @@ -1,46 +1,24 @@ - - - - - - - - - + android:descendantFocusability="blocksDescendants" + android:orientation="vertical" > + + + + + + + + \ No newline at end of file diff --git a/res/layout/fragment_page.xml b/res/layout/fragment_page.xml index c6fae6f..0e365a3 100755 --- a/res/layout/fragment_page.xml +++ b/res/layout/fragment_page.xml @@ -1,5 +1,5 @@ \ No newline at end of file + android:layout_width="match_parent" + android:layout_height="match_parent" + android:gravity="center" /> diff --git a/res/layout/list.xml b/res/layout/list.xml index 92d4486..06a76b9 100755 --- a/res/layout/list.xml +++ b/res/layout/list.xml @@ -1,17 +1,15 @@ - + + + + - - - \ No newline at end of file diff --git a/res/layout/lyrical_fragment.xml b/res/layout/lyrical_fragment.xml index 1e96895..fb1d87e 100755 --- a/res/layout/lyrical_fragment.xml +++ b/res/layout/lyrical_fragment.xml @@ -1,21 +1,20 @@ - + android:layout_height="fill_parent" > - + android:orientation="vertical" > + + + - \ No newline at end of file diff --git a/res/layout/main.xml b/res/layout/main.xml index 8d15792..6d3d1ac 100755 --- a/res/layout/main.xml +++ b/res/layout/main.xml @@ -3,9 +3,10 @@ android:id="@+id/vp_main" android:layout_width="match_parent" android:layout_height="match_parent" > - + + \ No newline at end of file diff --git a/res/layout/midi_options.xml b/res/layout/midi_options.xml index 18790c5..537e1b9 100755 --- a/res/layout/midi_options.xml +++ b/res/layout/midi_options.xml @@ -1,185 +1,181 @@ - + android:focusableInTouchMode="true" + android:padding="3dp" > - + android:orientation="vertical" + android:paddingEnd="5dp" + android:paddingLeft="5dp" + android:paddingRight="5dp" + android:paddingStart="5dp" > + + + + + +