From: kruland2607 Date: Sun, 8 Jan 2012 01:51:02 +0000 (+0000) Subject: Move the android package from the main trunk/src directory to trunk/android/src. X-Git-Tag: upstream/12.03~1^2~188 X-Git-Url: https://git.gag.com/?a=commitdiff_plain;h=7901d5fdebc50a0c1d180ebfc27fff725c232443;p=debian%2Fopenrocket Move the android package from the main trunk/src directory to trunk/android/src. git-svn-id: https://openrocket.svn.sourceforge.net/svnroot/openrocket/trunk@283 180e2498-e6e9-4542-8430-84ac67f01cd8 --- diff --git a/android/src/net/sf/openrocket/android/Application.java b/android/src/net/sf/openrocket/android/Application.java new file mode 100644 index 00000000..6628e5fb --- /dev/null +++ b/android/src/net/sf/openrocket/android/Application.java @@ -0,0 +1,84 @@ +package net.sf.openrocket.android; + +import java.util.Locale; + +import android.preference.PreferenceManager; + +import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; +import net.sf.openrocket.document.OpenRocketDocument; +import net.sf.openrocket.l10n.DebugTranslator; +import net.sf.openrocket.l10n.ResourceBundleTranslator; +import net.sf.openrocket.l10n.Translator; + +public class Application extends android.app.Application { + + private OpenRocketDocument rocketDocument; + + // Big B boolean so I can synchronize on it. + private static Boolean initialized = false; + + public static void initialize() { + synchronized (initialized) { + if ( initialized == true ) { + return; + } + + // Android does not have a default sax parser set. This needs to be defined first. + System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver"); + + net.sf.openrocket.startup.Application.setLogger( new LogHelper() ); + + net.sf.openrocket.startup.Application.setPreferences( new PreferencesAdapter() ); + + ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(false) { + + @Override + protected void loadMotors() { + } + }; + db.startLoading(); + + net.sf.openrocket.startup.Application.setMotorSetDatabase(db); + + Translator t; + t = new ResourceBundleTranslator("l10n.messages"); + if (Locale.getDefault().getLanguage().equals("xx")) { + t = new DebugTranslator(t); + } + + net.sf.openrocket.startup.Application.setBaseTranslator(t); + + initialized = true; + } + } + + public Application() { + initialize(); + } + + /* (non-Javadoc) + * @see android.app.Application#onCreate() + */ + @Override + public void onCreate() { + super.onCreate(); + PreferencesActivity.initializePreferences(this, PreferenceManager.getDefaultSharedPreferences(this)); + } + + /** + * @return the rocketDocument + */ + public OpenRocketDocument getRocketDocument() { + return rocketDocument; + } + + /** + * @param rocketDocument the rocketDocument to set + */ + public void setRocketDocument(OpenRocketDocument rocketDocument) { + this.rocketDocument = rocketDocument; + } + + + +} diff --git a/android/src/net/sf/openrocket/android/LogHelper.java b/android/src/net/sf/openrocket/android/LogHelper.java new file mode 100644 index 00000000..ae10d8b4 --- /dev/null +++ b/android/src/net/sf/openrocket/android/LogHelper.java @@ -0,0 +1,37 @@ +package net.sf.openrocket.android; + +import android.util.Log; +import net.sf.openrocket.logging.LogLevel; +import net.sf.openrocket.logging.LogLine; + + +public class LogHelper extends net.sf.openrocket.logging.LogHelper { + + /* (non-Javadoc) + * @see net.sf.openrocket.logging.LogHelper#log(net.sf.openrocket.logging.LogLine) + */ + @Override + public void log(LogLine line) { + + LogLevel level = line.getLevel(); + + switch ( level ) { + case ERROR: + Log.e("OpenRocket", line.toString()); + break; + case WARN: + Log.w("OpenRocket", line.toString()); + break; + case INFO: + Log.i("OpenRocket", line.toString()); + break; + case DEBUG: + Log.d("OpenRocket", line.toString()); + break; + default: + Log.v("OpenRocket", line.toString()); + } + } + + +} diff --git a/android/src/net/sf/openrocket/android/Main.java b/android/src/net/sf/openrocket/android/Main.java new file mode 100644 index 00000000..347115c6 --- /dev/null +++ b/android/src/net/sf/openrocket/android/Main.java @@ -0,0 +1,81 @@ +package net.sf.openrocket.android; + +import net.sf.openrocket.R; +import net.sf.openrocket.android.motor.MotorHierarchicalBrowser; +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.View; +import android.widget.ImageView; + +public class Main extends Activity { + + private static final int PICK_ORK_FILE_RESULT = 1; + + private static final int STOPSPLASH = 0; + //time in milliseconds + private static final long SPLASHTIME = 3000; + + private ImageView splash; + + //handler for splash screen + private Handler splashHandler = new Handler() { + /* (non-Javadoc) + * @see android.os.Handler#handleMessage(android.os.Message) + */ + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case STOPSPLASH: + //remove SplashScreen from view + splash.setVisibility(View.GONE); + break; + } + super.handleMessage(msg); + } + }; + + /** Called when the activity is first created. */ + @Override + public void onCreate(Bundle icicle) { + super.onCreate(icicle); + setContentView(R.layout.main); + splash = (ImageView) findViewById(R.id.splashscreen); + Message msg = new Message(); + msg.what = STOPSPLASH; + splashHandler.sendMessageDelayed(msg, SPLASHTIME); + } + + /* (non-Javadoc) + * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) + */ + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + switch ( requestCode ) { + case PICK_ORK_FILE_RESULT: + if(resultCode==RESULT_OK){ + Uri file = data.getData(); + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.setData(file); + startActivity(intent); + } + break; + } + super.onActivityResult(requestCode, resultCode, data); + } + + public void pickOrkFiles( View v ) { + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("file/*"); + startActivityForResult(intent,PICK_ORK_FILE_RESULT); + } + + public void browseMotors( View v ) { + Intent i = new Intent(Main.this, MotorHierarchicalBrowser.class); + startActivity(i); + } + +} diff --git a/android/src/net/sf/openrocket/android/PreferencesActivity.java b/android/src/net/sf/openrocket/android/PreferencesActivity.java new file mode 100644 index 00000000..66f4d778 --- /dev/null +++ b/android/src/net/sf/openrocket/android/PreferencesActivity.java @@ -0,0 +1,48 @@ +package net.sf.openrocket.android; + +import net.sf.openrocket.R; +import net.sf.openrocket.unit.UnitGroup; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; + +public class PreferencesActivity extends android.preference.PreferenceActivity +implements SharedPreferences.OnSharedPreferenceChangeListener { + + @Override + protected void onCreate( Bundle savedInstanceState ) { + super.onCreate( savedInstanceState ); + addPreferencesFromResource(R.xml.preferences); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + prefs.registerOnSharedPreferenceChangeListener(this); + } + + /* (non-Javadoc) + * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String) + */ + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + + initializePreferences(getApplication(), PreferenceManager.getDefaultSharedPreferences(this)); + } + + /** + * This method is to be called from Application setup to pull the saved preference + * values into the various datastructures used in OpenRocket. + * This method is located in this class because it is probably best to have as much + * of the code in the same place as possible. + * @param sharedPreferences + */ + public static void initializePreferences( android.app.Application app, SharedPreferences sharedPreferences ) { + + String unitLength = app.getResources().getString(R.string.PreferenceUnitLengthOption); + String len = sharedPreferences.getString(unitLength, "cm"); + UnitGroup.UNITS_LENGTH.setDefaultUnit( len ); + + String unitMass = app.getResources().getString(R.string.PreferenceUnitMassOption); + String mass = sharedPreferences.getString(unitMass, "g"); + UnitGroup.UNITS_MASS.setDefaultUnit( mass ); + + } + +} diff --git a/android/src/net/sf/openrocket/android/PreferencesAdapter.java b/android/src/net/sf/openrocket/android/PreferencesAdapter.java new file mode 100644 index 00000000..086c18c3 --- /dev/null +++ b/android/src/net/sf/openrocket/android/PreferencesAdapter.java @@ -0,0 +1,96 @@ +package net.sf.openrocket.android; + +import java.util.Collections; +import java.util.Set; + +import net.sf.openrocket.material.Material; + +public class PreferencesAdapter extends net.sf.openrocket.startup.Preferences { + + @Override + public boolean getBoolean(String key, boolean defaultValue) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void putBoolean(String key, boolean value) { + // TODO Auto-generated method stub + + } + + @Override + public int getInt(String key, int defaultValue) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void putInt(String key, int value) { + // TODO Auto-generated method stub + + } + + @Override + public double getDouble(String key, double defaultValue) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public void putDouble(String key, double value) { + // TODO Auto-generated method stub + + } + + @Override + public String getString(String key, String defaultValue) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void putString(String key, String value) { + // TODO Auto-generated method stub + + } + + @Override + public String getString(String directory, String key, String defaultValue) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void putString(String directory, String key, String value) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see net.sf.openrocket.startup.Preferences#addUserMaterial(net.sf.openrocket.material.Material) + */ + @Override + public void addUserMaterial(Material m) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see net.sf.openrocket.startup.Preferences#getUserMaterials() + */ + @Override + public Set getUserMaterials() { + return Collections.emptySet(); + } + + /* (non-Javadoc) + * @see net.sf.openrocket.startup.Preferences#removeUserMaterial(net.sf.openrocket.material.Material) + */ + @Override + public void removeUserMaterial(Material m) { + // TODO Auto-generated method stub + + } + +} diff --git a/android/src/net/sf/openrocket/android/db/DbAdapter.java b/android/src/net/sf/openrocket/android/db/DbAdapter.java new file mode 100644 index 00000000..4de12fac --- /dev/null +++ b/android/src/net/sf/openrocket/android/db/DbAdapter.java @@ -0,0 +1,81 @@ +package net.sf.openrocket.android.db; + +import android.content.Context; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +public class DbAdapter { + + private static final String TAG = "DbAdapter"; + private DatabaseHelper mDbHelper; + private SQLiteDatabase mDb; + + private static final String DATABASE_NAME = "rocketflightnotebook"; + private static final int DATABASE_VERSION = 5; + + private final Context mCtx; + + private MotorDao motorDao; + + public MotorDao getMotorDao() { + return motorDao; + } + + private class DatabaseHelper extends SQLiteOpenHelper { + DatabaseHelper(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + @Override + public void onCreate(SQLiteDatabase db) { + executeSQL( db, MotorDao.create()); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + + newVersion + ", which will destroy all old data"); + executeSQL(db, MotorDao.update(oldVersion, newVersion)); + } + + private void executeSQL( SQLiteDatabase db, String[] sqls ) { + for(String s: sqls ) { + db.execSQL(s); + } + } + + } + + /** + * Constructor - takes the context to allow the database to be + * opened/created + * + * @param ctx the Context within which to work + */ + public DbAdapter(Context ctx) { + this.mCtx = ctx; + } + + /** + * Open the database. If it cannot be opened, try to create a new + * instance of the database. If it cannot be created, throw an exception to + * signal the failure + * + * @return this (self reference, allowing this to be chained in an + * initialization call) + * @throws SQLException if the database could be neither opened or created + */ + public DbAdapter open() throws SQLException { + mDbHelper = new DatabaseHelper(mCtx); + mDb = mDbHelper.getWritableDatabase(); + motorDao = new MotorDao(mDb); + return this; + } + + public void close() { + mDbHelper.close(); + } + +} \ No newline at end of file diff --git a/android/src/net/sf/openrocket/android/db/MotorDao.java b/android/src/net/sf/openrocket/android/db/MotorDao.java new file mode 100644 index 00000000..7da2598a --- /dev/null +++ b/android/src/net/sf/openrocket/android/db/MotorDao.java @@ -0,0 +1,270 @@ +package net.sf.openrocket.android.db; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Vector; + +import net.sf.openrocket.android.motor.Motor; +import android.content.ContentValues; +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.util.Log; + +public class MotorDao { + + private static final String TAG = "MotorDao"; + + private SQLiteDatabase mDb; + + private final static String DATABASE_TABLE = "motor"; + private final static String DROP_TABLE = "DROP TABLE IF EXISTS " + DATABASE_TABLE; + private final static String CREATE_TABLE = + "create table "+ DATABASE_TABLE + " ( " + + "_id integer primary key, "+ + "unique_name text unique, "+ + "name text, "+ + "diameter number, "+ + "tot_impulse_ns number, "+ + "avg_thrust_n number, "+ + "max_thrust_n number, "+ + "burn_time_s number, "+ + "length number," + + "prop_mass_g number,"+ + "tot_mass_g number,"+ + "case_info text,"+ + "manufacturer text," + + "impulse_class text," + + "burndata blob"+ + ");"; + + MotorDao( SQLiteDatabase mDb ) { + this.mDb = mDb; + } + + static String[] create() { return new String[] {CREATE_TABLE}; } + + static String[] update( int oldVer, int newVer ) { + return new String[] { DROP_TABLE, CREATE_TABLE }; + } + + public final static String ID = "_id"; + public final static String UNIQUE_NAME = "unique_name"; + public final static String NAME = "name"; + public final static String DIAMETER = "diameter"; + public final static String TOTAL_IMPULSE = "tot_impulse_ns"; + public final static String AVG_THRUST = "avg_thrust_n"; + public final static String MAX_THRUST = "max_thrust_n"; + public final static String BURN_TIME = "burn_time_s"; + public final static String LENGTH = "length"; + public final static String PROP_MASS = "prop_mass_g"; + public final static String TOT_MASS = "tot_mass_g"; + public final static String BURNDATA = "burndata"; + public final static String CASE_INFO = "case_info"; + public final static String MANUFACTURER = "manufacturer"; + public final static String IMPULSE_CLASS = "impulse_class"; + + public long insertOrUpdateMotor(Motor mi) { + ContentValues initialValues = new ContentValues(); + initialValues.put(ID, mi.getMotor_id()); + initialValues.put(NAME, mi.getName()); + initialValues.put(DIAMETER,mi.getDiameter()); + initialValues.put(TOTAL_IMPULSE,mi.getTotalImpulse()); + initialValues.put(AVG_THRUST,mi.getAvgThrust()); + initialValues.put(MAX_THRUST,mi.getMaxThrust()); + initialValues.put(BURN_TIME,mi.getBurnTime()); + initialValues.put(LENGTH, mi.getLength()); + initialValues.put(PROP_MASS, mi.getPropMass()); + initialValues.put(TOT_MASS,mi.getTotMass()); + initialValues.put(CASE_INFO, mi.getCaseInfo()); + initialValues.put(MANUFACTURER,mi.getManufacturer()); + initialValues.put(IMPULSE_CLASS,mi.getImpulseClass()); + initialValues.put(UNIQUE_NAME, mi.getManufacturer()+mi.getName()); + { + // Serialize the Vector of burn data + Vector burndata = mi.getBurndata(); + byte[] serObj = null; + if ( burndata != null ) { + try { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + ObjectOutputStream os = new ObjectOutputStream(b); + os.writeObject(burndata); + os.close(); + serObj = b.toByteArray(); + } catch (Exception ex) { + Log.d(TAG,"unable to serialze burndata"); + } + } + initialValues.put(BURNDATA, serObj); + } + + + Log.d(TAG,"insertOrUpdate Motor"); + long rv = mDb.insertWithOnConflict(DATABASE_TABLE, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE); + return rv; + } + + /** + * Delete the motor and burn data with the given rowId + * + * @param name name of motor to delete + * @return true if deleted, false otherwise + */ + public boolean deleteMotor(Long id) { + + boolean rv = mDb.delete(DATABASE_TABLE, ID + "=" + id, null) > 0; + return rv; + } + + /** + * + * @param groupCol + * @param groupVal + * @return + */ + public Cursor fetchAllInGroups( String groupCol, String groupVal ) { + return mDb.query(DATABASE_TABLE, + /* columns */new String[] { + ID, + NAME, + DIAMETER , + TOTAL_IMPULSE, + AVG_THRUST , + MAX_THRUST , + BURN_TIME , + LENGTH, + PROP_MASS, + TOT_MASS, + CASE_INFO, + IMPULSE_CLASS, + MANUFACTURER + }, + /* selection */groupCol + "=?", + /* selection args*/new String[] {groupVal}, + /* groupby */null, + /* having*/null, + /* orderby*/ NAME ); + + } + + /** + * Fetch the groups based on groupCol + * @param groupCol + * @return + */ + public Cursor fetchGroups( String groupCol ) { + return mDb.query(true, DATABASE_TABLE, + /* columns */new String[] { + groupCol + }, + /* selection */null, + /* selection args*/null, + /* groupby */null, + /* having*/null, + /* orderby*/null, + /* limit*/ null); + + } + + /** + * Return a Cursor over the list of all motors + * + * @return Cursor over all notes + */ + public Cursor fetchAllMotors() { + + return mDb.query(DATABASE_TABLE, + /* columns */new String[] { + ID, + NAME, + DIAMETER , + TOTAL_IMPULSE, + AVG_THRUST , + MAX_THRUST , + BURN_TIME , + LENGTH, + PROP_MASS, + TOT_MASS, + CASE_INFO, + IMPULSE_CLASS, + MANUFACTURER + }, + /* selection */null, + /* selection args*/null, + /* groupby */null, + /* having*/null, + /* orderby*/null); + } + + public Motor fetchMotor(Long id ) throws SQLException { + Cursor mCursor = mDb.query(DATABASE_TABLE, + /* columns */new String[] { + ID, + NAME , + DIAMETER , + TOTAL_IMPULSE , + AVG_THRUST , + MAX_THRUST , + BURN_TIME , + LENGTH, + PROP_MASS, + TOT_MASS, + CASE_INFO, + IMPULSE_CLASS, + MANUFACTURER, + BURNDATA + }, + /* selection */ID + "="+id, + /* selection args*/null, + /* groupby */null, + /* having*/null, + /* orderby*/null); + if ( mCursor == null ) { + return null; + } + try { + if (mCursor.getCount() == 0) { + return null; + } + mCursor.moveToFirst(); + Motor mi = new Motor(); + mi.setMotor_id(mCursor.getLong(mCursor.getColumnIndex(ID))); + mi.setName(mCursor.getString(mCursor.getColumnIndex(NAME))); + mi.setDiameter(mCursor.getLong(mCursor.getColumnIndex(DIAMETER))); + mi.setTotalImpulse(mCursor.getFloat(mCursor.getColumnIndex(TOTAL_IMPULSE))); + mi.setAvgThrust(mCursor.getFloat(mCursor.getColumnIndex(AVG_THRUST))); + mi.setMaxThrust(mCursor.getFloat(mCursor.getColumnIndex(MAX_THRUST))); + mi.setBurnTime(mCursor.getFloat(mCursor.getColumnIndex(BURN_TIME))); + mi.setLength(mCursor.getFloat(mCursor.getColumnIndex(LENGTH))); + mi.setPropMass(mCursor.getDouble(mCursor.getColumnIndex(PROP_MASS))); + mi.setCaseInfo(mCursor.getString(mCursor.getColumnIndex(CASE_INFO))); + mi.setTotMass(mCursor.getDouble(mCursor.getColumnIndex(TOT_MASS))); + mi.setManufacturer(mCursor.getString(mCursor.getColumnIndex(MANUFACTURER))); + mi.setImpulseClass(mCursor.getString(mCursor.getColumnIndex(IMPULSE_CLASS))); + + { + // Deserialize burndata column + byte[] serObj = mCursor.getBlob(mCursor.getColumnIndex(BURNDATA)); + Vector burndata = null; + if (serObj != null ) { + try { + ObjectInputStream is = new ObjectInputStream( new ByteArrayInputStream(serObj)); + burndata = (Vector) is.readObject(); + } + catch (Exception ex) { + Log.d(TAG,"cannot deserialize burndata"); + } + } + mi.setBurndata(burndata); + } + return mi; + } + finally { + mCursor.close(); + } + + } + +} diff --git a/android/src/net/sf/openrocket/android/motor/BurnPlotFragment.java b/android/src/net/sf/openrocket/android/motor/BurnPlotFragment.java new file mode 100644 index 00000000..1a8df463 --- /dev/null +++ b/android/src/net/sf/openrocket/android/motor/BurnPlotFragment.java @@ -0,0 +1,243 @@ +package net.sf.openrocket.android.motor; + +import java.util.Vector; + +import net.sf.openrocket.R; +import android.app.Activity; +import android.graphics.Color; +import android.graphics.PointF; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.View; +import android.view.View.OnTouchListener; +import android.view.ViewGroup; + +import com.androidplot.xy.BoundaryMode; +import com.androidplot.xy.LineAndPointFormatter; +import com.androidplot.xy.LineAndPointRenderer; +import com.androidplot.xy.SimpleXYSeries; +import com.androidplot.xy.XYPlot; +import com.androidplot.xy.YValueMarker; + +public class BurnPlotFragment extends Fragment implements OnTouchListener { + + private final static String TAG = "BurnPlotFragment"; + + private XYPlot mySimpleXYPlot; + private SimpleXYSeries mySeries; + private PointF minXY; + private PointF maxXY; + + private float absMinX; + private float absMaxX; + private float minNoError; + private float maxNoError; + + private ScaleGestureDetector mScaleDetector; + private float mScaleFactor = 1.f; + + public static BurnPlotFragment initializeBurnPlotHelper( Motor motor ) { + BurnPlotFragment h = new BurnPlotFragment(); + + Bundle args = new Bundle(); + args.putSerializable("Motor", motor); + h.setArguments(args); + return h; + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + Log.d(TAG,"onAttach"); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + Log.d(TAG,"onCreate"); + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + Log.d(TAG,"onCreateView"); + View v = inflater.inflate(R.layout.motor_burn, container, false); + mySimpleXYPlot = (XYPlot) v.findViewById(R.id.xyplot); + mySimpleXYPlot.setOnTouchListener(this); + mScaleDetector = new ScaleGestureDetector(v.getContext(), new ScaleListener()); + // Motor motor = getMotor(); + // init(motor); + return v; + } + + void init( Motor motor ) { + + mySimpleXYPlot.setUserDomainOrigin(0); + mySimpleXYPlot.setUserRangeOrigin(0); + mySimpleXYPlot.setRangeLabel("impuse (n)"); + mySimpleXYPlot.setDomainLabel("time (s)"); + mySimpleXYPlot.addMarker(new YValueMarker(motor.getAvgThrust(),"average" )); + mySimpleXYPlot.disableAllMarkup(); + + Vector data = null; + try { + data = motor.getBurndata(); + } catch ( Exception ex ) { + } + if ( data == null || data.size() == 0 ) { + data = new Vector(); + data.add(0.0); + data.add(0.0); + data.add(1.0); + data.add(1.0); + } + Log.d("plot","data = " + data.toString()); + + mySeries = new SimpleXYSeries(data, SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,motor.getName()); + + mySimpleXYPlot.addSeries(mySeries, LineAndPointRenderer.class, + new LineAndPointFormatter(Color.rgb(0, 255, 0), Color.rgb(200, 0, 0), null)); + + //Set of internal variables for keeping track of the boundaries + mySimpleXYPlot.calculateMinMaxVals(); + + mySimpleXYPlot.redraw(); + + minXY=new PointF(mySimpleXYPlot.getCalculatedMinX().floatValue(),mySimpleXYPlot.getCalculatedMinY().floatValue()); + maxXY=new PointF(mySimpleXYPlot.getCalculatedMaxX().floatValue(),mySimpleXYPlot.getCalculatedMaxY().floatValue()); + + absMinX = minXY.x; + absMaxX = maxXY.x; + + minNoError = Math.round(mySeries.getX(1).floatValue() +2); + maxNoError = Math.round(mySeries.getX(mySeries.size() -1).floatValue()) - 2.0f; + } + + private float mPosX; + private float mPosY; + + private float mLastTouchX; + private float mLastTouchY; + + private int mActivePointerId = -1; + + @Override + public boolean onTouch(View arg0, MotionEvent event) { + mScaleDetector.onTouchEvent(event); + + final int action = event.getAction(); + switch ( action & MotionEvent.ACTION_MASK ) { + case MotionEvent.ACTION_DOWN: { + final float x = event.getX(); + final float y = event.getY(); + + mLastTouchX = x; + mLastTouchY = y; + + mActivePointerId = event.getPointerId(0); + break; + } + + case MotionEvent.ACTION_MOVE: { + final int pointerIndex = event.findPointerIndex(mActivePointerId); + final float x = event.getX(pointerIndex); + final float y = event.getY(pointerIndex); + + if (!mScaleDetector.isInProgress()) { + final float dx = x - mLastTouchX; + final float dy = y - mLastTouchY; + + mPosX += dx; + mPosY += dy; + scroll(dx); + // do scroll. + + } + mLastTouchX = x; + mLastTouchY = y; + + break; + } + + case MotionEvent.ACTION_UP: { + mActivePointerId = -1; + break; + } + + case MotionEvent.ACTION_CANCEL: { + mActivePointerId = -1; + break; + } + + case MotionEvent.ACTION_POINTER_UP: { + final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; + final int pointerId = event.getPointerId(pointerIndex); + if (pointerId == mActivePointerId) { + // This was our active pointer going up. choose a new active pointer and adjust accordingly. + final int newPointerIndex = pointerIndex ==0 ? 1:0; + mLastTouchX = event.getX(newPointerIndex); + mLastTouchY = event.getY(newPointerIndex); + mActivePointerId = event.getPointerId(newPointerIndex); + } + break; + } + } + return true; + } + + private void zoom(float scale) { + Log.d(TAG,"zoom by " + scale); + float domainSpan = absMaxX - absMinX; + Log.d(TAG,"domainSpan = " + domainSpan); + float domainMidPoint = absMaxX - domainSpan / 2.0f; + Log.d(TAG,"domainMidPoint = " + domainMidPoint); + float offset = domainSpan / scale; + Log.d(TAG,"offset " + offset); + minXY.x=domainMidPoint- offset; + Log.d(TAG,"min X " + minXY.x); + maxXY.x=domainMidPoint+offset; + Log.d(TAG,"max X " + maxXY.x); + checkBoundaries(); + mySimpleXYPlot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.AUTO); + mySimpleXYPlot.redraw(); + } + + private void scroll(float pan) { + float domainSpan = maxXY.x - minXY.x; + float step = domainSpan / mySimpleXYPlot.getWidth(); + float offset = pan * step; + minXY.x+= offset; + maxXY.x+= offset; + checkBoundaries(); + mySimpleXYPlot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.AUTO); + mySimpleXYPlot.redraw(); + } + + private void checkBoundaries() { + + if ( minXY.x < absMinX) + minXY.x = absMinX; +// else if ( minXY.x > maxNoError ) +// minXY.x = maxNoError; + + if ( maxXY.x > absMaxX) + maxXY.x = absMaxX; +// else if ( maxXY.x < minNoError) +// maxXY.x = minNoError; + } + private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { + @Override + public boolean onScale( ScaleGestureDetector detector ) { + mScaleFactor *= detector.getScaleFactor(); + + mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 5.0f)); + zoom(mScaleFactor); + return true; + } + } +} + diff --git a/android/src/net/sf/openrocket/android/motor/Motor.java b/android/src/net/sf/openrocket/android/motor/Motor.java new file mode 100644 index 00000000..68bd113a --- /dev/null +++ b/android/src/net/sf/openrocket/android/motor/Motor.java @@ -0,0 +1,107 @@ +package net.sf.openrocket.android.motor; + +import java.io.Serializable; +import java.util.Vector; + +public class Motor implements Serializable { + + private Long motor_id; + private String name; + private String impulseClass; + private String manufacturer; + private Long diameter; + private String caseInfo; + private Float avgThrust; + private Float maxThrust; + private Float totalImpulse; + private Float burnTime; + private Float length; + private Double propMass; + private Double totMass; + private Vector burndata; + public Long getMotor_id() { + return motor_id; + } + public void setMotor_id(Long motor_id) { + this.motor_id = motor_id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getImpulseClass() { + return impulseClass; + } + public void setImpulseClass(String impulseClass) { + this.impulseClass = impulseClass; + } + public String getManufacturer() { + return manufacturer; + } + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + public Long getDiameter() { + return diameter; + } + public void setDiameter(Long diameter) { + this.diameter = diameter; + } + public String getCaseInfo() { + return caseInfo; + } + public void setCaseInfo(String caseInfo) { + this.caseInfo = caseInfo; + } + public Float getAvgThrust() { + return avgThrust; + } + public void setAvgThrust(Float avgThrust) { + this.avgThrust = avgThrust; + } + public Float getMaxThrust() { + return maxThrust; + } + public void setMaxThrust(Float maxThrust) { + this.maxThrust = maxThrust; + } + public Float getTotalImpulse() { + return totalImpulse; + } + public void setTotalImpulse(Float totalImpulse) { + this.totalImpulse = totalImpulse; + } + public Float getBurnTime() { + return burnTime; + } + public void setBurnTime(Float burnTime) { + this.burnTime = burnTime; + } + public Float getLength() { + return length; + } + public void setLength(Float length) { + this.length = length; + } + public Double getPropMass() { + return propMass; + } + public void setPropMass(Double propMass) { + this.propMass = propMass; + } + public Double getTotMass() { + return totMass; + } + public void setTotMass(Double totMass) { + this.totMass = totMass; + } + public Vector getBurndata() { + return burndata; + } + public void setBurndata(Vector burndata) { + this.burndata = burndata; + } + +} diff --git a/android/src/net/sf/openrocket/android/motor/MotorDetails.java b/android/src/net/sf/openrocket/android/motor/MotorDetails.java new file mode 100644 index 00000000..19f75487 --- /dev/null +++ b/android/src/net/sf/openrocket/android/motor/MotorDetails.java @@ -0,0 +1,77 @@ +package net.sf.openrocket.android.motor; + +import net.sf.openrocket.R; +import android.content.Intent; +import android.os.Bundle; +import android.support.v4.app.FragmentActivity; +import android.util.Log; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.widget.ImageView; +import android.widget.SlidingDrawer; + +public class MotorDetails extends FragmentActivity +implements SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerOpenListener { + + private final static String TAG = "MotorDetails"; + + private SlidingDrawer slidingDrawer; + private ImageView handle; + + private Motor motor; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Log.d(TAG,"onCreate Bundle = "+ String.valueOf(savedInstanceState)); + setContentView(R.layout.motor_detail); + + Intent i = getIntent(); + motor = (Motor) i.getSerializableExtra("Motor"); + + BurnPlotFragment burnPlot = (BurnPlotFragment) getSupportFragmentManager().findFragmentById(R.id.burnPlotFragment); + burnPlot.init(motor); + + MotorDetailsFragment motorDetails = (MotorDetailsFragment) getSupportFragmentManager().findFragmentById(R.id.motorDetailForm); + motorDetails.init(motor); + + slidingDrawer = (SlidingDrawer) findViewById(R.id.drawer); + + slidingDrawer.setOnDrawerOpenListener(this); + slidingDrawer.setOnDrawerCloseListener(this); + + handle = (ImageView) findViewById(R.id.handle); + + } + + @Override + public void onDrawerOpened() { + handle.setImageResource(R.drawable.arrow_down_float); + } + + @Override + public void onDrawerClosed() { + handle.setImageResource(R.drawable.arrow_up_float); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.motor_details_option_menu, menu); + return true; + } + + @Override + public boolean onMenuItemSelected(int featureId, MenuItem item) { + switch(item.getItemId()) { + case R.id.save: + // Extract form data to Motor. + // Save motor. + return true; + } + return super.onMenuItemSelected(featureId, item); + } + + +} diff --git a/android/src/net/sf/openrocket/android/motor/MotorDetailsFragment.java b/android/src/net/sf/openrocket/android/motor/MotorDetailsFragment.java new file mode 100644 index 00000000..eca5d9c6 --- /dev/null +++ b/android/src/net/sf/openrocket/android/motor/MotorDetailsFragment.java @@ -0,0 +1,43 @@ +package net.sf.openrocket.android.motor; + +import net.sf.openrocket.R; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; + +public class MotorDetailsFragment extends Fragment { + + EditText manuField; + EditText nameField; + EditText caseField; + EditText impulseClassField; + EditText diameterField; + EditText lengthField; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View v = inflater.inflate(R.layout.motor_detail_form, container, false); + manuField = (EditText) v.findViewById(R.id.motorDetailsManufacturer); + nameField = (EditText) v.findViewById(R.id.motorDetailsName); + caseField = (EditText) v.findViewById(R.id.motorDetailsCaseInfo); + impulseClassField = (EditText) v.findViewById(R.id.motorDetailsImpuseClass); + diameterField = (EditText) v.findViewById(R.id.motorDetailsDiameter); + lengthField = (EditText) v.findViewById(R.id.motorDetailsLength); + return v; + } + + public void init( Motor m ) { + manuField.setText( m.getManufacturer()); + nameField.setText( m.getName() ); + caseField.setText( m.getCaseInfo()); + impulseClassField.setText( m.getImpulseClass()); + diameterField.setText( m.getDiameter().toString() ); + lengthField.setText( m.getLength().toString() ); + + } + +} diff --git a/android/src/net/sf/openrocket/android/motor/MotorHierarchicalBrowser.java b/android/src/net/sf/openrocket/android/motor/MotorHierarchicalBrowser.java new file mode 100644 index 00000000..8344083c --- /dev/null +++ b/android/src/net/sf/openrocket/android/motor/MotorHierarchicalBrowser.java @@ -0,0 +1,231 @@ +package net.sf.openrocket.android.motor; + +import net.sf.openrocket.R; +import net.sf.openrocket.android.PreferencesActivity; +import net.sf.openrocket.android.db.DbAdapter; +import net.sf.openrocket.android.db.MotorDao; +import net.sf.openrocket.android.thrustcurve.TCQueryActivity; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.res.Resources; +import android.database.Cursor; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.util.Log; +import android.view.ContextMenu; +import android.view.ContextMenu.ContextMenuInfo; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.CursorTreeAdapter; +import android.widget.ExpandableListView; +import android.widget.SimpleCursorTreeAdapter; + + +public class MotorHierarchicalBrowser +extends PersistentExpandableListActivity +implements SharedPreferences.OnSharedPreferenceChangeListener +{ + private static final String TAG = "MotorHierarchicalBrowser"; + + private static final int ACTIVITY_DOWNLOAD=0; + + private static final int CONTEXTMENU_DELETE = Menu.FIRST+1; + + private String groupColumnPreferenceKey; + private String groupColumn = MotorDao.CASE_INFO; + + private static final String[] groupColumns = new String[] { + MotorDao.CASE_INFO, + MotorDao.DIAMETER, + MotorDao.IMPULSE_CLASS, + MotorDao.MANUFACTURER + }; + + private CursorTreeAdapter mAdapter; + + private DbAdapter mDbHelper; + + public class MotorHierarchicalListAdapter extends SimpleCursorTreeAdapter + { + + // Note that the constructor does not take a Cursor. This is done to avoid querying the + // database on the main thread. + public MotorHierarchicalListAdapter(Context context, Cursor cursor, int groupLayout, + int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom, + int[] childrenTo) { + + super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, + childrenTo); + } + + @Override + protected Cursor getChildrenCursor(Cursor arg0) { + Log.d(TAG,"getChildrenCursor"); + String group = arg0.getString(arg0.getColumnIndex(groupColumn)); + Log.d(TAG," for: "+ groupColumn + " = " + group); + Cursor c = mDbHelper.getMotorDao().fetchAllInGroups(groupColumn,group); + Log.d(TAG," got cursor"); + startManagingCursor(c); + return c; + } + + @Override + public long getGroupId(int groupPosition) { + return groupPosition; + } + + } + + @Override + public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) { + if ( groupColumnPreferenceKey.equals(arg1) ) { + setGroupColumnFromPreferences(arg0); + refreshData(); + } + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mDbHelper = new DbAdapter(this); + mDbHelper.open(); + + Resources resources = this.getResources(); + groupColumnPreferenceKey = resources.getString(R.string.PreferenceMotorBrowserGroupingOption); + SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); + + setGroupColumnFromPreferences(pref); + + pref.registerOnSharedPreferenceChangeListener(this); + + refreshData(); + + registerForContextMenu(getExpandableListView()); + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.motor_browser_option_menu, menu); + return true; + } + + @Override + public boolean onMenuItemSelected(int featureId, MenuItem item) { + Log.d(TAG,"onMenuItemSelected" + item.getItemId()); + switch(item.getItemId()) { + case R.id.download_from_thrustcurve_menu_option: + tcDownload(); + return true; + case R.id.preference_menu_option: + Intent intent = new Intent().setClass(this, PreferencesActivity.class); + this.startActivity(intent); + return true; + } + return super.onMenuItemSelected(featureId, item); + } + + @Override + public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { + Log.d(TAG,"onCreateContextMenu " + menuInfo); + Log.d(TAG, "v.getId() = " + v.getId()); + Log.d(TAG, "motorListView = " + R.id.motorListView); + // if (v.getId() == R.id.motorListView) { + ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; + menu.setHeaderTitle("context menu"); + menu.add(Menu.NONE,CONTEXTMENU_DELETE,CONTEXTMENU_DELETE,"Delete"); + // } + super.onCreateContextMenu(menu, v, menuInfo); + } + + @Override + public boolean onContextItemSelected(MenuItem item) { + ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo(); + long motorId = info.id; + Log.d(TAG,"ContextMenu: " + motorId); + switch(item.getItemId()) { + case CONTEXTMENU_DELETE: + mDbHelper.getMotorDao().deleteMotor(motorId); + refreshData(); + return true; + } + return super.onContextItemSelected(item); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent intent) { + super.onActivityResult(requestCode, resultCode, intent); + refreshData(); + } + + + @Override + public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { + super.onChildClick(parent, v, groupPosition, childPosition, id); + Motor m = mDbHelper.getMotorDao().fetchMotor(id); + //Intent i = new Intent(this, BurnPlotActivity.class); + Intent i = new Intent(this,MotorDetails.class); + i.putExtra("Motor", m); + startActivity(i); + return true; + } + + @Override + protected void onDestroy() { + super.onDestroy(); + + SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); + pref.unregisterOnSharedPreferenceChangeListener(this); + + // Null out the group cursor. This will cause the group cursor and all of the child cursors + // to be closed. + mAdapter.changeCursor(null); + mAdapter = null; + + mDbHelper.close(); + } + + private void tcDownload() { + Intent i = new Intent(this, TCQueryActivity.class); + startActivityForResult(i, ACTIVITY_DOWNLOAD); + } + + private void setGroupColumnFromPreferences( SharedPreferences prefs ) { + String indexStr = prefs.getString(groupColumnPreferenceKey, "1"); + int index; + //Dirty hack, you can't use integer-array in ListPreferences + try { + index = Integer.parseInt(indexStr); + } catch ( Exception e ) { + index = 1; + } + if ( index >= groupColumns.length ) { + index = 1; + } + groupColumn = groupColumns[index]; + + } + private void refreshData() { + if (mAdapter != null ) { + mAdapter.changeCursor(null); + } + Cursor motorCursor = mDbHelper.getMotorDao().fetchGroups(groupColumn); + startManagingCursor(motorCursor); + // Set up our adapter + mAdapter = new MotorHierarchicalListAdapter( + this, + motorCursor, + R.layout.motor_list_group, + R.layout.motor_list_child, + new String[] { groupColumn }, // Name for group layouts + new int[] { R.id.motorGroup }, + new String[] { MotorDao.MANUFACTURER, MotorDao.NAME, MotorDao.TOTAL_IMPULSE }, // Number for child layouts + new int[] { R.id.motorChildManu, R.id.motorChildName, R.id.motorChildImpulse }); + setListAdapter(mAdapter); + } +} diff --git a/android/src/net/sf/openrocket/android/motor/PersistentExpandableListActivity.java b/android/src/net/sf/openrocket/android/motor/PersistentExpandableListActivity.java new file mode 100644 index 00000000..f179374a --- /dev/null +++ b/android/src/net/sf/openrocket/android/motor/PersistentExpandableListActivity.java @@ -0,0 +1,91 @@ +package net.sf.openrocket.android.motor; + +import java.util.ArrayList; +import java.util.List; + +import android.app.ExpandableListActivity; +import android.os.Bundle; +import android.widget.ExpandableListAdapter; +import android.widget.ExpandableListView; + +public class PersistentExpandableListActivity extends ExpandableListActivity { + private long[] expandedIds; + + @Override + protected void onStart() { + super.onStart(); + if (this.expandedIds != null) { + restoreExpandedState(expandedIds); + } + } + + @Override + protected void onStop() { + super.onStop(); + expandedIds = getExpandedIds(); + } + + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + this.expandedIds = getExpandedIds(); + outState.putLongArray("ExpandedIds", this.expandedIds); + } + + @Override + protected void onRestoreInstanceState(Bundle state) { + super.onRestoreInstanceState(state); + long[] expandedIds = state.getLongArray("ExpandedIds"); + if (expandedIds != null) { + restoreExpandedState(expandedIds); + } + } + + private long[] getExpandedIds() { + ExpandableListView list = getExpandableListView(); + ExpandableListAdapter adapter = getExpandableListAdapter(); + if (adapter != null) { + int length = adapter.getGroupCount(); + ArrayList expandedIds = new ArrayList(); + for(int i=0; i < length; i++) { + if(list.isGroupExpanded(i)) { + expandedIds.add(adapter.getGroupId(i)); + } + } + return toLongArray(expandedIds); + } else { + return null; + } + } + + private void restoreExpandedState(long[] expandedIds) { + this.expandedIds = expandedIds; + if (expandedIds != null) { + ExpandableListView list = getExpandableListView(); + ExpandableListAdapter adapter = getExpandableListAdapter(); + if (adapter != null) { + for (int i=0; i list) { + long[] ret = new long[list.size()]; + int i = 0; + for (Long e : list) + ret[i++] = e.longValue(); + return ret; + } +} diff --git a/android/src/net/sf/openrocket/android/rocket/OpenRocketLoaderTask.java b/android/src/net/sf/openrocket/android/rocket/OpenRocketLoaderTask.java new file mode 100644 index 00000000..aef2ace4 --- /dev/null +++ b/android/src/net/sf/openrocket/android/rocket/OpenRocketLoaderTask.java @@ -0,0 +1,34 @@ +package net.sf.openrocket.android.rocket; + +import java.io.File; + +import net.sf.openrocket.document.OpenRocketDocument; +import net.sf.openrocket.file.RocketLoadException; +import net.sf.openrocket.file.openrocket.OpenRocketLoader; +import android.os.AsyncTask; +import android.util.Log; + +public class OpenRocketLoaderTask extends AsyncTask { + + private final static String TAG = "OpenRocketLoaderTask"; + + /* (non-Javadoc) + * @see android.os.AsyncTask#doInBackground(Params[]) + */ + @Override + protected OpenRocketDocument doInBackground(File... arg0) { + Log.d(TAG,"doInBackgroud"); + + OpenRocketLoader rocketLoader = new OpenRocketLoader(); + try { + OpenRocketDocument rocket = rocketLoader.load(arg0[0]); + return rocket; + } + catch( RocketLoadException ex ) { + Log.e(TAG, "doInBackground rocketLaoder.load threw", ex); + } + return null; + + } + +} diff --git a/android/src/net/sf/openrocket/android/rocket/OpenRocketViewer.java b/android/src/net/sf/openrocket/android/rocket/OpenRocketViewer.java new file mode 100644 index 00000000..1037d1b8 --- /dev/null +++ b/android/src/net/sf/openrocket/android/rocket/OpenRocketViewer.java @@ -0,0 +1,270 @@ +package net.sf.openrocket.android.rocket; + + +import java.io.File; + +import net.sf.openrocket.R; +import net.sf.openrocket.android.Application; +import net.sf.openrocket.android.PreferencesActivity; +import net.sf.openrocket.android.motor.MotorHierarchicalBrowser; +import net.sf.openrocket.android.simulation.SimulationViewer; +import net.sf.openrocket.document.OpenRocketDocument; +import net.sf.openrocket.document.Simulation; +import net.sf.openrocket.rocketcomponent.Rocket; +import net.sf.openrocket.rocketcomponent.RocketComponent; +import net.sf.openrocket.rocketcomponent.RocketUtils; +import net.sf.openrocket.unit.Unit; +import net.sf.openrocket.unit.UnitGroup; +import net.sf.openrocket.util.Coordinate; +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.TabHost; +import android.widget.TextView; + +public class OpenRocketViewer extends Activity +implements SharedPreferences.OnSharedPreferenceChangeListener +{ + + private static final String TAG = "OpenRocketViewer"; + + private ProgressDialog progress; + + private ListView componentList; + private ListView simulationList; + + private Application app; + + private final static int PICK_ORK_FILE_RESULT = 1; + + /* (non-Javadoc) + * @see android.app.Activity#onCreate(android.os.Bundle) + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + Log.d(TAG,"In onCreate"); + + app = (Application) this.getApplication(); + + setContentView(R.layout.openrocketviewer); + + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + prefs.registerOnSharedPreferenceChangeListener(this); + + TabHost tabs=(TabHost)findViewById(R.id.openrocketviewerTabHost); + + tabs.setup(); + + TabHost.TabSpec spec=tabs.newTabSpec("tag1"); + + spec.setContent(R.id.openrocketviewerOverview); + spec.setIndicator("Overview"); + tabs.addTab(spec); + + spec=tabs.newTabSpec("tag2"); + spec.setContent(R.id.openrocketviewerComponentList); + spec.setIndicator("Components"); + tabs.addTab(spec); + + spec=tabs.newTabSpec("tag3"); + spec.setContent(R.id.openrocketviewerSimulationList); + spec.setIndicator("Simulations"); + tabs.addTab(spec); + + componentList = (ListView) findViewById(R.id.openrocketviewerComponentList); + simulationList = (ListView) findViewById(R.id.openrocketviewerSimulationList); + + Intent i = getIntent(); + Uri file = i.getData(); + + if ( file == null ) { + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("file/*"); + startActivityForResult(intent,PICK_ORK_FILE_RESULT); + + } else { + loadOrkFile(file); + } + } + + @Override + protected void onDestroy() { + if ( progress != null ) { + if ( progress.isShowing() ) { + progress.dismiss(); + } + progress = null; + } + super.onDestroy(); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // TODO Auto-generated method stub + switch(requestCode){ + case PICK_ORK_FILE_RESULT: + if(resultCode==RESULT_OK){ + Uri file = data.getData(); + loadOrkFile(file); + } + break; + } + } + + private void loadOrkFile( Uri file ) { + Log.d(TAG,"Use ork file: " + file); + String path = file.getPath(); + File orkFile = new File(path); + progress = ProgressDialog.show(this, "Loading file", ""); + + final OpenRocketLoaderTask task = new OpenRocketLoaderTask() { + + /* (non-Javadoc) + * @see android.os.AsyncTask#onPostExecute(java.lang.Object) + */ + @Override + protected void onPostExecute(OpenRocketDocument result) { + super.onPostExecute(result); + app.setRocketDocument( result ); + updateContents(); + } + + }; + + task.execute(orkFile); + + } + + /* (non-Javadoc) + * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String) + */ + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + // just in case the user changed the units, we redraw. + PreferencesActivity.initializePreferences(getApplication(), PreferenceManager.getDefaultSharedPreferences(this)); + updateContents(); + } + + private void updateContents() { + + OpenRocketDocument rocketDocument = app.getRocketDocument(); + Rocket rocket = rocketDocument.getRocket(); + + setTitle(rocket.getName()); + + Unit LengthUnit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); + Unit MassUnit = UnitGroup.UNITS_MASS.getDefaultUnit(); + + Coordinate cg = RocketUtils.getCG(rocket); + double length = RocketUtils.getLength(rocket); + ((TextView) findViewById(R.id.openrocketviewerRocketName)).setText( rocket.getName()); + ((TextView)findViewById(R.id.openrocketviewerDesigner)).setText(rocket.getDesigner()); + ((TextView)findViewById(R.id.openrocketviewerCG)).setText(LengthUnit.toStringUnit(cg.x) ); + ((TextView)findViewById(R.id.openrocketviewerLength)).setText(LengthUnit.toStringUnit(length)); + ((TextView)findViewById(R.id.openrocketviewerMass)).setText(MassUnit.toStringUnit(cg.weight)); + ((TextView)findViewById(R.id.openrocketviewerStageCount)).setText(String.valueOf(rocket.getStageCount())); + ((TextView)findViewById(R.id.openrocketviewerComment)).setText(rocket.getComment()); + + ArrayAdapter sims = new ArrayAdapter(this,android.R.layout.simple_list_item_2,rocketDocument.getSimulations()) { + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View v = convertView; + if ( v == null ) { + LayoutInflater li = getLayoutInflater(); + v = li.inflate(android.R.layout.simple_list_item_2,null); + } + Simulation sim = this.getItem(position); + ((TextView)v.findViewById(android.R.id.text1)).setText( sim.getName() ); + ((TextView)v.findViewById(android.R.id.text2)).setText( "motors: " + sim.getConfiguration().getMotorConfigurationDescription() + " apogee: " + sim.getSimulatedData().getMaxAltitude() + "m time: " + sim.getSimulatedData().getFlightTime() + "s"); + return v; + } + + }; + simulationList.setOnItemClickListener( new OnItemClickListener() { + @Override + public void onItemClick(AdapterView l, View v, int position, long id) { + Intent i = new Intent(OpenRocketViewer.this, SimulationViewer.class); + Log.d(TAG,"onItemClick simulation number " + id ); + i.putExtra("Simulation",(int)id); + startActivityForResult(i, 1/*magic*/); + } + + }); + simulationList.setAdapter(sims); + + ArrayAdapter comps = new ArrayAdapter(this, android.R.layout.simple_list_item_1,rocket.getChildren()) { + + /* (non-Javadoc) + * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup) + */ + @Override + public View getView(int position, View convertView, ViewGroup parent) { + View v = convertView; + if ( v == null ) { + LayoutInflater li = getLayoutInflater(); + v = li.inflate(android.R.layout.simple_list_item_1,null); + } + RocketComponent comp = this.getItem(position); + ((TextView)v.findViewById(android.R.id.text1)).setText( comp.getName() ); + return v; + } + + + }; + componentList.setAdapter(comps); + + if ( progress.isShowing() ) { + progress.dismiss(); + } + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.rocket_viewer_option_menu, menu); + return true; + } + + @Override + public boolean onMenuItemSelected(int featureId, MenuItem item) { + Log.d(TAG,"onMenuItemSelected" + item.getItemId()); + switch(item.getItemId()) { + case R.id.motor_list_menu_option: + startMotorBrowser(); + return true; + case R.id.preference_menu_option: + Intent intent = new Intent().setClass(this, PreferencesActivity.class); + this.startActivity(intent); + return true; + } + return super.onMenuItemSelected(featureId, item); + } + + public void startMotorBrowser() { + Log.d(TAG,"motorBrowserButton clicked"); + Intent i = new Intent(OpenRocketViewer.this, MotorHierarchicalBrowser.class); + startActivity(i); + } + + + +} diff --git a/android/src/net/sf/openrocket/android/simulation/GraphicalActivity.java b/android/src/net/sf/openrocket/android/simulation/GraphicalActivity.java new file mode 100644 index 00000000..8335bd87 --- /dev/null +++ b/android/src/net/sf/openrocket/android/simulation/GraphicalActivity.java @@ -0,0 +1,51 @@ +/** + * Copyright (C) 2009, 2010 SC 4ViewSoft SRL + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.openrocket.android.simulation; + +import org.achartengine.ChartFactory; +import org.achartengine.GraphicalView; +import org.achartengine.chart.AbstractChart; + +import android.app.Activity; +import android.os.Bundle; +import android.view.Window; + +/** + * An activity that encapsulates a graphical view of the chart. + */ +public class GraphicalActivity extends Activity { + /** The encapsulated graphical view. */ + private GraphicalView mView; + /** The chart to be drawn. */ + private AbstractChart mChart; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + Bundle extras = getIntent().getExtras(); + mChart = (AbstractChart) extras.getSerializable(ChartFactory.CHART); + mView = new GraphicalView(this, mChart); + String title = extras.getString(ChartFactory.TITLE); + if (title == null) { + requestWindowFeature(Window.FEATURE_NO_TITLE); + } else if (title.length() > 0) { + setTitle(title); + } + setContentView(mView); + } + +} \ No newline at end of file diff --git a/android/src/net/sf/openrocket/android/simulation/SimulationChart.java b/android/src/net/sf/openrocket/android/simulation/SimulationChart.java new file mode 100644 index 00000000..20bab823 --- /dev/null +++ b/android/src/net/sf/openrocket/android/simulation/SimulationChart.java @@ -0,0 +1,231 @@ +/** + * Copyright (C) 2009, 2010 SC 4ViewSoft SRL + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.openrocket.android.simulation; + +import java.util.List; + +import net.sf.openrocket.simulation.FlightDataBranch; +import net.sf.openrocket.simulation.FlightDataType; +import net.sf.openrocket.simulation.FlightEvent; + +import org.achartengine.ChartFactory; +import org.achartengine.chart.LineChart; +import org.achartengine.chart.PointStyle; +import org.achartengine.chart.XYChart; +import org.achartengine.model.XYMultipleSeriesDataset; +import org.achartengine.model.XYSeries; +import org.achartengine.renderer.XYMultipleSeriesRenderer; +import org.achartengine.renderer.XYSeriesRenderer; + +import android.content.Context; +import android.content.Intent; +import android.graphics.Color; +import android.graphics.Paint.Align; +import android.util.Log; + +/** + * Multiple temperature demo chart. + */ +public class SimulationChart { + + private final static String TAG = "SimulationChart"; + + private FlightDataBranch flightDataBranch; + private FlightDataType series1; + private FlightDataType series2; + private final FlightDataType time = FlightDataType.TYPE_TIME; + private List flightEvents; + + // Define 4 different colors and point styles to use for the series. + // For now only 2 series are supported though. + private final static int[] colors = new int[] { Color.BLUE, Color.YELLOW, Color.GREEN, Color.RED }; + private final static PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND, + PointStyle.TRIANGLE, PointStyle.SQUARE }; + + /** + * @param flightDataBranch the flightDataBranch to set + */ + public void setFlightDataBranch(FlightDataBranch flightDataBranch) { + this.flightDataBranch = flightDataBranch; + } + + /** + * @param series1 the series1 to set + */ + public void setSeries1(FlightDataType series1) { + this.series1 = series1; + } + + /** + * @param series2 the series2 to set + */ + public void setSeries2(FlightDataType series2) { + this.series2 = series2; + } + + /** + * @param flightEvents the flightEvents to set + */ + public void setFlightEvents(List flightEvents) { + this.flightEvents = flightEvents; + } + + private static String formatFlightDataTypeAxisLabel( FlightDataType fdt ) { + return fdt.getName() + " (" + fdt.getUnitGroup().getDefaultUnit().toString() + ")"; + } + + /** + * Executes the chart demo. + * + * @param context the context + * @return the built intent + */ + public Intent execute(Context context) { + + /* + * TODO - + * Figure out why you can pan all over the place even where there are no visible points. + */ + int seriesCount = 2; + // if the same series is selected twice, only plot it once. + if ( series1 == series2 ) { + seriesCount = 1; + } + + XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(seriesCount); + + renderer.setAxisTitleTextSize(16); + renderer.setChartTitleTextSize(20); + renderer.setLabelsTextSize(15); + renderer.setLegendTextSize(15); + renderer.setPointSize(5f); + renderer.setXLabels(10); + renderer.setYLabels(10); + renderer.setShowGrid(true); + renderer.setZoomButtonsVisible(true); + renderer.setChartTitle("Simulation"); + + renderer.setMargins(new int[] { 50, 30, 0, 20 }); + { + for (int i = 0; i < seriesCount; i++) { + XYSeriesRenderer r = new XYSeriesRenderer(); + r.setColor(colors[i]); + r.setPointStyle(styles[i]); + r.setFillPoints(true); + renderer.addSeriesRenderer(r); + // setting the YAximMin to 0 locks the origins. + renderer.setYAxisMin(0.0, i); + } + } + + renderer.setXTitle(formatFlightDataTypeAxisLabel(time)); + renderer.setXLabelsAlign(Align.RIGHT); + + renderer.setYTitle(formatFlightDataTypeAxisLabel(series1),0); + renderer.setYLabelsAlign(Align.RIGHT,0); + + if ( seriesCount > 1 ) { + renderer.setYTitle(formatFlightDataTypeAxisLabel(series2), 1); + renderer.setYAxisAlign(Align.RIGHT, 1); + renderer.setYLabelsAlign(Align.LEFT, 1); + } + + renderer.setAxesColor(Color.LTGRAY); + renderer.setLabelsColor(Color.LTGRAY); + + XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); + + List timevalues = flightDataBranch.get(time); + List series1values = flightDataBranch.get(series1); + + // compute the axis limits using timevalues and series1values. + double xmin = 0; + double ymin = 0; + renderer.setXAxisMin(xmin); + renderer.setYAxisMin(ymin); + + double ymax = computeMaxValueWithPadding( series1values ); + double xmax = Math.ceil( timevalues.get( timevalues.size()-1)); + + Log.d(TAG,"ymax = " + ymax); + renderer.setXAxisMax(xmax); + renderer.setYAxisMax(ymax); + + // These configurations don't really work well just now. + //renderer.setPanLimits(new double[] { xmin, xmax, ymin, ymax }); + //renderer.setZoomLimits(new double[] { xmin, xmax, ymin, ymax }); + + // Add first series + addXYSeries(dataset, series1.getName(), timevalues, series1values, 0); + + if ( seriesCount > 1 ) { + // Add second series + addXYSeries(dataset, series2.getName(), timevalues, flightDataBranch.get(series2), 1); + } + Intent intent = getLineChartIntent(context, dataset, renderer,"Simulation"); + return intent; + } + + private static void addXYSeries(XYMultipleSeriesDataset dataset, String titles, List xValues, List yValues, int scale) { + XYSeries series = new XYSeries(titles, scale); + int datasize = xValues.size(); + for( int i = 0; i list ) { + double max = list.get(0); + for( double v : list ) { + if ( v > max ) { + max = v; + } + } + if ( max <= 0 ) return 1.0; + + // Do something stupid. + // return: + // 10 if max <= 10 + // next 10 if 10 < max < 1000 + // next 100 if 1000 < max < 10,000 + // next 1000 if max >= 10,000 + double numdigits = Math.floor(Math.log10(max)); + + if ( numdigits <= 1.0 ) { + return 10.0; + } else if ( numdigits <= 3.0 ) { + return 10.0 * ( Math.ceil( max/10.0)); + } else if ( numdigits <= 4.0 ) { + return 100.0 * ( Math.ceil( max/ 100.0) ); + } else { + return 1000.0 * ( Math.ceil( max / 1000.0 )); + } + + } + +} diff --git a/android/src/net/sf/openrocket/android/simulation/SimulationViewer.java b/android/src/net/sf/openrocket/android/simulation/SimulationViewer.java new file mode 100644 index 00000000..3746cb5f --- /dev/null +++ b/android/src/net/sf/openrocket/android/simulation/SimulationViewer.java @@ -0,0 +1,142 @@ +package net.sf.openrocket.android.simulation; + +import java.util.ArrayList; +import java.util.List; + +import net.sf.openrocket.R; +import net.sf.openrocket.android.Application; +import net.sf.openrocket.document.Simulation; +import net.sf.openrocket.simulation.FlightDataBranch; +import net.sf.openrocket.simulation.FlightDataType; +import net.sf.openrocket.simulation.FlightEvent; +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.util.Log; +import android.util.SparseBooleanArray; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.ListView; +import android.widget.Spinner; +import android.widget.TabHost; +import android.widget.TextView; + +public class SimulationViewer extends Activity { + + private final static String TAG = "SimulationViewer"; + + private ListView eventList; + private Spinner series1Spinner; + private Spinner series2Spinner; + + private Simulation sim; + private FlightDataBranch data; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Log.d(TAG,"onCreate Bundle = "+ String.valueOf(savedInstanceState)); + setContentView(R.layout.simulation_detail); + + Intent i = getIntent(); + int simnumber = i.getIntExtra("Simulation", 0); + sim = ((Application)this.getApplication()).getRocketDocument().getSimulation(simnumber); + data = sim.getSimulatedData().getBranch(0); + + TabHost tabs=(TabHost)findViewById(R.id.simulationConfigurationForm); + + tabs.setup(); + + TabHost.TabSpec spec=tabs.newTabSpec("tag1"); + + spec.setContent(R.id.simulationEventsList); + spec.setIndicator("Events"); + tabs.addTab(spec); + + spec=tabs.newTabSpec("tag2"); + spec.setContent(R.id.simulationSeriesSelection); + spec.setIndicator("Series"); + tabs.addTab(spec); + + eventList = (ListView) findViewById(R.id.simulationEventsList); + + // Initialize the eventList + ArrayAdapter events = new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,data.getEvents()) { + + @Override + public View getView(int position, View convertView, + ViewGroup parent) { + View v = convertView; + if ( v == null ) { + LayoutInflater li = getLayoutInflater(); + v = li.inflate(android.R.layout.simple_list_item_multiple_choice,null); + } + FlightEvent event = this.getItem(position); + ((TextView)v.findViewById(android.R.id.text1)).setText( event.getType().toString() + " " + event.getTime() + " (s)" ); + return v; + } + + }; + eventList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); + eventList.setAdapter(events); + + series1Spinner = (Spinner) findViewById(R.id.simulationSeries1); + series2Spinner = (Spinner) findViewById(R.id.simulationSeries2); + + List selectableSeries = new ArrayList(); + for( FlightDataType fdt : data.getTypes() ) { + if ( fdt == FlightDataType.TYPE_TIME ) { + + } else { + selectableSeries.add(fdt); + } + } + ArrayAdapter serieses = new ArrayAdapter(this,android.R.layout.simple_spinner_item,selectableSeries) { + + @Override + public View getView(int position, View convertView, + ViewGroup parent) { + View v = convertView; + if ( v == null ) { + LayoutInflater li = getLayoutInflater(); + v = li.inflate(android.R.layout.simple_spinner_item,null); + } + FlightDataType fdt = this.getItem(position); + ((TextView)v.findViewById(android.R.id.text1)).setText( fdt.toString() ); + return v; + } + + }; + series1Spinner.setAdapter(serieses); + series2Spinner.setAdapter(serieses); + + } + + public void draw( View v ) { + List eventsToShow = new ArrayList(); + { + SparseBooleanArray eventsSelected = eventList.getCheckedItemPositions(); + List flightEvents = data.getEvents(); + for( int i=0; i< flightEvents.size(); i++ ) { + if ( eventsSelected.get(i) ) { + eventsToShow.add(flightEvents.get(i) ); + } + } + } + FlightDataType series1 = (FlightDataType) series1Spinner.getSelectedItem(); + Log.d(TAG,"sereis1 = " + series1.toString()); + FlightDataType series2 = (FlightDataType) series2Spinner.getSelectedItem(); + Log.d(TAG,"series2 = " + series2.toString()); + + SimulationChart chart = new SimulationChart(); + chart.setFlightDataBranch(data); + chart.setSeries1(series1); + chart.setSeries2(series2); + chart.setFlightEvents(eventsToShow); + + startActivity(chart.execute(this)); + } + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/Base64Decoder.java b/android/src/net/sf/openrocket/android/thrustcurve/Base64Decoder.java new file mode 100644 index 00000000..e172edc3 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/Base64Decoder.java @@ -0,0 +1,122 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; + +public abstract class Base64Decoder { + + private static final String BASE64_CHARS = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + private static final char PAD_CHAR = '='; + + private final static short[] _charToBits = new short[128]; + + static { + + for (int i = 0; i < _charToBits.length; i++) + _charToBits[i] = -1; + + for (int i = 0; i < BASE64_CHARS.length(); i++) + _charToBits[BASE64_CHARS.charAt(i)] = (byte) i; + _charToBits[PAD_CHAR] = 0; + + } + + /** + * Decode the specified Base64 string and write binary data + * to the given stream. + * @param str Base64 encoded string + * @param w output stream + */ + public static String decodeData(String str) throws IOException + { + StringReader r; + int c1; + + if (str == null || str.length() < 1) + return null; + + r = new StringReader(str); + + StringWriter w = new StringWriter(); + + // spin through the input string + c1 = readToNonSpace(r); + while (c1 > 0) + { + int c2, c3, c4; + int p1, p2, p3, p4; + int pad, n; + + pad = 0; + + c2 = readToNonSpace(r); + c3 = readToNonSpace(r); + c4 = readToNonSpace(r); + if (c4 < 0) + throw new IllegalArgumentException("Encoded string ends prematurely."); + + p1 = charToBits(c1); + p2 = charToBits(c2); + + if (c3 == PAD_CHAR) + { + p3 = 0; + pad++; + } + else + p3 = charToBits(c3); + + if (c4 == PAD_CHAR) + { + p4 = 0; + pad++; + } + else + p4 = charToBits(c4); + + if (p1 < 0 || p2 < 0 || p3 < 0 || p4 < 0) + throw new IllegalArgumentException("Encoded string contains invalid characters."); + + n = (p1 << 18) | (p2 << 12) | (p3 << 6) | p4; + + w.write((byte) ((n & 0xFF0000) >> 16)); + if (pad < 2) + w.write((byte) ((n & 0x00FF00) >> 8)); + if (pad < 1) + w.write((byte) (n & 0x0000FF)); + + c1 = readToNonSpace(r); + if (c1 > 0 && pad > 0) + throw new IllegalArgumentException("Extra characters found after padding."); + } + + return w.toString(); + } + + + private static int readToNonSpace(Reader r) + throws IOException + { + int c; + + c = r.read(); + while (c >= 0 && Character.isWhitespace(c)) + c = r.read(); + + return c; + } + + private static int charToBits(int c) + { + // use it to look up the value + if (c < 0 || c >= _charToBits.length) + return -1; + else + return _charToBits[c]; + } + + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/DownloadRequest.java b/android/src/net/sf/openrocket/android/thrustcurve/DownloadRequest.java new file mode 100644 index 00000000..98d22c13 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/DownloadRequest.java @@ -0,0 +1,43 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.util.ArrayList; + +class DownloadRequest { + + private ArrayList motorIds = new ArrayList(); + + private String format = null; + + public void add( Integer motorId ) { + this.motorIds.add(motorId); + } + + public void setFormat( String format ) { + this.format = format; + } + + @Override + public String toString() { + StringBuilder w = new StringBuilder(); + + w.append("\n"); + w.append("\n"); + + if ( format != null ) { + w.append(" ").append(format).append("\n"); + } + + w.append(" \n"); + for( Integer i : motorIds ) { + w.append(" ").append(i).append("\n"); + } + w.append(" \n"); + w.append("\n"); + return w.toString(); + } + + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/DownloadResponse.java b/android/src/net/sf/openrocket/android/thrustcurve/DownloadResponse.java new file mode 100644 index 00000000..84e15916 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/DownloadResponse.java @@ -0,0 +1,37 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.util.HashMap; +import java.util.Map; + + +public class DownloadResponse { + + private Map data = new HashMap(); + + private String error = null; + + public void add( MotorBurnFile mbd ) { + MotorBurnFile currentData = data.get(mbd.getMotorId()); + if ( currentData == null || currentData.getDatapoints().size() < mbd.getDatapoints().size() ) { + data.put(mbd.getMotorId(),mbd); + } + } + + public MotorBurnFile getData(Integer motor_id) { + return data.get(motor_id); + } + + public void setError(String error) { + this.error = error; + } + + public String getError() { + return error; + } + + @Override + public String toString() { + return "DownloadResponse [error=" + error + ", data=" + data + "]"; + } + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/DownloadResponseParser.java b/android/src/net/sf/openrocket/android/thrustcurve/DownloadResponseParser.java new file mode 100644 index 00000000..7e24e7eb --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/DownloadResponseParser.java @@ -0,0 +1,122 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.io.InputStream; + +import org.xml.sax.Attributes; + +import android.sax.Element; +import android.sax.EndElementListener; +import android.sax.EndTextElementListener; +import android.sax.RootElement; +import android.sax.StartElementListener; +import android.util.Log; +import android.util.Xml; + +public class DownloadResponseParser { + + private static final String TAG = "DownloadResponseParser"; + + private static final String thrustcurveURI = "http://www.thrustcurve.org/2009/DownloadResponse"; + + private static final String root_tag = "download-response"; + private static final String results_tag = "results"; + private static final String result_tag = "result"; + private static final String motor_id_tag = "motor-id"; + private static final String simfile_id_tag = "simfile-id"; + private static final String format_tag = "format"; + private static final String source_tag = "source"; + private static final String license_tag = "license"; + private static final String data_tag = "data"; + private static final String error_tag = "error"; + + public static DownloadResponse parse( InputStream in ) { + + final DownloadResponse ret = new DownloadResponse(); + final MotorBurnFile currentMotor = new MotorBurnFile(); + + // Have a place to put the data string and format. + // We hold on to these here, then push them into the currentMotor + // only if it a supported filetype + final StringHolder current_format = new StringHolder(); + final StringHolder current_data = new StringHolder(); + + RootElement rootEl = new RootElement(thrustcurveURI, root_tag); + /* + rootEl.setStartElementListener( + new StartElementListener() { + public void start(Attributes arg0) { + Log.d(TAG,"Start Element error"); + ret.setError("IsError"); + } + } + ); + */ + Element resultsEl = rootEl.getChild( thrustcurveURI, results_tag); + Element resultEl = resultsEl.getChild( thrustcurveURI, result_tag); + resultEl.setStartElementListener( + new StartElementListener() { + @Override + public void start(Attributes arg0) { + Log.d(TAG,"Start Element result"); + currentMotor.init(); + } + } + ); + + resultEl.setEndElementListener( + new EndElementListener() { + @Override + public void end() { + if ( SupportedFileTypes.isSupportedFileType(current_format.s) ) { + currentMotor.setFiletype(current_format.s); + String s = null; + try { + s = Base64Decoder.decodeData(current_data.s); + } catch ( Exception ex ) { + Log.d(TAG,"base64: " + ex.getMessage()); + } + currentMotor.decodeFile( s ); + } + ret.add((MotorBurnFile)currentMotor.clone()); + } + } + ); + + resultEl.getChild(thrustcurveURI,motor_id_tag).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setMotor_id(Integer.parseInt(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,format_tag).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + current_format.s = arg0; + } + } + ); + resultEl.getChild(thrustcurveURI,data_tag).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + current_data.s = arg0; + } + } + ); + try { + Xml.parse(in, Xml.Encoding.UTF_8, rootEl.getContentHandler()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return ret; + } + + private static class StringHolder { + public String s; + } + +} \ No newline at end of file diff --git a/android/src/net/sf/openrocket/android/thrustcurve/MotorBurnFile.java b/android/src/net/sf/openrocket/android/thrustcurve/MotorBurnFile.java new file mode 100644 index 00000000..58f7bb3e --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/MotorBurnFile.java @@ -0,0 +1,89 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.util.Vector; + +public class MotorBurnFile { + + private Integer motor_id; + private String filetype; + private Float length; + private String delays; + private Double propWeightG; + private Double totWeightG; + private Vector datapoints = new Vector(); + + public void init() { + this.motor_id = null; + this.filetype = null; + this.length = null; + this.delays = null; + this.propWeightG = null; + this.totWeightG = null; + this.datapoints = new Vector(); + } + + @Override + public MotorBurnFile clone() { + MotorBurnFile clone = new MotorBurnFile(); + clone.motor_id = this.motor_id; + clone.filetype = this.filetype; + clone.length = this.length; + clone.delays = this.delays; + clone.propWeightG = this.propWeightG; + clone.totWeightG = this.totWeightG; + clone.datapoints = this.datapoints; + return clone; + } + + public void decodeFile(String data){ + if (SupportedFileTypes.RASP_FORMAT.equals(filetype)) { + RaspBurnFile.parse(this,data); + } else if (SupportedFileTypes.ROCKSIM_FORMAT.equals(filetype) ){ + RSEBurnFile.parse(this,data); + } + } + + public Integer getMotorId() { + return motor_id; + } + public String getFileType() { + return filetype; + } + public Float getLength() { + return length; + } + public String getDelays() { + return delays; + } + public Double getPropWeightG() { + return propWeightG; + } + public Double getTotWeightG() { + return totWeightG; + } + public Vector getDatapoints() { + return datapoints; + } + + void setMotor_id(Integer motor_id) { + this.motor_id = motor_id; + } + void setFiletype(String filetype ) { + this.filetype = filetype; + } + void setLength(Float length) { + this.length = length; + } + void setDelays(String delays) { + this.delays = delays; + } + void setPropWeightG(Double propWeightG) { + this.propWeightG = propWeightG; + } + void setTotWeightG(Double totWeightG) { + this.totWeightG = totWeightG; + } + void setDatapoints(Vector datapoints) { + this.datapoints = datapoints; + } +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/RSEBurnFile.java b/android/src/net/sf/openrocket/android/thrustcurve/RSEBurnFile.java new file mode 100644 index 00000000..0c937571 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/RSEBurnFile.java @@ -0,0 +1,131 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Vector; + +import org.xml.sax.Attributes; + +import android.sax.Element; +import android.sax.RootElement; +import android.sax.StartElementListener; +import android.util.Log; +import android.util.Xml; + +class RSEBurnFile extends MotorBurnFile { + + private final static String TAG = "RSEBurnFile"; + + static void parse( MotorBurnFile that, String filecontents ) { + + parse(that, new ByteArrayInputStream(filecontents.getBytes()) ); + } + + private final static String root_tag = "engine-database"; + private final static String engine_list_tag = "engine-list"; + private final static String engine_tag = "engine"; + + private final static String delays_attr = "delays"; + private final static String len_attr = "len"; + private final static String propwgt_attr = "propWt"; + private final static String totwgt_attr = "initWt"; + + private final static String data_tag = "data"; + private final static String eng_data_tag = "eng-data"; + + private final static String time_attr="t"; + private final static String force_attr="f"; + + static void parse( final MotorBurnFile that, InputStream in ) { + + RootElement rootEl = new RootElement(root_tag); + Element engineEl = rootEl.getChild(engine_list_tag).getChild(engine_tag); + + final Vector datapoints = new Vector(); + + Log.d(TAG,"parsing start"); + + engineEl.setStartElementListener( + new StartElementListener() { + @Override + public void start(Attributes arg0) { + Log.d(TAG,"start engineEl"); + that.setPropWeightG(Double.parseDouble(arg0.getValue(propwgt_attr))); + that.setTotWeightG(Double.parseDouble(arg0.getValue(totwgt_attr))); + that.setLength(Float.parseFloat(arg0.getValue(len_attr))); + that.setDelays(arg0.getValue(delays_attr)); + Log.d(TAG, "me is now " + that.toString()); + } + } + ); + + Element datapointEl = engineEl.getChild(data_tag).getChild(eng_data_tag); + datapointEl.setStartElementListener( + new StartElementListener() { + @Override + public void start(Attributes attributes) { + Double x = Double.parseDouble(attributes.getValue(time_attr)); + Double y = Double.parseDouble(attributes.getValue(force_attr)); + Log.d(TAG, "add data point " + x + "," + y); + datapoints.add(x); + datapoints.add(y); + } + } + ); + + try { + Xml.parse(in, Xml.Encoding.UTF_8, rootEl.getContentHandler()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + that.setDatapoints(datapoints); + } +} +// +// +// +// +// Apogee C4 RASP.ENG file made from NAR published data +// File produced September 4, 2000 +// The total impulse, peak thrust, average thrust and burn time are +// the same as the averaged static test data on the NAR web site in +// the certification file. The curve drawn with these data points is as +// close to the certification curve as can be with such a limited +// number of points (32) allowed with wRASP up to v1.6. +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// diff --git a/android/src/net/sf/openrocket/android/thrustcurve/RaspBurnFile.java b/android/src/net/sf/openrocket/android/thrustcurve/RaspBurnFile.java new file mode 100644 index 00000000..2c2e834e --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/RaspBurnFile.java @@ -0,0 +1,85 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.StringReader; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import android.util.Log; + + +class RaspBurnFile{ + + private final static String TAG = "RaspBurnFile"; + + private final static int HEADER = 0; + private final static int DATA = 1; + private final static Pattern headerPattern = Pattern.compile("(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)"); + private final static Pattern dataPattern = Pattern.compile("(\\S*)\\s+(\\S*)"); + + static void parse( MotorBurnFile that, String filecontents ) { + + int state = HEADER; + + LineNumberReader reader = new LineNumberReader( new StringReader(filecontents)); + + Vector datapoints = new Vector(); + + String line; + Matcher m; + try { + while ( (line = reader.readLine()) != null ) { + line = line.trim(); + Log.d("RASP",line); + if ( line.startsWith(";")) { + continue; + } + switch (state) { + + case HEADER: + Log.d("RASP","header"); + m = headerPattern.matcher(line); + if ( m.matches() ) { + Log.d("RASP","header matches"); + + /*motorName = m.group(1);*/ + /*diameter = Integer.decode(m.group(2));*/ + that.setLength(Float.parseFloat(m.group(3)) ); + String delays = m.group(4); + if ( delays != null ) { + delays = delays.replace("-", ","); + that.setDelays(delays); + } + that.setPropWeightG(Double.parseDouble(m.group(5))*1000.0); + that.setTotWeightG(Double.parseDouble(m.group(6))*1000.0); + /*manufacturer = m.group(7);*/ + + } + state = DATA; + break; + + case DATA: + Log.d("RASP","data"); + m = dataPattern.matcher(line); + if ( m.matches() ) { + Log.d("RASP","data matches"); + Double x = Double.parseDouble(m.group(1)); + Double y = Double.parseDouble(m.group(2)); + Log.d("RASP","data matches ("+x+","+y+")"); + datapoints.add(x); + datapoints.add(y); + } + break; + } + that.setDatapoints(datapoints); + } + } catch (IOException ex ) { + Log.d(TAG,"Unable to parse Rasp file: " + ex); + } + + } + + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/SearchRequest.java b/android/src/net/sf/openrocket/android/thrustcurve/SearchRequest.java new file mode 100644 index 00000000..681c049f --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/SearchRequest.java @@ -0,0 +1,117 @@ +package net.sf.openrocket.android.thrustcurve; + +public class SearchRequest { + + private String manufacturer; + private String designation; + private String brand_name; + + private String common_name; + private String impulse_class; + private Integer diameter; + + /* + public enum Type { + "SU"; + "reload"; + "hybrid" + }; + */ + private String type; + + public void setManufacturer(String manufacturer) { + this.manufacturer = null; + if ( manufacturer != null ) { + manufacturer = manufacturer.trim(); + if ( ! "".equals(manufacturer) ) { + this.manufacturer = manufacturer; + } + } + } + + public void setDesignation(String designation) { + this.designation = designation; + } + + public void setBrand_name(String brand_name) { + this.brand_name = brand_name; + } + + public void setCommon_name(String common_name) { + if ( common_name == null ) { + this.common_name = null; + return; + } + this.common_name = common_name.trim(); + if ( "".equals(this.common_name)) { + this.common_name = null; + } + } + + public void setImpulse_class(String impulse_class) { + this.impulse_class = null; + if ( impulse_class != null ) { + this.impulse_class = impulse_class.trim(); + if ( "".equals(impulse_class) ) { + this.impulse_class = null; + } + } + } + + public void setDiameter(Integer diameter) { + this.diameter = diameter; + } + + public void setDiameter(String diameter) { + this.diameter = null; + if ( diameter == null ) { + return; + } + try { + this.diameter = Integer.decode(diameter); + } catch ( NumberFormatException ex ) { + this.diameter = null; + } + } + + public void setType(String type) { + this.type = type; + } + + @Override + public String toString() { + StringBuilder w = new StringBuilder(); + + w.append("\n"); + w.append("\n"); + + if ( manufacturer != null ) { + w.append(" ").append(manufacturer).append("\n"); + } + if ( designation != null ) { + w.append(" ").append(designation).append("\n"); + } + if ( brand_name != null ) { + w.append(" ").append(brand_name).append("\n"); + } + if ( common_name != null ) { + w.append(" ").append(common_name).append("\n"); + } + if ( impulse_class != null ) { + w.append(" ").append(impulse_class).append("\n"); + } + if ( diameter != null ) { + w.append(" ").append(diameter).append("\n"); + } + if ( type != null ) { + w.append(" ").append(type).append("\n"); + } + w.append("*"); + w.append("50"); + w.append("\n"); + return w.toString(); + } +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/SearchResponse.java b/android/src/net/sf/openrocket/android/thrustcurve/SearchResponse.java new file mode 100644 index 00000000..48cbfefb --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/SearchResponse.java @@ -0,0 +1,45 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.util.ArrayList; +import java.util.List; + + +public class SearchResponse { + + private List results = new ArrayList(); + + private int matches; + + private String error; + + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } + + public int getMatches() { + return matches; + } + + public void setMatches(int matches) { + this.matches = matches; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + @Override + public String toString() { + return "SearchResult [results=" + results + ", matches=" + matches + + ", error=" + error + "]"; + } + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/SearchResponseParser.java b/android/src/net/sf/openrocket/android/thrustcurve/SearchResponseParser.java new file mode 100644 index 00000000..be532435 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/SearchResponseParser.java @@ -0,0 +1,281 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.io.InputStream; + +import org.xml.sax.Attributes; + +import android.sax.Element; +import android.sax.EndElementListener; +import android.sax.EndTextElementListener; +import android.sax.RootElement; +import android.sax.StartElementListener; +import android.util.Xml; + +public class SearchResponseParser { + + private static final String thrustcurveURI = "http://www.thrustcurve.org/2008/SearchResponse"; + /* + * XML Tags in SearchResult xsd + */ + private static final String root_tag = "search-response"; + private static final String criteria = "criteria"; + private static final String criterion = "criterion"; + private static final String name = "name"; + private static final String value = "value"; + private static final String matches = "matches"; + private static final String results = "results"; + private static final String result = "result"; + + private static final String motor_id = "motor-id"; + private static final String manufacturer = "manufacturer"; + private static final String manufacturer_abbr = "manufacturer-abbrev"; + private static final String designation = "designation"; + private static final String brand_name = "brand-name"; + private static final String common_name = "common-name"; + private static final String impulse_class = "impulse-class"; + private static final String diameter = "diameter"; + private static final String length = "length"; + private static final String type = "type"; + private static final String cert_org = "cert-org"; + private static final String avg_thrust_n = "avg-thrust-n"; + private static final String max_thrust_n = "max-thrust-n"; + private static final String tot_impulse_ns = "tot-impulse-ns"; + private static final String burn_time_s = "burn-time-s"; + private static final String data_files = "data-files"; + private static final String info_url = "info-url"; + private static final String total_weight_g = "total-weight-g"; + private static final String prop_weight_g = "prop-weight-g"; + private static final String delays = "delays"; + private static final String case_info = "case-info"; + private static final String prop_info = "prop-info"; + private static final String updated_on = "updated-on"; + + public static SearchResponse parse( InputStream in ) { + + final SearchResponse ret = new SearchResponse(); + final TCMotor currentMotor = new TCMotor(); + + RootElement rootEl = new RootElement(thrustcurveURI, root_tag); + Element criteriaEl = rootEl.getChild( thrustcurveURI, criteria); + + criteriaEl.getChild(thrustcurveURI,matches).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + ret.setMatches(Integer.parseInt(arg0)); + } + } + ); + Element resultsEl = rootEl.getChild(thrustcurveURI,results); + Element resultEl = resultsEl.getChild(thrustcurveURI,result); + + resultEl.setStartElementListener( + new StartElementListener() { + @Override + public void start(Attributes arg0) { + currentMotor.init(); + } + } + ); + + resultEl.setEndElementListener( + new EndElementListener() { + @Override + public void end() { + ret.getResults().add((TCMotor)currentMotor.clone()); + } + } + ); + + resultEl.getChild(thrustcurveURI,motor_id).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setMotor_id(Integer.parseInt(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,manufacturer).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + if ( arg0 != null ) { + currentMotor.setManufacturer(arg0); + } + } + } + ); + resultEl.getChild(thrustcurveURI,manufacturer_abbr).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + if ( arg0 != null ) { + currentMotor.setManufacturer_abbr(arg0); + } + } + } + ); + resultEl.getChild(thrustcurveURI,designation).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setDesignation(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,brand_name).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setBrand_name(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,common_name).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setCommon_name(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,impulse_class).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setImpulse_class(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,diameter).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setDiameter(Float.parseFloat(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,length).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setLength(Float.parseFloat(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,type).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setType(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,cert_org).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setCert_org(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,avg_thrust_n).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setAvg_thrust_n(Float.parseFloat(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,max_thrust_n).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setMax_thrust_n(Float.parseFloat(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,tot_impulse_ns).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setTot_impulse_ns(Float.parseFloat(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,burn_time_s).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setBurn_time_s(Float.parseFloat(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,data_files).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setData_files(Integer.parseInt(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,info_url).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setInfo_url(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,total_weight_g).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setTot_mass_g(Double.parseDouble(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,prop_weight_g).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setProp_mass_g(Double.parseDouble(arg0)); + } + } + ); + resultEl.getChild(thrustcurveURI,delays).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setDelays(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,case_info).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setCase_info(arg0); + } + } + ); + resultEl.getChild(thrustcurveURI,prop_info).setEndTextElementListener( + new EndTextElementListener() { + @Override + public void end(String arg0) { + currentMotor.setProp_info(arg0); + } + } + ); + + + try { + Xml.parse(in, Xml.Encoding.UTF_8, rootEl.getContentHandler()); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return ret; + } + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/SupportedFileTypes.java b/android/src/net/sf/openrocket/android/thrustcurve/SupportedFileTypes.java new file mode 100644 index 00000000..c1230164 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/SupportedFileTypes.java @@ -0,0 +1,11 @@ +package net.sf.openrocket.android.thrustcurve; + +public abstract class SupportedFileTypes { + + public final static String ROCKSIM_FORMAT = "RockSim"; + public final static String RASP_FORMAT = "RASP"; + + public static boolean isSupportedFileType( String arg0 ) { + return (ROCKSIM_FORMAT.equals(arg0) || RASP_FORMAT.equals(arg0)); + } +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/TCMotor.java b/android/src/net/sf/openrocket/android/thrustcurve/TCMotor.java new file mode 100644 index 00000000..477029ec --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/TCMotor.java @@ -0,0 +1,299 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.util.Date; +import java.util.Vector; + +public class TCMotor implements Cloneable { + + private Integer motor_id; + private String manufacturer; + private String manufacturer_abbr; + private String designation; + private String brand_name; + private String common_name; + private String impulse_class; + private Float diameter; + private Float length; + private String type; + private String cert_org; + private Float avg_thrust_n; + private Float max_thrust_n; + private Float tot_impulse_ns; + private Float burn_time_s; + private Integer data_files; + private String info_url; + private Double tot_mass_g; + private Double prop_mass_g; + private String delays; + private String case_info; + private String prop_info; + private Date updated_on; + private Vector burndata; + + public void init() { + motor_id = null; + manufacturer = null; + manufacturer_abbr = null; + designation = null; + brand_name = null; + common_name = null; + impulse_class = null; + diameter = null; + length = null; + type = null; + cert_org = null; + avg_thrust_n = null; + max_thrust_n = null; + tot_impulse_ns = null; + burn_time_s = null; + data_files = null; + info_url = null; + tot_mass_g = null; + prop_mass_g = null; + delays = null; + case_info = null; + prop_info = null; + updated_on = null; + burndata = null; + } + + @Override + public TCMotor clone() { + TCMotor clone = new TCMotor(); + clone.motor_id = this.motor_id; + clone.manufacturer = this.manufacturer; + clone.manufacturer_abbr = this.manufacturer_abbr; + clone.designation = this.designation; + clone.brand_name = this.brand_name; + clone.common_name = this.common_name; + clone.impulse_class = this.impulse_class; + clone.diameter = this.diameter; + clone.length = this.length; + clone.type = this.type; + clone.cert_org = this.cert_org; + clone.avg_thrust_n = this.avg_thrust_n; + clone.max_thrust_n = this.max_thrust_n; + clone.tot_impulse_ns = this.tot_impulse_ns; + clone.burn_time_s = this.burn_time_s; + clone.data_files = this.data_files; + clone.info_url = this.info_url; + clone.tot_mass_g = this.tot_mass_g; + clone.prop_mass_g = this.prop_mass_g; + clone.delays = this.delays; + clone.case_info = this.case_info; + clone.prop_info = this.prop_info; + clone.updated_on = this.updated_on; + clone.burndata = this.burndata; + return clone; + } + + public Integer getMotor_id() { + return motor_id; + } + + public void setMotor_id(Integer motor_id) { + this.motor_id = motor_id; + } + + public String getManufacturer() { + return manufacturer; + } + + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + + public String getManufacturer_abbr() { + return manufacturer_abbr; + } + + public void setManufacturer_abbr(String manufacturer_abbr) { + this.manufacturer_abbr = manufacturer_abbr; + } + + public String getDesignation() { + return designation; + } + + public void setDesignation(String designation) { + this.designation = designation; + } + + public String getBrand_name() { + return brand_name; + } + + public void setBrand_name(String brand_name) { + this.brand_name = brand_name; + } + + public String getCommon_name() { + return common_name; + } + + public void setCommon_name(String common_name) { + this.common_name = common_name; + } + + public String getImpulse_class() { + return impulse_class; + } + + public void setImpulse_class(String impulse_class) { + this.impulse_class = impulse_class; + } + + public Float getDiameter() { + return diameter; + } + + public void setDiameter(Float diameter) { + this.diameter = diameter; + } + + public Float getLength() { + return length; + } + + public void setLength(Float length) { + this.length = length; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCert_org() { + return cert_org; + } + + public void setCert_org(String cert_org) { + this.cert_org = cert_org; + } + + public Float getAvg_thrust_n() { + return avg_thrust_n; + } + + public void setAvg_thrust_n(Float avg_thrust_n) { + this.avg_thrust_n = avg_thrust_n; + } + + public Float getMax_thrust_n() { + return max_thrust_n; + } + + public void setMax_thrust_n(Float max_thrust_n) { + this.max_thrust_n = max_thrust_n; + } + + public Float getTot_impulse_ns() { + return tot_impulse_ns; + } + + public void setTot_impulse_ns(Float tot_impulse_ns) { + this.tot_impulse_ns = tot_impulse_ns; + } + + public Float getBurn_time_s() { + return burn_time_s; + } + + public void setBurn_time_s(Float burn_time_s) { + this.burn_time_s = burn_time_s; + } + + public Integer getData_files() { + return data_files; + } + + public void setData_files(Integer data_files) { + this.data_files = data_files; + } + + public String getInfo_url() { + return info_url; + } + + public void setInfo_url(String info_url) { + this.info_url = info_url; + } + + public Double getTot_mass_g() { + return tot_mass_g; + } + + public void setTot_mass_g(Double tot_mass_g) { + this.tot_mass_g = tot_mass_g; + } + + public Double getProp_mass_g() { + return prop_mass_g; + } + + public void setProp_mass_g(Double prop_mass_g) { + this.prop_mass_g = prop_mass_g; + } + + public String getDelays() { + return delays; + } + + public void setDelays(String delays) { + this.delays = delays; + } + + public String getCase_info() { + return case_info; + } + + public void setCase_info(String case_info) { + this.case_info = case_info; + } + + public String getProp_info() { + return prop_info; + } + + public void setProp_info(String prop_info) { + this.prop_info = prop_info; + } + + public Date getUpdated_on() { + return updated_on; + } + + public void setUpdated_on(Date updated_on) { + this.updated_on = updated_on; + } + + public Vector getBurndata() { + return burndata; + } + + public void setBurndata(Vector burndata) { + this.burndata = burndata; + } + + @Override + public String toString() { + return "TCMotor [motor_id=" + motor_id + ", manufacturer=" + + manufacturer + ", manufacturer_abbr=" + manufacturer_abbr + + ", designation=" + designation + ", brand_name=" + brand_name + + ", common_name=" + common_name + ", impulse_class=" + + impulse_class + ", diameter=" + diameter + ", length=" + + length + ", type=" + type + ", cert_org=" + cert_org + + ", avg_thrust_n=" + avg_thrust_n + ", max_thrust_n=" + + max_thrust_n + ", tot_impulse_ns=" + tot_impulse_ns + + ", burn_time_s=" + burn_time_s + ", data_files=" + data_files + + ", info_url=" + info_url + ", tot_mass_g=" + tot_mass_g + + ", prop_mass_g=" + prop_mass_g + ", delays=" + delays + + ", case_info=" + case_info + ", prop_info=" + prop_info + + ", updated_on=" + updated_on + "]"; + } + +} diff --git a/android/src/net/sf/openrocket/android/thrustcurve/TCQueryActivity.java b/android/src/net/sf/openrocket/android/thrustcurve/TCQueryActivity.java new file mode 100644 index 00000000..8f5a7835 --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/TCQueryActivity.java @@ -0,0 +1,256 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.util.Vector; + +import net.sf.openrocket.R; +import net.sf.openrocket.android.db.DbAdapter; +import net.sf.openrocket.android.motor.Motor; +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import android.os.Bundle; +import android.os.Handler; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Spinner; + +public class TCQueryActivity extends Activity { + + private static final String TAG = "ThrustCurveQueryActivity"; + + private DbAdapter mDbHelper; + + private ProgressDialog progress; + private Thread downloadThread; + private Handler handler; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.tcqueryform); + + mDbHelper = new DbAdapter(this); + mDbHelper.open(); + + final Spinner manufacturerField = (Spinner) findViewById(R.id.TCMotorSearchFormManufacturerField); + final Spinner impulseField = (Spinner) findViewById(R.id.TCMotorSearchFormImpulseField); + final Spinner diameterField = (Spinner) findViewById(R.id.TCMotorSearchFormDiameterField); + final EditText commonNameField = (EditText) findViewById(R.id.TCMotorSearchFormCommonNameField); + + Button submitButton = (Button) findViewById(R.id.TCMotorSearchFromSubmitButton); + submitButton.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick( View v ) { + Log.d(TAG,"submit button clicked"); + + String commonName = commonNameField.getText().toString(); + + SearchRequest r = new SearchRequest(); + if ( manufacturerField.getSelectedItemPosition() != 0) { + String m = (String) manufacturerField.getSelectedItem(); + Log.d(TAG,"manufacturer = " + m); + r.setManufacturer(m); + } + if ( impulseField.getSelectedItemPosition() != 0 ) { + String impulse = (String) impulseField.getSelectedItem(); + Log.d(TAG,"impulse = " + impulse); + r.setImpulse_class(impulse); + } + if ( diameterField.getSelectedItemPosition() != 0 ) { + String diameter = (String)diameterField.getSelectedItem(); + Log.d(TAG,"diameter = " + diameter); + r.setDiameter(diameter); + } + r.setCommon_name(commonName); + + Downloader d = new Downloader(r); + + handler = new Handler(); + progress = ProgressDialog.show(TCQueryActivity.this, null, ""); + + downloadThread = new Thread( d ); + downloadThread.start(); + } + } + ); + } + + @Override + public Object onRetainNonConfigurationInstance() { + return downloadThread; + } + + @Override + protected void onDestroy() { + mDbHelper.close(); + if ( progress != null ) { + if ( progress.isShowing() ) { + progress.dismiss(); + } + progress = null; + } + super.onDestroy(); + } + + private class UpdateMessage implements Runnable { + private String newMessage; + UpdateMessage( String message ) { + this.newMessage = message; + } + @Override + public void run() { + progress.setMessage(newMessage); + } + } + + private class Dismiss implements Runnable { + @Override + public void run() { + progress.dismiss(); + TCQueryActivity.this.finish(); + } + } + + private class Error implements Runnable { + private String newMessage; + Error( String message ) { + this.newMessage = message; + } + @Override + public void run() { + progress.dismiss(); + final AlertDialog dialog = new AlertDialog.Builder(TCQueryActivity.this).create(); + dialog.setMessage(newMessage); + dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"Dismiss", new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface arg0, int arg1) { + dialog.dismiss(); + } + + }); + dialog.show(); + } + } + private class Downloader implements Runnable { + + SearchRequest request; + + Downloader( SearchRequest request ) { + this.request = request; + } + + @Override + public void run() { + try { + handler.post( new UpdateMessage("Quering Thrustcurve")); + SearchResponse res = new ThrustCurveAPI().doSearch(request); + + int total = res.getResults().size(); + int count = 1; + for( TCMotor mi : res.getResults() ) { + handler.post(new UpdateMessage("Downloading details " + count + " of " + total)); + count++; + if ( mi.getData_files() == null || mi.getData_files().intValue() == 0 ) { + continue; + } + + MotorBurnFile b = new ThrustCurveAPI().downloadData(mi.getMotor_id()); + + if ( b != null ) { + if ( b.getLength() != null ) { + mi.setLength( b.getLength() ); + } + if ( b.getPropWeightG() != null ) { + mi.setProp_mass_g(b.getPropWeightG()); + } + if ( b.getTotWeightG() != null ) { + mi.setTot_mass_g(b.getTotWeightG()); + } + if ( b.getDelays() != null ) { + mi.setDelays(b.getDelays()); + } + mi.setBurndata(b.getDatapoints()); + } + Log.d(TAG, mi.toString()); + + // convert to Motors. One per delay. + Motor m = new Motor(); + // Base name of motor. + String name = mi.getCommon_name() + "-"; + + m.setManufacturer(mi.getManufacturer_abbr()); + // Convert impulse class. ThrustCurve puts mmx, 1/4a and 1/2a as A. + m.setImpulseClass(mi.getImpulse_class()); + if ( "a".equalsIgnoreCase(mi.getImpulse_class())) { + if( mi.getCommon_name().startsWith("1/2A") ) { + m.setImpulseClass("1/2A"); + } else if (mi.getCommon_name().startsWith("1/4A") ) { + m.setImpulseClass("1/4A"); + } else if (mi.getCommon_name().startsWith("Micro") ) { + m.setImpulseClass("1/8A"); + } + } + m.setAvgThrust(mi.getAvg_thrust_n()); + m.setBurndata(mi.getBurndata()); + m.setBurnTime(mi.getBurn_time_s()); + m.setDiameter(mi.getDiameter() == null ? null : mi.getDiameter().longValue()); + m.setLength(mi.getLength()); + m.setMaxThrust(mi.getMax_thrust_n()); + m.setPropMass(mi.getProp_mass_g()); + m.setTotalImpulse(mi.getTot_impulse_ns()); + m.setTotMass(mi.getTot_mass_g()); + // Convert Case Info. + if ( mi.getCase_info() == null + || "single use".equalsIgnoreCase(mi.getCase_info()) + || "single-use".equalsIgnoreCase(mi.getCase_info())) { + m.setCaseInfo(mi.getType()+ " " + mi.getDiameter() + "x" + mi.getLength()); + } else { + m.setCaseInfo(mi.getCase_info()); + } + + Vector delays = new Vector(); + { + String delaysString = mi.getDelays(); + if ( delaysString != null ) { + delaysString = delaysString.trim(); + } + + if ( delaysString == null || "".equals(delaysString)) { + delays.add(""); + } else { + String[] delayString = delaysString.split(","); + for( String d : delayString ) { + delays.add( d.trim() ); + } + } + } + + for( String d: delays ) { + if ( "100".equals(d) ) { + m.setName(name + "P"); + } else { + m.setName(name + d); + } + mDbHelper.getMotorDao().insertOrUpdateMotor(m); + } + } + if ( total < res.getMatches() ) { + handler.post( new Error( total + " motors downloaded, " + res.getMatches() + " matched. Try restricting the query more.") ); + } else { + handler.post( new Dismiss()); + } + } + catch( Exception ex){ + Log.d(TAG,ex.toString()); + handler.post( new Error(ex.toString()) ); + } + + } + } +} + diff --git a/android/src/net/sf/openrocket/android/thrustcurve/ThrustCurveAPI.java b/android/src/net/sf/openrocket/android/thrustcurve/ThrustCurveAPI.java new file mode 100644 index 00000000..9241228b --- /dev/null +++ b/android/src/net/sf/openrocket/android/thrustcurve/ThrustCurveAPI.java @@ -0,0 +1,80 @@ +package net.sf.openrocket.android.thrustcurve; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +import android.util.Log; + + +public class ThrustCurveAPI { + + private final static String TAG = "ThrustCurveAPI"; + + private String url_base = "http://www.thrustcurve.org/servlets/"; + + public SearchResponse doSearch( SearchRequest request ) throws MalformedURLException, IOException { + + String requestString = request.toString(); + + Log.d(TAG, "doSearch: " + requestString); + URL url = new URL(url_base + "search"); + + OutputStream stream; + + URLConnection conn = url.openConnection(); + conn.setConnectTimeout(2000); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + + stream = conn.getOutputStream(); + + stream.write(requestString.getBytes()); + + InputStream is = conn.getInputStream(); + + SearchResponse result = SearchResponseParser.parse(is); + Log.d(TAG,result.toString()); + + return result; + } + + public MotorBurnFile downloadData( Integer motor_id ) throws MalformedURLException, IOException { + + if ( motor_id == null ) { + return null; + } + DownloadRequest dr = new DownloadRequest(); + dr.add(motor_id); + + String requestString = dr.toString(); + + Log.d(TAG, "downloadData: " + requestString); + URL url = new URL(url_base + "download"); + + OutputStream stream; + + URLConnection conn = url.openConnection(); + conn.setDoInput(true); + conn.setDoOutput(true); + conn.setUseCaches(false); + + stream = conn.getOutputStream(); + + stream.write(requestString.getBytes()); + + InputStream is = conn.getInputStream(); + + DownloadResponse downloadResponse = DownloadResponseParser.parse(is); + Log.d(TAG,downloadResponse.toString()); + + MotorBurnFile mbf = downloadResponse.getData(motor_id); + + return mbf; + + } +} diff --git a/src/net/sf/openrocket/android/Application.java b/src/net/sf/openrocket/android/Application.java deleted file mode 100644 index 6628e5fb..00000000 --- a/src/net/sf/openrocket/android/Application.java +++ /dev/null @@ -1,84 +0,0 @@ -package net.sf.openrocket.android; - -import java.util.Locale; - -import android.preference.PreferenceManager; - -import net.sf.openrocket.database.ThrustCurveMotorSetDatabase; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.l10n.DebugTranslator; -import net.sf.openrocket.l10n.ResourceBundleTranslator; -import net.sf.openrocket.l10n.Translator; - -public class Application extends android.app.Application { - - private OpenRocketDocument rocketDocument; - - // Big B boolean so I can synchronize on it. - private static Boolean initialized = false; - - public static void initialize() { - synchronized (initialized) { - if ( initialized == true ) { - return; - } - - // Android does not have a default sax parser set. This needs to be defined first. - System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver"); - - net.sf.openrocket.startup.Application.setLogger( new LogHelper() ); - - net.sf.openrocket.startup.Application.setPreferences( new PreferencesAdapter() ); - - ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(false) { - - @Override - protected void loadMotors() { - } - }; - db.startLoading(); - - net.sf.openrocket.startup.Application.setMotorSetDatabase(db); - - Translator t; - t = new ResourceBundleTranslator("l10n.messages"); - if (Locale.getDefault().getLanguage().equals("xx")) { - t = new DebugTranslator(t); - } - - net.sf.openrocket.startup.Application.setBaseTranslator(t); - - initialized = true; - } - } - - public Application() { - initialize(); - } - - /* (non-Javadoc) - * @see android.app.Application#onCreate() - */ - @Override - public void onCreate() { - super.onCreate(); - PreferencesActivity.initializePreferences(this, PreferenceManager.getDefaultSharedPreferences(this)); - } - - /** - * @return the rocketDocument - */ - public OpenRocketDocument getRocketDocument() { - return rocketDocument; - } - - /** - * @param rocketDocument the rocketDocument to set - */ - public void setRocketDocument(OpenRocketDocument rocketDocument) { - this.rocketDocument = rocketDocument; - } - - - -} diff --git a/src/net/sf/openrocket/android/LogHelper.java b/src/net/sf/openrocket/android/LogHelper.java deleted file mode 100644 index ae10d8b4..00000000 --- a/src/net/sf/openrocket/android/LogHelper.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.sf.openrocket.android; - -import android.util.Log; -import net.sf.openrocket.logging.LogLevel; -import net.sf.openrocket.logging.LogLine; - - -public class LogHelper extends net.sf.openrocket.logging.LogHelper { - - /* (non-Javadoc) - * @see net.sf.openrocket.logging.LogHelper#log(net.sf.openrocket.logging.LogLine) - */ - @Override - public void log(LogLine line) { - - LogLevel level = line.getLevel(); - - switch ( level ) { - case ERROR: - Log.e("OpenRocket", line.toString()); - break; - case WARN: - Log.w("OpenRocket", line.toString()); - break; - case INFO: - Log.i("OpenRocket", line.toString()); - break; - case DEBUG: - Log.d("OpenRocket", line.toString()); - break; - default: - Log.v("OpenRocket", line.toString()); - } - } - - -} diff --git a/src/net/sf/openrocket/android/Main.java b/src/net/sf/openrocket/android/Main.java deleted file mode 100644 index 347115c6..00000000 --- a/src/net/sf/openrocket/android/Main.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.sf.openrocket.android; - -import net.sf.openrocket.R; -import net.sf.openrocket.android.motor.MotorHierarchicalBrowser; -import android.app.Activity; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.view.View; -import android.widget.ImageView; - -public class Main extends Activity { - - private static final int PICK_ORK_FILE_RESULT = 1; - - private static final int STOPSPLASH = 0; - //time in milliseconds - private static final long SPLASHTIME = 3000; - - private ImageView splash; - - //handler for splash screen - private Handler splashHandler = new Handler() { - /* (non-Javadoc) - * @see android.os.Handler#handleMessage(android.os.Message) - */ - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case STOPSPLASH: - //remove SplashScreen from view - splash.setVisibility(View.GONE); - break; - } - super.handleMessage(msg); - } - }; - - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle icicle) { - super.onCreate(icicle); - setContentView(R.layout.main); - splash = (ImageView) findViewById(R.id.splashscreen); - Message msg = new Message(); - msg.what = STOPSPLASH; - splashHandler.sendMessageDelayed(msg, SPLASHTIME); - } - - /* (non-Javadoc) - * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) - */ - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - switch ( requestCode ) { - case PICK_ORK_FILE_RESULT: - if(resultCode==RESULT_OK){ - Uri file = data.getData(); - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setData(file); - startActivity(intent); - } - break; - } - super.onActivityResult(requestCode, resultCode, data); - } - - public void pickOrkFiles( View v ) { - Intent intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.setType("file/*"); - startActivityForResult(intent,PICK_ORK_FILE_RESULT); - } - - public void browseMotors( View v ) { - Intent i = new Intent(Main.this, MotorHierarchicalBrowser.class); - startActivity(i); - } - -} diff --git a/src/net/sf/openrocket/android/PreferencesActivity.java b/src/net/sf/openrocket/android/PreferencesActivity.java deleted file mode 100644 index 66f4d778..00000000 --- a/src/net/sf/openrocket/android/PreferencesActivity.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.sf.openrocket.android; - -import net.sf.openrocket.R; -import net.sf.openrocket.unit.UnitGroup; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; - -public class PreferencesActivity extends android.preference.PreferenceActivity -implements SharedPreferences.OnSharedPreferenceChangeListener { - - @Override - protected void onCreate( Bundle savedInstanceState ) { - super.onCreate( savedInstanceState ); - addPreferencesFromResource(R.xml.preferences); - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); - prefs.registerOnSharedPreferenceChangeListener(this); - } - - /* (non-Javadoc) - * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String) - */ - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - - initializePreferences(getApplication(), PreferenceManager.getDefaultSharedPreferences(this)); - } - - /** - * This method is to be called from Application setup to pull the saved preference - * values into the various datastructures used in OpenRocket. - * This method is located in this class because it is probably best to have as much - * of the code in the same place as possible. - * @param sharedPreferences - */ - public static void initializePreferences( android.app.Application app, SharedPreferences sharedPreferences ) { - - String unitLength = app.getResources().getString(R.string.PreferenceUnitLengthOption); - String len = sharedPreferences.getString(unitLength, "cm"); - UnitGroup.UNITS_LENGTH.setDefaultUnit( len ); - - String unitMass = app.getResources().getString(R.string.PreferenceUnitMassOption); - String mass = sharedPreferences.getString(unitMass, "g"); - UnitGroup.UNITS_MASS.setDefaultUnit( mass ); - - } - -} diff --git a/src/net/sf/openrocket/android/PreferencesAdapter.java b/src/net/sf/openrocket/android/PreferencesAdapter.java deleted file mode 100644 index 086c18c3..00000000 --- a/src/net/sf/openrocket/android/PreferencesAdapter.java +++ /dev/null @@ -1,96 +0,0 @@ -package net.sf.openrocket.android; - -import java.util.Collections; -import java.util.Set; - -import net.sf.openrocket.material.Material; - -public class PreferencesAdapter extends net.sf.openrocket.startup.Preferences { - - @Override - public boolean getBoolean(String key, boolean defaultValue) { - // TODO Auto-generated method stub - return false; - } - - @Override - public void putBoolean(String key, boolean value) { - // TODO Auto-generated method stub - - } - - @Override - public int getInt(String key, int defaultValue) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void putInt(String key, int value) { - // TODO Auto-generated method stub - - } - - @Override - public double getDouble(String key, double defaultValue) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public void putDouble(String key, double value) { - // TODO Auto-generated method stub - - } - - @Override - public String getString(String key, String defaultValue) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void putString(String key, String value) { - // TODO Auto-generated method stub - - } - - @Override - public String getString(String directory, String key, String defaultValue) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void putString(String directory, String key, String value) { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see net.sf.openrocket.startup.Preferences#addUserMaterial(net.sf.openrocket.material.Material) - */ - @Override - public void addUserMaterial(Material m) { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see net.sf.openrocket.startup.Preferences#getUserMaterials() - */ - @Override - public Set getUserMaterials() { - return Collections.emptySet(); - } - - /* (non-Javadoc) - * @see net.sf.openrocket.startup.Preferences#removeUserMaterial(net.sf.openrocket.material.Material) - */ - @Override - public void removeUserMaterial(Material m) { - // TODO Auto-generated method stub - - } - -} diff --git a/src/net/sf/openrocket/android/db/DbAdapter.java b/src/net/sf/openrocket/android/db/DbAdapter.java deleted file mode 100644 index 4de12fac..00000000 --- a/src/net/sf/openrocket/android/db/DbAdapter.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.sf.openrocket.android.db; - -import android.content.Context; -import android.database.SQLException; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.util.Log; - -public class DbAdapter { - - private static final String TAG = "DbAdapter"; - private DatabaseHelper mDbHelper; - private SQLiteDatabase mDb; - - private static final String DATABASE_NAME = "rocketflightnotebook"; - private static final int DATABASE_VERSION = 5; - - private final Context mCtx; - - private MotorDao motorDao; - - public MotorDao getMotorDao() { - return motorDao; - } - - private class DatabaseHelper extends SQLiteOpenHelper { - DatabaseHelper(Context context) { - super(context, DATABASE_NAME, null, DATABASE_VERSION); - } - - @Override - public void onCreate(SQLiteDatabase db) { - executeSQL( db, MotorDao.create()); - } - - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - Log.w(TAG, "Upgrading database from version " + oldVersion + " to " - + newVersion + ", which will destroy all old data"); - executeSQL(db, MotorDao.update(oldVersion, newVersion)); - } - - private void executeSQL( SQLiteDatabase db, String[] sqls ) { - for(String s: sqls ) { - db.execSQL(s); - } - } - - } - - /** - * Constructor - takes the context to allow the database to be - * opened/created - * - * @param ctx the Context within which to work - */ - public DbAdapter(Context ctx) { - this.mCtx = ctx; - } - - /** - * Open the database. If it cannot be opened, try to create a new - * instance of the database. If it cannot be created, throw an exception to - * signal the failure - * - * @return this (self reference, allowing this to be chained in an - * initialization call) - * @throws SQLException if the database could be neither opened or created - */ - public DbAdapter open() throws SQLException { - mDbHelper = new DatabaseHelper(mCtx); - mDb = mDbHelper.getWritableDatabase(); - motorDao = new MotorDao(mDb); - return this; - } - - public void close() { - mDbHelper.close(); - } - -} \ No newline at end of file diff --git a/src/net/sf/openrocket/android/db/MotorDao.java b/src/net/sf/openrocket/android/db/MotorDao.java deleted file mode 100644 index 7da2598a..00000000 --- a/src/net/sf/openrocket/android/db/MotorDao.java +++ /dev/null @@ -1,270 +0,0 @@ -package net.sf.openrocket.android.db; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.Vector; - -import net.sf.openrocket.android.motor.Motor; -import android.content.ContentValues; -import android.database.Cursor; -import android.database.SQLException; -import android.database.sqlite.SQLiteDatabase; -import android.util.Log; - -public class MotorDao { - - private static final String TAG = "MotorDao"; - - private SQLiteDatabase mDb; - - private final static String DATABASE_TABLE = "motor"; - private final static String DROP_TABLE = "DROP TABLE IF EXISTS " + DATABASE_TABLE; - private final static String CREATE_TABLE = - "create table "+ DATABASE_TABLE + " ( " + - "_id integer primary key, "+ - "unique_name text unique, "+ - "name text, "+ - "diameter number, "+ - "tot_impulse_ns number, "+ - "avg_thrust_n number, "+ - "max_thrust_n number, "+ - "burn_time_s number, "+ - "length number," + - "prop_mass_g number,"+ - "tot_mass_g number,"+ - "case_info text,"+ - "manufacturer text," + - "impulse_class text," + - "burndata blob"+ - ");"; - - MotorDao( SQLiteDatabase mDb ) { - this.mDb = mDb; - } - - static String[] create() { return new String[] {CREATE_TABLE}; } - - static String[] update( int oldVer, int newVer ) { - return new String[] { DROP_TABLE, CREATE_TABLE }; - } - - public final static String ID = "_id"; - public final static String UNIQUE_NAME = "unique_name"; - public final static String NAME = "name"; - public final static String DIAMETER = "diameter"; - public final static String TOTAL_IMPULSE = "tot_impulse_ns"; - public final static String AVG_THRUST = "avg_thrust_n"; - public final static String MAX_THRUST = "max_thrust_n"; - public final static String BURN_TIME = "burn_time_s"; - public final static String LENGTH = "length"; - public final static String PROP_MASS = "prop_mass_g"; - public final static String TOT_MASS = "tot_mass_g"; - public final static String BURNDATA = "burndata"; - public final static String CASE_INFO = "case_info"; - public final static String MANUFACTURER = "manufacturer"; - public final static String IMPULSE_CLASS = "impulse_class"; - - public long insertOrUpdateMotor(Motor mi) { - ContentValues initialValues = new ContentValues(); - initialValues.put(ID, mi.getMotor_id()); - initialValues.put(NAME, mi.getName()); - initialValues.put(DIAMETER,mi.getDiameter()); - initialValues.put(TOTAL_IMPULSE,mi.getTotalImpulse()); - initialValues.put(AVG_THRUST,mi.getAvgThrust()); - initialValues.put(MAX_THRUST,mi.getMaxThrust()); - initialValues.put(BURN_TIME,mi.getBurnTime()); - initialValues.put(LENGTH, mi.getLength()); - initialValues.put(PROP_MASS, mi.getPropMass()); - initialValues.put(TOT_MASS,mi.getTotMass()); - initialValues.put(CASE_INFO, mi.getCaseInfo()); - initialValues.put(MANUFACTURER,mi.getManufacturer()); - initialValues.put(IMPULSE_CLASS,mi.getImpulseClass()); - initialValues.put(UNIQUE_NAME, mi.getManufacturer()+mi.getName()); - { - // Serialize the Vector of burn data - Vector burndata = mi.getBurndata(); - byte[] serObj = null; - if ( burndata != null ) { - try { - ByteArrayOutputStream b = new ByteArrayOutputStream(); - ObjectOutputStream os = new ObjectOutputStream(b); - os.writeObject(burndata); - os.close(); - serObj = b.toByteArray(); - } catch (Exception ex) { - Log.d(TAG,"unable to serialze burndata"); - } - } - initialValues.put(BURNDATA, serObj); - } - - - Log.d(TAG,"insertOrUpdate Motor"); - long rv = mDb.insertWithOnConflict(DATABASE_TABLE, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE); - return rv; - } - - /** - * Delete the motor and burn data with the given rowId - * - * @param name name of motor to delete - * @return true if deleted, false otherwise - */ - public boolean deleteMotor(Long id) { - - boolean rv = mDb.delete(DATABASE_TABLE, ID + "=" + id, null) > 0; - return rv; - } - - /** - * - * @param groupCol - * @param groupVal - * @return - */ - public Cursor fetchAllInGroups( String groupCol, String groupVal ) { - return mDb.query(DATABASE_TABLE, - /* columns */new String[] { - ID, - NAME, - DIAMETER , - TOTAL_IMPULSE, - AVG_THRUST , - MAX_THRUST , - BURN_TIME , - LENGTH, - PROP_MASS, - TOT_MASS, - CASE_INFO, - IMPULSE_CLASS, - MANUFACTURER - }, - /* selection */groupCol + "=?", - /* selection args*/new String[] {groupVal}, - /* groupby */null, - /* having*/null, - /* orderby*/ NAME ); - - } - - /** - * Fetch the groups based on groupCol - * @param groupCol - * @return - */ - public Cursor fetchGroups( String groupCol ) { - return mDb.query(true, DATABASE_TABLE, - /* columns */new String[] { - groupCol - }, - /* selection */null, - /* selection args*/null, - /* groupby */null, - /* having*/null, - /* orderby*/null, - /* limit*/ null); - - } - - /** - * Return a Cursor over the list of all motors - * - * @return Cursor over all notes - */ - public Cursor fetchAllMotors() { - - return mDb.query(DATABASE_TABLE, - /* columns */new String[] { - ID, - NAME, - DIAMETER , - TOTAL_IMPULSE, - AVG_THRUST , - MAX_THRUST , - BURN_TIME , - LENGTH, - PROP_MASS, - TOT_MASS, - CASE_INFO, - IMPULSE_CLASS, - MANUFACTURER - }, - /* selection */null, - /* selection args*/null, - /* groupby */null, - /* having*/null, - /* orderby*/null); - } - - public Motor fetchMotor(Long id ) throws SQLException { - Cursor mCursor = mDb.query(DATABASE_TABLE, - /* columns */new String[] { - ID, - NAME , - DIAMETER , - TOTAL_IMPULSE , - AVG_THRUST , - MAX_THRUST , - BURN_TIME , - LENGTH, - PROP_MASS, - TOT_MASS, - CASE_INFO, - IMPULSE_CLASS, - MANUFACTURER, - BURNDATA - }, - /* selection */ID + "="+id, - /* selection args*/null, - /* groupby */null, - /* having*/null, - /* orderby*/null); - if ( mCursor == null ) { - return null; - } - try { - if (mCursor.getCount() == 0) { - return null; - } - mCursor.moveToFirst(); - Motor mi = new Motor(); - mi.setMotor_id(mCursor.getLong(mCursor.getColumnIndex(ID))); - mi.setName(mCursor.getString(mCursor.getColumnIndex(NAME))); - mi.setDiameter(mCursor.getLong(mCursor.getColumnIndex(DIAMETER))); - mi.setTotalImpulse(mCursor.getFloat(mCursor.getColumnIndex(TOTAL_IMPULSE))); - mi.setAvgThrust(mCursor.getFloat(mCursor.getColumnIndex(AVG_THRUST))); - mi.setMaxThrust(mCursor.getFloat(mCursor.getColumnIndex(MAX_THRUST))); - mi.setBurnTime(mCursor.getFloat(mCursor.getColumnIndex(BURN_TIME))); - mi.setLength(mCursor.getFloat(mCursor.getColumnIndex(LENGTH))); - mi.setPropMass(mCursor.getDouble(mCursor.getColumnIndex(PROP_MASS))); - mi.setCaseInfo(mCursor.getString(mCursor.getColumnIndex(CASE_INFO))); - mi.setTotMass(mCursor.getDouble(mCursor.getColumnIndex(TOT_MASS))); - mi.setManufacturer(mCursor.getString(mCursor.getColumnIndex(MANUFACTURER))); - mi.setImpulseClass(mCursor.getString(mCursor.getColumnIndex(IMPULSE_CLASS))); - - { - // Deserialize burndata column - byte[] serObj = mCursor.getBlob(mCursor.getColumnIndex(BURNDATA)); - Vector burndata = null; - if (serObj != null ) { - try { - ObjectInputStream is = new ObjectInputStream( new ByteArrayInputStream(serObj)); - burndata = (Vector) is.readObject(); - } - catch (Exception ex) { - Log.d(TAG,"cannot deserialize burndata"); - } - } - mi.setBurndata(burndata); - } - return mi; - } - finally { - mCursor.close(); - } - - } - -} diff --git a/src/net/sf/openrocket/android/motor/BurnPlotFragment.java b/src/net/sf/openrocket/android/motor/BurnPlotFragment.java deleted file mode 100644 index 1a8df463..00000000 --- a/src/net/sf/openrocket/android/motor/BurnPlotFragment.java +++ /dev/null @@ -1,243 +0,0 @@ -package net.sf.openrocket.android.motor; - -import java.util.Vector; - -import net.sf.openrocket.R; -import android.app.Activity; -import android.graphics.Color; -import android.graphics.PointF; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.ScaleGestureDetector; -import android.view.View; -import android.view.View.OnTouchListener; -import android.view.ViewGroup; - -import com.androidplot.xy.BoundaryMode; -import com.androidplot.xy.LineAndPointFormatter; -import com.androidplot.xy.LineAndPointRenderer; -import com.androidplot.xy.SimpleXYSeries; -import com.androidplot.xy.XYPlot; -import com.androidplot.xy.YValueMarker; - -public class BurnPlotFragment extends Fragment implements OnTouchListener { - - private final static String TAG = "BurnPlotFragment"; - - private XYPlot mySimpleXYPlot; - private SimpleXYSeries mySeries; - private PointF minXY; - private PointF maxXY; - - private float absMinX; - private float absMaxX; - private float minNoError; - private float maxNoError; - - private ScaleGestureDetector mScaleDetector; - private float mScaleFactor = 1.f; - - public static BurnPlotFragment initializeBurnPlotHelper( Motor motor ) { - BurnPlotFragment h = new BurnPlotFragment(); - - Bundle args = new Bundle(); - args.putSerializable("Motor", motor); - h.setArguments(args); - return h; - } - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - Log.d(TAG,"onAttach"); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - Log.d(TAG,"onCreate"); - super.onCreate(savedInstanceState); - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - Log.d(TAG,"onCreateView"); - View v = inflater.inflate(R.layout.motor_burn, container, false); - mySimpleXYPlot = (XYPlot) v.findViewById(R.id.xyplot); - mySimpleXYPlot.setOnTouchListener(this); - mScaleDetector = new ScaleGestureDetector(v.getContext(), new ScaleListener()); - // Motor motor = getMotor(); - // init(motor); - return v; - } - - void init( Motor motor ) { - - mySimpleXYPlot.setUserDomainOrigin(0); - mySimpleXYPlot.setUserRangeOrigin(0); - mySimpleXYPlot.setRangeLabel("impuse (n)"); - mySimpleXYPlot.setDomainLabel("time (s)"); - mySimpleXYPlot.addMarker(new YValueMarker(motor.getAvgThrust(),"average" )); - mySimpleXYPlot.disableAllMarkup(); - - Vector data = null; - try { - data = motor.getBurndata(); - } catch ( Exception ex ) { - } - if ( data == null || data.size() == 0 ) { - data = new Vector(); - data.add(0.0); - data.add(0.0); - data.add(1.0); - data.add(1.0); - } - Log.d("plot","data = " + data.toString()); - - mySeries = new SimpleXYSeries(data, SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED,motor.getName()); - - mySimpleXYPlot.addSeries(mySeries, LineAndPointRenderer.class, - new LineAndPointFormatter(Color.rgb(0, 255, 0), Color.rgb(200, 0, 0), null)); - - //Set of internal variables for keeping track of the boundaries - mySimpleXYPlot.calculateMinMaxVals(); - - mySimpleXYPlot.redraw(); - - minXY=new PointF(mySimpleXYPlot.getCalculatedMinX().floatValue(),mySimpleXYPlot.getCalculatedMinY().floatValue()); - maxXY=new PointF(mySimpleXYPlot.getCalculatedMaxX().floatValue(),mySimpleXYPlot.getCalculatedMaxY().floatValue()); - - absMinX = minXY.x; - absMaxX = maxXY.x; - - minNoError = Math.round(mySeries.getX(1).floatValue() +2); - maxNoError = Math.round(mySeries.getX(mySeries.size() -1).floatValue()) - 2.0f; - } - - private float mPosX; - private float mPosY; - - private float mLastTouchX; - private float mLastTouchY; - - private int mActivePointerId = -1; - - @Override - public boolean onTouch(View arg0, MotionEvent event) { - mScaleDetector.onTouchEvent(event); - - final int action = event.getAction(); - switch ( action & MotionEvent.ACTION_MASK ) { - case MotionEvent.ACTION_DOWN: { - final float x = event.getX(); - final float y = event.getY(); - - mLastTouchX = x; - mLastTouchY = y; - - mActivePointerId = event.getPointerId(0); - break; - } - - case MotionEvent.ACTION_MOVE: { - final int pointerIndex = event.findPointerIndex(mActivePointerId); - final float x = event.getX(pointerIndex); - final float y = event.getY(pointerIndex); - - if (!mScaleDetector.isInProgress()) { - final float dx = x - mLastTouchX; - final float dy = y - mLastTouchY; - - mPosX += dx; - mPosY += dy; - scroll(dx); - // do scroll. - - } - mLastTouchX = x; - mLastTouchY = y; - - break; - } - - case MotionEvent.ACTION_UP: { - mActivePointerId = -1; - break; - } - - case MotionEvent.ACTION_CANCEL: { - mActivePointerId = -1; - break; - } - - case MotionEvent.ACTION_POINTER_UP: { - final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; - final int pointerId = event.getPointerId(pointerIndex); - if (pointerId == mActivePointerId) { - // This was our active pointer going up. choose a new active pointer and adjust accordingly. - final int newPointerIndex = pointerIndex ==0 ? 1:0; - mLastTouchX = event.getX(newPointerIndex); - mLastTouchY = event.getY(newPointerIndex); - mActivePointerId = event.getPointerId(newPointerIndex); - } - break; - } - } - return true; - } - - private void zoom(float scale) { - Log.d(TAG,"zoom by " + scale); - float domainSpan = absMaxX - absMinX; - Log.d(TAG,"domainSpan = " + domainSpan); - float domainMidPoint = absMaxX - domainSpan / 2.0f; - Log.d(TAG,"domainMidPoint = " + domainMidPoint); - float offset = domainSpan / scale; - Log.d(TAG,"offset " + offset); - minXY.x=domainMidPoint- offset; - Log.d(TAG,"min X " + minXY.x); - maxXY.x=domainMidPoint+offset; - Log.d(TAG,"max X " + maxXY.x); - checkBoundaries(); - mySimpleXYPlot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.AUTO); - mySimpleXYPlot.redraw(); - } - - private void scroll(float pan) { - float domainSpan = maxXY.x - minXY.x; - float step = domainSpan / mySimpleXYPlot.getWidth(); - float offset = pan * step; - minXY.x+= offset; - maxXY.x+= offset; - checkBoundaries(); - mySimpleXYPlot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.AUTO); - mySimpleXYPlot.redraw(); - } - - private void checkBoundaries() { - - if ( minXY.x < absMinX) - minXY.x = absMinX; -// else if ( minXY.x > maxNoError ) -// minXY.x = maxNoError; - - if ( maxXY.x > absMaxX) - maxXY.x = absMaxX; -// else if ( maxXY.x < minNoError) -// maxXY.x = minNoError; - } - private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { - @Override - public boolean onScale( ScaleGestureDetector detector ) { - mScaleFactor *= detector.getScaleFactor(); - - mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 5.0f)); - zoom(mScaleFactor); - return true; - } - } -} - diff --git a/src/net/sf/openrocket/android/motor/Motor.java b/src/net/sf/openrocket/android/motor/Motor.java deleted file mode 100644 index 68bd113a..00000000 --- a/src/net/sf/openrocket/android/motor/Motor.java +++ /dev/null @@ -1,107 +0,0 @@ -package net.sf.openrocket.android.motor; - -import java.io.Serializable; -import java.util.Vector; - -public class Motor implements Serializable { - - private Long motor_id; - private String name; - private String impulseClass; - private String manufacturer; - private Long diameter; - private String caseInfo; - private Float avgThrust; - private Float maxThrust; - private Float totalImpulse; - private Float burnTime; - private Float length; - private Double propMass; - private Double totMass; - private Vector burndata; - public Long getMotor_id() { - return motor_id; - } - public void setMotor_id(Long motor_id) { - this.motor_id = motor_id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getImpulseClass() { - return impulseClass; - } - public void setImpulseClass(String impulseClass) { - this.impulseClass = impulseClass; - } - public String getManufacturer() { - return manufacturer; - } - public void setManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - } - public Long getDiameter() { - return diameter; - } - public void setDiameter(Long diameter) { - this.diameter = diameter; - } - public String getCaseInfo() { - return caseInfo; - } - public void setCaseInfo(String caseInfo) { - this.caseInfo = caseInfo; - } - public Float getAvgThrust() { - return avgThrust; - } - public void setAvgThrust(Float avgThrust) { - this.avgThrust = avgThrust; - } - public Float getMaxThrust() { - return maxThrust; - } - public void setMaxThrust(Float maxThrust) { - this.maxThrust = maxThrust; - } - public Float getTotalImpulse() { - return totalImpulse; - } - public void setTotalImpulse(Float totalImpulse) { - this.totalImpulse = totalImpulse; - } - public Float getBurnTime() { - return burnTime; - } - public void setBurnTime(Float burnTime) { - this.burnTime = burnTime; - } - public Float getLength() { - return length; - } - public void setLength(Float length) { - this.length = length; - } - public Double getPropMass() { - return propMass; - } - public void setPropMass(Double propMass) { - this.propMass = propMass; - } - public Double getTotMass() { - return totMass; - } - public void setTotMass(Double totMass) { - this.totMass = totMass; - } - public Vector getBurndata() { - return burndata; - } - public void setBurndata(Vector burndata) { - this.burndata = burndata; - } - -} diff --git a/src/net/sf/openrocket/android/motor/MotorDetails.java b/src/net/sf/openrocket/android/motor/MotorDetails.java deleted file mode 100644 index 19f75487..00000000 --- a/src/net/sf/openrocket/android/motor/MotorDetails.java +++ /dev/null @@ -1,77 +0,0 @@ -package net.sf.openrocket.android.motor; - -import net.sf.openrocket.R; -import android.content.Intent; -import android.os.Bundle; -import android.support.v4.app.FragmentActivity; -import android.util.Log; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.widget.ImageView; -import android.widget.SlidingDrawer; - -public class MotorDetails extends FragmentActivity -implements SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerOpenListener { - - private final static String TAG = "MotorDetails"; - - private SlidingDrawer slidingDrawer; - private ImageView handle; - - private Motor motor; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Log.d(TAG,"onCreate Bundle = "+ String.valueOf(savedInstanceState)); - setContentView(R.layout.motor_detail); - - Intent i = getIntent(); - motor = (Motor) i.getSerializableExtra("Motor"); - - BurnPlotFragment burnPlot = (BurnPlotFragment) getSupportFragmentManager().findFragmentById(R.id.burnPlotFragment); - burnPlot.init(motor); - - MotorDetailsFragment motorDetails = (MotorDetailsFragment) getSupportFragmentManager().findFragmentById(R.id.motorDetailForm); - motorDetails.init(motor); - - slidingDrawer = (SlidingDrawer) findViewById(R.id.drawer); - - slidingDrawer.setOnDrawerOpenListener(this); - slidingDrawer.setOnDrawerCloseListener(this); - - handle = (ImageView) findViewById(R.id.handle); - - } - - @Override - public void onDrawerOpened() { - handle.setImageResource(R.drawable.arrow_down_float); - } - - @Override - public void onDrawerClosed() { - handle.setImageResource(R.drawable.arrow_up_float); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.motor_details_option_menu, menu); - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - switch(item.getItemId()) { - case R.id.save: - // Extract form data to Motor. - // Save motor. - return true; - } - return super.onMenuItemSelected(featureId, item); - } - - -} diff --git a/src/net/sf/openrocket/android/motor/MotorDetailsFragment.java b/src/net/sf/openrocket/android/motor/MotorDetailsFragment.java deleted file mode 100644 index eca5d9c6..00000000 --- a/src/net/sf/openrocket/android/motor/MotorDetailsFragment.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.android.motor; - -import net.sf.openrocket.R; -import android.os.Bundle; -import android.support.v4.app.Fragment; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.EditText; - -public class MotorDetailsFragment extends Fragment { - - EditText manuField; - EditText nameField; - EditText caseField; - EditText impulseClassField; - EditText diameterField; - EditText lengthField; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.motor_detail_form, container, false); - manuField = (EditText) v.findViewById(R.id.motorDetailsManufacturer); - nameField = (EditText) v.findViewById(R.id.motorDetailsName); - caseField = (EditText) v.findViewById(R.id.motorDetailsCaseInfo); - impulseClassField = (EditText) v.findViewById(R.id.motorDetailsImpuseClass); - diameterField = (EditText) v.findViewById(R.id.motorDetailsDiameter); - lengthField = (EditText) v.findViewById(R.id.motorDetailsLength); - return v; - } - - public void init( Motor m ) { - manuField.setText( m.getManufacturer()); - nameField.setText( m.getName() ); - caseField.setText( m.getCaseInfo()); - impulseClassField.setText( m.getImpulseClass()); - diameterField.setText( m.getDiameter().toString() ); - lengthField.setText( m.getLength().toString() ); - - } - -} diff --git a/src/net/sf/openrocket/android/motor/MotorHierarchicalBrowser.java b/src/net/sf/openrocket/android/motor/MotorHierarchicalBrowser.java deleted file mode 100644 index 8344083c..00000000 --- a/src/net/sf/openrocket/android/motor/MotorHierarchicalBrowser.java +++ /dev/null @@ -1,231 +0,0 @@ -package net.sf.openrocket.android.motor; - -import net.sf.openrocket.R; -import net.sf.openrocket.android.PreferencesActivity; -import net.sf.openrocket.android.db.DbAdapter; -import net.sf.openrocket.android.db.MotorDao; -import net.sf.openrocket.android.thrustcurve.TCQueryActivity; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.res.Resources; -import android.database.Cursor; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.ContextMenu; -import android.view.ContextMenu.ContextMenuInfo; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.CursorTreeAdapter; -import android.widget.ExpandableListView; -import android.widget.SimpleCursorTreeAdapter; - - -public class MotorHierarchicalBrowser -extends PersistentExpandableListActivity -implements SharedPreferences.OnSharedPreferenceChangeListener -{ - private static final String TAG = "MotorHierarchicalBrowser"; - - private static final int ACTIVITY_DOWNLOAD=0; - - private static final int CONTEXTMENU_DELETE = Menu.FIRST+1; - - private String groupColumnPreferenceKey; - private String groupColumn = MotorDao.CASE_INFO; - - private static final String[] groupColumns = new String[] { - MotorDao.CASE_INFO, - MotorDao.DIAMETER, - MotorDao.IMPULSE_CLASS, - MotorDao.MANUFACTURER - }; - - private CursorTreeAdapter mAdapter; - - private DbAdapter mDbHelper; - - public class MotorHierarchicalListAdapter extends SimpleCursorTreeAdapter - { - - // Note that the constructor does not take a Cursor. This is done to avoid querying the - // database on the main thread. - public MotorHierarchicalListAdapter(Context context, Cursor cursor, int groupLayout, - int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom, - int[] childrenTo) { - - super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, - childrenTo); - } - - @Override - protected Cursor getChildrenCursor(Cursor arg0) { - Log.d(TAG,"getChildrenCursor"); - String group = arg0.getString(arg0.getColumnIndex(groupColumn)); - Log.d(TAG," for: "+ groupColumn + " = " + group); - Cursor c = mDbHelper.getMotorDao().fetchAllInGroups(groupColumn,group); - Log.d(TAG," got cursor"); - startManagingCursor(c); - return c; - } - - @Override - public long getGroupId(int groupPosition) { - return groupPosition; - } - - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) { - if ( groupColumnPreferenceKey.equals(arg1) ) { - setGroupColumnFromPreferences(arg0); - refreshData(); - } - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - mDbHelper = new DbAdapter(this); - mDbHelper.open(); - - Resources resources = this.getResources(); - groupColumnPreferenceKey = resources.getString(R.string.PreferenceMotorBrowserGroupingOption); - SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); - - setGroupColumnFromPreferences(pref); - - pref.registerOnSharedPreferenceChangeListener(this); - - refreshData(); - - registerForContextMenu(getExpandableListView()); - - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.motor_browser_option_menu, menu); - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - Log.d(TAG,"onMenuItemSelected" + item.getItemId()); - switch(item.getItemId()) { - case R.id.download_from_thrustcurve_menu_option: - tcDownload(); - return true; - case R.id.preference_menu_option: - Intent intent = new Intent().setClass(this, PreferencesActivity.class); - this.startActivity(intent); - return true; - } - return super.onMenuItemSelected(featureId, item); - } - - @Override - public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { - Log.d(TAG,"onCreateContextMenu " + menuInfo); - Log.d(TAG, "v.getId() = " + v.getId()); - Log.d(TAG, "motorListView = " + R.id.motorListView); - // if (v.getId() == R.id.motorListView) { - ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; - menu.setHeaderTitle("context menu"); - menu.add(Menu.NONE,CONTEXTMENU_DELETE,CONTEXTMENU_DELETE,"Delete"); - // } - super.onCreateContextMenu(menu, v, menuInfo); - } - - @Override - public boolean onContextItemSelected(MenuItem item) { - ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo(); - long motorId = info.id; - Log.d(TAG,"ContextMenu: " + motorId); - switch(item.getItemId()) { - case CONTEXTMENU_DELETE: - mDbHelper.getMotorDao().deleteMotor(motorId); - refreshData(); - return true; - } - return super.onContextItemSelected(item); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent intent) { - super.onActivityResult(requestCode, resultCode, intent); - refreshData(); - } - - - @Override - public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { - super.onChildClick(parent, v, groupPosition, childPosition, id); - Motor m = mDbHelper.getMotorDao().fetchMotor(id); - //Intent i = new Intent(this, BurnPlotActivity.class); - Intent i = new Intent(this,MotorDetails.class); - i.putExtra("Motor", m); - startActivity(i); - return true; - } - - @Override - protected void onDestroy() { - super.onDestroy(); - - SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); - pref.unregisterOnSharedPreferenceChangeListener(this); - - // Null out the group cursor. This will cause the group cursor and all of the child cursors - // to be closed. - mAdapter.changeCursor(null); - mAdapter = null; - - mDbHelper.close(); - } - - private void tcDownload() { - Intent i = new Intent(this, TCQueryActivity.class); - startActivityForResult(i, ACTIVITY_DOWNLOAD); - } - - private void setGroupColumnFromPreferences( SharedPreferences prefs ) { - String indexStr = prefs.getString(groupColumnPreferenceKey, "1"); - int index; - //Dirty hack, you can't use integer-array in ListPreferences - try { - index = Integer.parseInt(indexStr); - } catch ( Exception e ) { - index = 1; - } - if ( index >= groupColumns.length ) { - index = 1; - } - groupColumn = groupColumns[index]; - - } - private void refreshData() { - if (mAdapter != null ) { - mAdapter.changeCursor(null); - } - Cursor motorCursor = mDbHelper.getMotorDao().fetchGroups(groupColumn); - startManagingCursor(motorCursor); - // Set up our adapter - mAdapter = new MotorHierarchicalListAdapter( - this, - motorCursor, - R.layout.motor_list_group, - R.layout.motor_list_child, - new String[] { groupColumn }, // Name for group layouts - new int[] { R.id.motorGroup }, - new String[] { MotorDao.MANUFACTURER, MotorDao.NAME, MotorDao.TOTAL_IMPULSE }, // Number for child layouts - new int[] { R.id.motorChildManu, R.id.motorChildName, R.id.motorChildImpulse }); - setListAdapter(mAdapter); - } -} diff --git a/src/net/sf/openrocket/android/motor/PersistentExpandableListActivity.java b/src/net/sf/openrocket/android/motor/PersistentExpandableListActivity.java deleted file mode 100644 index f179374a..00000000 --- a/src/net/sf/openrocket/android/motor/PersistentExpandableListActivity.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.sf.openrocket.android.motor; - -import java.util.ArrayList; -import java.util.List; - -import android.app.ExpandableListActivity; -import android.os.Bundle; -import android.widget.ExpandableListAdapter; -import android.widget.ExpandableListView; - -public class PersistentExpandableListActivity extends ExpandableListActivity { - private long[] expandedIds; - - @Override - protected void onStart() { - super.onStart(); - if (this.expandedIds != null) { - restoreExpandedState(expandedIds); - } - } - - @Override - protected void onStop() { - super.onStop(); - expandedIds = getExpandedIds(); - } - - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - this.expandedIds = getExpandedIds(); - outState.putLongArray("ExpandedIds", this.expandedIds); - } - - @Override - protected void onRestoreInstanceState(Bundle state) { - super.onRestoreInstanceState(state); - long[] expandedIds = state.getLongArray("ExpandedIds"); - if (expandedIds != null) { - restoreExpandedState(expandedIds); - } - } - - private long[] getExpandedIds() { - ExpandableListView list = getExpandableListView(); - ExpandableListAdapter adapter = getExpandableListAdapter(); - if (adapter != null) { - int length = adapter.getGroupCount(); - ArrayList expandedIds = new ArrayList(); - for(int i=0; i < length; i++) { - if(list.isGroupExpanded(i)) { - expandedIds.add(adapter.getGroupId(i)); - } - } - return toLongArray(expandedIds); - } else { - return null; - } - } - - private void restoreExpandedState(long[] expandedIds) { - this.expandedIds = expandedIds; - if (expandedIds != null) { - ExpandableListView list = getExpandableListView(); - ExpandableListAdapter adapter = getExpandableListAdapter(); - if (adapter != null) { - for (int i=0; i list) { - long[] ret = new long[list.size()]; - int i = 0; - for (Long e : list) - ret[i++] = e.longValue(); - return ret; - } -} diff --git a/src/net/sf/openrocket/android/rocket/OpenRocketLoaderTask.java b/src/net/sf/openrocket/android/rocket/OpenRocketLoaderTask.java deleted file mode 100644 index aef2ace4..00000000 --- a/src/net/sf/openrocket/android/rocket/OpenRocketLoaderTask.java +++ /dev/null @@ -1,34 +0,0 @@ -package net.sf.openrocket.android.rocket; - -import java.io.File; - -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.file.RocketLoadException; -import net.sf.openrocket.file.openrocket.OpenRocketLoader; -import android.os.AsyncTask; -import android.util.Log; - -public class OpenRocketLoaderTask extends AsyncTask { - - private final static String TAG = "OpenRocketLoaderTask"; - - /* (non-Javadoc) - * @see android.os.AsyncTask#doInBackground(Params[]) - */ - @Override - protected OpenRocketDocument doInBackground(File... arg0) { - Log.d(TAG,"doInBackgroud"); - - OpenRocketLoader rocketLoader = new OpenRocketLoader(); - try { - OpenRocketDocument rocket = rocketLoader.load(arg0[0]); - return rocket; - } - catch( RocketLoadException ex ) { - Log.e(TAG, "doInBackground rocketLaoder.load threw", ex); - } - return null; - - } - -} diff --git a/src/net/sf/openrocket/android/rocket/OpenRocketViewer.java b/src/net/sf/openrocket/android/rocket/OpenRocketViewer.java deleted file mode 100644 index 1037d1b8..00000000 --- a/src/net/sf/openrocket/android/rocket/OpenRocketViewer.java +++ /dev/null @@ -1,270 +0,0 @@ -package net.sf.openrocket.android.rocket; - - -import java.io.File; - -import net.sf.openrocket.R; -import net.sf.openrocket.android.Application; -import net.sf.openrocket.android.PreferencesActivity; -import net.sf.openrocket.android.motor.MotorHierarchicalBrowser; -import net.sf.openrocket.android.simulation.SimulationViewer; -import net.sf.openrocket.document.OpenRocketDocument; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.rocketcomponent.Rocket; -import net.sf.openrocket.rocketcomponent.RocketComponent; -import net.sf.openrocket.rocketcomponent.RocketUtils; -import net.sf.openrocket.unit.Unit; -import net.sf.openrocket.unit.UnitGroup; -import net.sf.openrocket.util.Coordinate; -import android.app.Activity; -import android.app.ProgressDialog; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.TabHost; -import android.widget.TextView; - -public class OpenRocketViewer extends Activity -implements SharedPreferences.OnSharedPreferenceChangeListener -{ - - private static final String TAG = "OpenRocketViewer"; - - private ProgressDialog progress; - - private ListView componentList; - private ListView simulationList; - - private Application app; - - private final static int PICK_ORK_FILE_RESULT = 1; - - /* (non-Javadoc) - * @see android.app.Activity#onCreate(android.os.Bundle) - */ - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - Log.d(TAG,"In onCreate"); - - app = (Application) this.getApplication(); - - setContentView(R.layout.openrocketviewer); - - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); - prefs.registerOnSharedPreferenceChangeListener(this); - - TabHost tabs=(TabHost)findViewById(R.id.openrocketviewerTabHost); - - tabs.setup(); - - TabHost.TabSpec spec=tabs.newTabSpec("tag1"); - - spec.setContent(R.id.openrocketviewerOverview); - spec.setIndicator("Overview"); - tabs.addTab(spec); - - spec=tabs.newTabSpec("tag2"); - spec.setContent(R.id.openrocketviewerComponentList); - spec.setIndicator("Components"); - tabs.addTab(spec); - - spec=tabs.newTabSpec("tag3"); - spec.setContent(R.id.openrocketviewerSimulationList); - spec.setIndicator("Simulations"); - tabs.addTab(spec); - - componentList = (ListView) findViewById(R.id.openrocketviewerComponentList); - simulationList = (ListView) findViewById(R.id.openrocketviewerSimulationList); - - Intent i = getIntent(); - Uri file = i.getData(); - - if ( file == null ) { - Intent intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.setType("file/*"); - startActivityForResult(intent,PICK_ORK_FILE_RESULT); - - } else { - loadOrkFile(file); - } - } - - @Override - protected void onDestroy() { - if ( progress != null ) { - if ( progress.isShowing() ) { - progress.dismiss(); - } - progress = null; - } - super.onDestroy(); - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - // TODO Auto-generated method stub - switch(requestCode){ - case PICK_ORK_FILE_RESULT: - if(resultCode==RESULT_OK){ - Uri file = data.getData(); - loadOrkFile(file); - } - break; - } - } - - private void loadOrkFile( Uri file ) { - Log.d(TAG,"Use ork file: " + file); - String path = file.getPath(); - File orkFile = new File(path); - progress = ProgressDialog.show(this, "Loading file", ""); - - final OpenRocketLoaderTask task = new OpenRocketLoaderTask() { - - /* (non-Javadoc) - * @see android.os.AsyncTask#onPostExecute(java.lang.Object) - */ - @Override - protected void onPostExecute(OpenRocketDocument result) { - super.onPostExecute(result); - app.setRocketDocument( result ); - updateContents(); - } - - }; - - task.execute(orkFile); - - } - - /* (non-Javadoc) - * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String) - */ - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - // just in case the user changed the units, we redraw. - PreferencesActivity.initializePreferences(getApplication(), PreferenceManager.getDefaultSharedPreferences(this)); - updateContents(); - } - - private void updateContents() { - - OpenRocketDocument rocketDocument = app.getRocketDocument(); - Rocket rocket = rocketDocument.getRocket(); - - setTitle(rocket.getName()); - - Unit LengthUnit = UnitGroup.UNITS_LENGTH.getDefaultUnit(); - Unit MassUnit = UnitGroup.UNITS_MASS.getDefaultUnit(); - - Coordinate cg = RocketUtils.getCG(rocket); - double length = RocketUtils.getLength(rocket); - ((TextView) findViewById(R.id.openrocketviewerRocketName)).setText( rocket.getName()); - ((TextView)findViewById(R.id.openrocketviewerDesigner)).setText(rocket.getDesigner()); - ((TextView)findViewById(R.id.openrocketviewerCG)).setText(LengthUnit.toStringUnit(cg.x) ); - ((TextView)findViewById(R.id.openrocketviewerLength)).setText(LengthUnit.toStringUnit(length)); - ((TextView)findViewById(R.id.openrocketviewerMass)).setText(MassUnit.toStringUnit(cg.weight)); - ((TextView)findViewById(R.id.openrocketviewerStageCount)).setText(String.valueOf(rocket.getStageCount())); - ((TextView)findViewById(R.id.openrocketviewerComment)).setText(rocket.getComment()); - - ArrayAdapter sims = new ArrayAdapter(this,android.R.layout.simple_list_item_2,rocketDocument.getSimulations()) { - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - View v = convertView; - if ( v == null ) { - LayoutInflater li = getLayoutInflater(); - v = li.inflate(android.R.layout.simple_list_item_2,null); - } - Simulation sim = this.getItem(position); - ((TextView)v.findViewById(android.R.id.text1)).setText( sim.getName() ); - ((TextView)v.findViewById(android.R.id.text2)).setText( "motors: " + sim.getConfiguration().getMotorConfigurationDescription() + " apogee: " + sim.getSimulatedData().getMaxAltitude() + "m time: " + sim.getSimulatedData().getFlightTime() + "s"); - return v; - } - - }; - simulationList.setOnItemClickListener( new OnItemClickListener() { - @Override - public void onItemClick(AdapterView l, View v, int position, long id) { - Intent i = new Intent(OpenRocketViewer.this, SimulationViewer.class); - Log.d(TAG,"onItemClick simulation number " + id ); - i.putExtra("Simulation",(int)id); - startActivityForResult(i, 1/*magic*/); - } - - }); - simulationList.setAdapter(sims); - - ArrayAdapter comps = new ArrayAdapter(this, android.R.layout.simple_list_item_1,rocket.getChildren()) { - - /* (non-Javadoc) - * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup) - */ - @Override - public View getView(int position, View convertView, ViewGroup parent) { - View v = convertView; - if ( v == null ) { - LayoutInflater li = getLayoutInflater(); - v = li.inflate(android.R.layout.simple_list_item_1,null); - } - RocketComponent comp = this.getItem(position); - ((TextView)v.findViewById(android.R.id.text1)).setText( comp.getName() ); - return v; - } - - - }; - componentList.setAdapter(comps); - - if ( progress.isShowing() ) { - progress.dismiss(); - } - - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuInflater inflater = getMenuInflater(); - inflater.inflate(R.menu.rocket_viewer_option_menu, menu); - return true; - } - - @Override - public boolean onMenuItemSelected(int featureId, MenuItem item) { - Log.d(TAG,"onMenuItemSelected" + item.getItemId()); - switch(item.getItemId()) { - case R.id.motor_list_menu_option: - startMotorBrowser(); - return true; - case R.id.preference_menu_option: - Intent intent = new Intent().setClass(this, PreferencesActivity.class); - this.startActivity(intent); - return true; - } - return super.onMenuItemSelected(featureId, item); - } - - public void startMotorBrowser() { - Log.d(TAG,"motorBrowserButton clicked"); - Intent i = new Intent(OpenRocketViewer.this, MotorHierarchicalBrowser.class); - startActivity(i); - } - - - -} diff --git a/src/net/sf/openrocket/android/simulation/GraphicalActivity.java b/src/net/sf/openrocket/android/simulation/GraphicalActivity.java deleted file mode 100644 index 8335bd87..00000000 --- a/src/net/sf/openrocket/android/simulation/GraphicalActivity.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright (C) 2009, 2010 SC 4ViewSoft SRL - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sf.openrocket.android.simulation; - -import org.achartengine.ChartFactory; -import org.achartengine.GraphicalView; -import org.achartengine.chart.AbstractChart; - -import android.app.Activity; -import android.os.Bundle; -import android.view.Window; - -/** - * An activity that encapsulates a graphical view of the chart. - */ -public class GraphicalActivity extends Activity { - /** The encapsulated graphical view. */ - private GraphicalView mView; - /** The chart to be drawn. */ - private AbstractChart mChart; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); - Bundle extras = getIntent().getExtras(); - mChart = (AbstractChart) extras.getSerializable(ChartFactory.CHART); - mView = new GraphicalView(this, mChart); - String title = extras.getString(ChartFactory.TITLE); - if (title == null) { - requestWindowFeature(Window.FEATURE_NO_TITLE); - } else if (title.length() > 0) { - setTitle(title); - } - setContentView(mView); - } - -} \ No newline at end of file diff --git a/src/net/sf/openrocket/android/simulation/SimulationChart.java b/src/net/sf/openrocket/android/simulation/SimulationChart.java deleted file mode 100644 index 20bab823..00000000 --- a/src/net/sf/openrocket/android/simulation/SimulationChart.java +++ /dev/null @@ -1,231 +0,0 @@ -/** - * Copyright (C) 2009, 2010 SC 4ViewSoft SRL - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sf.openrocket.android.simulation; - -import java.util.List; - -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; - -import org.achartengine.ChartFactory; -import org.achartengine.chart.LineChart; -import org.achartengine.chart.PointStyle; -import org.achartengine.chart.XYChart; -import org.achartengine.model.XYMultipleSeriesDataset; -import org.achartengine.model.XYSeries; -import org.achartengine.renderer.XYMultipleSeriesRenderer; -import org.achartengine.renderer.XYSeriesRenderer; - -import android.content.Context; -import android.content.Intent; -import android.graphics.Color; -import android.graphics.Paint.Align; -import android.util.Log; - -/** - * Multiple temperature demo chart. - */ -public class SimulationChart { - - private final static String TAG = "SimulationChart"; - - private FlightDataBranch flightDataBranch; - private FlightDataType series1; - private FlightDataType series2; - private final FlightDataType time = FlightDataType.TYPE_TIME; - private List flightEvents; - - // Define 4 different colors and point styles to use for the series. - // For now only 2 series are supported though. - private final static int[] colors = new int[] { Color.BLUE, Color.YELLOW, Color.GREEN, Color.RED }; - private final static PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE, PointStyle.DIAMOND, - PointStyle.TRIANGLE, PointStyle.SQUARE }; - - /** - * @param flightDataBranch the flightDataBranch to set - */ - public void setFlightDataBranch(FlightDataBranch flightDataBranch) { - this.flightDataBranch = flightDataBranch; - } - - /** - * @param series1 the series1 to set - */ - public void setSeries1(FlightDataType series1) { - this.series1 = series1; - } - - /** - * @param series2 the series2 to set - */ - public void setSeries2(FlightDataType series2) { - this.series2 = series2; - } - - /** - * @param flightEvents the flightEvents to set - */ - public void setFlightEvents(List flightEvents) { - this.flightEvents = flightEvents; - } - - private static String formatFlightDataTypeAxisLabel( FlightDataType fdt ) { - return fdt.getName() + " (" + fdt.getUnitGroup().getDefaultUnit().toString() + ")"; - } - - /** - * Executes the chart demo. - * - * @param context the context - * @return the built intent - */ - public Intent execute(Context context) { - - /* - * TODO - - * Figure out why you can pan all over the place even where there are no visible points. - */ - int seriesCount = 2; - // if the same series is selected twice, only plot it once. - if ( series1 == series2 ) { - seriesCount = 1; - } - - XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(seriesCount); - - renderer.setAxisTitleTextSize(16); - renderer.setChartTitleTextSize(20); - renderer.setLabelsTextSize(15); - renderer.setLegendTextSize(15); - renderer.setPointSize(5f); - renderer.setXLabels(10); - renderer.setYLabels(10); - renderer.setShowGrid(true); - renderer.setZoomButtonsVisible(true); - renderer.setChartTitle("Simulation"); - - renderer.setMargins(new int[] { 50, 30, 0, 20 }); - { - for (int i = 0; i < seriesCount; i++) { - XYSeriesRenderer r = new XYSeriesRenderer(); - r.setColor(colors[i]); - r.setPointStyle(styles[i]); - r.setFillPoints(true); - renderer.addSeriesRenderer(r); - // setting the YAximMin to 0 locks the origins. - renderer.setYAxisMin(0.0, i); - } - } - - renderer.setXTitle(formatFlightDataTypeAxisLabel(time)); - renderer.setXLabelsAlign(Align.RIGHT); - - renderer.setYTitle(formatFlightDataTypeAxisLabel(series1),0); - renderer.setYLabelsAlign(Align.RIGHT,0); - - if ( seriesCount > 1 ) { - renderer.setYTitle(formatFlightDataTypeAxisLabel(series2), 1); - renderer.setYAxisAlign(Align.RIGHT, 1); - renderer.setYLabelsAlign(Align.LEFT, 1); - } - - renderer.setAxesColor(Color.LTGRAY); - renderer.setLabelsColor(Color.LTGRAY); - - XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); - - List timevalues = flightDataBranch.get(time); - List series1values = flightDataBranch.get(series1); - - // compute the axis limits using timevalues and series1values. - double xmin = 0; - double ymin = 0; - renderer.setXAxisMin(xmin); - renderer.setYAxisMin(ymin); - - double ymax = computeMaxValueWithPadding( series1values ); - double xmax = Math.ceil( timevalues.get( timevalues.size()-1)); - - Log.d(TAG,"ymax = " + ymax); - renderer.setXAxisMax(xmax); - renderer.setYAxisMax(ymax); - - // These configurations don't really work well just now. - //renderer.setPanLimits(new double[] { xmin, xmax, ymin, ymax }); - //renderer.setZoomLimits(new double[] { xmin, xmax, ymin, ymax }); - - // Add first series - addXYSeries(dataset, series1.getName(), timevalues, series1values, 0); - - if ( seriesCount > 1 ) { - // Add second series - addXYSeries(dataset, series2.getName(), timevalues, flightDataBranch.get(series2), 1); - } - Intent intent = getLineChartIntent(context, dataset, renderer,"Simulation"); - return intent; - } - - private static void addXYSeries(XYMultipleSeriesDataset dataset, String titles, List xValues, List yValues, int scale) { - XYSeries series = new XYSeries(titles, scale); - int datasize = xValues.size(); - for( int i = 0; i list ) { - double max = list.get(0); - for( double v : list ) { - if ( v > max ) { - max = v; - } - } - if ( max <= 0 ) return 1.0; - - // Do something stupid. - // return: - // 10 if max <= 10 - // next 10 if 10 < max < 1000 - // next 100 if 1000 < max < 10,000 - // next 1000 if max >= 10,000 - double numdigits = Math.floor(Math.log10(max)); - - if ( numdigits <= 1.0 ) { - return 10.0; - } else if ( numdigits <= 3.0 ) { - return 10.0 * ( Math.ceil( max/10.0)); - } else if ( numdigits <= 4.0 ) { - return 100.0 * ( Math.ceil( max/ 100.0) ); - } else { - return 1000.0 * ( Math.ceil( max / 1000.0 )); - } - - } - -} diff --git a/src/net/sf/openrocket/android/simulation/SimulationViewer.java b/src/net/sf/openrocket/android/simulation/SimulationViewer.java deleted file mode 100644 index 3746cb5f..00000000 --- a/src/net/sf/openrocket/android/simulation/SimulationViewer.java +++ /dev/null @@ -1,142 +0,0 @@ -package net.sf.openrocket.android.simulation; - -import java.util.ArrayList; -import java.util.List; - -import net.sf.openrocket.R; -import net.sf.openrocket.android.Application; -import net.sf.openrocket.document.Simulation; -import net.sf.openrocket.simulation.FlightDataBranch; -import net.sf.openrocket.simulation.FlightDataType; -import net.sf.openrocket.simulation.FlightEvent; -import android.app.Activity; -import android.content.Intent; -import android.os.Bundle; -import android.util.Log; -import android.util.SparseBooleanArray; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.ListView; -import android.widget.Spinner; -import android.widget.TabHost; -import android.widget.TextView; - -public class SimulationViewer extends Activity { - - private final static String TAG = "SimulationViewer"; - - private ListView eventList; - private Spinner series1Spinner; - private Spinner series2Spinner; - - private Simulation sim; - private FlightDataBranch data; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Log.d(TAG,"onCreate Bundle = "+ String.valueOf(savedInstanceState)); - setContentView(R.layout.simulation_detail); - - Intent i = getIntent(); - int simnumber = i.getIntExtra("Simulation", 0); - sim = ((Application)this.getApplication()).getRocketDocument().getSimulation(simnumber); - data = sim.getSimulatedData().getBranch(0); - - TabHost tabs=(TabHost)findViewById(R.id.simulationConfigurationForm); - - tabs.setup(); - - TabHost.TabSpec spec=tabs.newTabSpec("tag1"); - - spec.setContent(R.id.simulationEventsList); - spec.setIndicator("Events"); - tabs.addTab(spec); - - spec=tabs.newTabSpec("tag2"); - spec.setContent(R.id.simulationSeriesSelection); - spec.setIndicator("Series"); - tabs.addTab(spec); - - eventList = (ListView) findViewById(R.id.simulationEventsList); - - // Initialize the eventList - ArrayAdapter events = new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,data.getEvents()) { - - @Override - public View getView(int position, View convertView, - ViewGroup parent) { - View v = convertView; - if ( v == null ) { - LayoutInflater li = getLayoutInflater(); - v = li.inflate(android.R.layout.simple_list_item_multiple_choice,null); - } - FlightEvent event = this.getItem(position); - ((TextView)v.findViewById(android.R.id.text1)).setText( event.getType().toString() + " " + event.getTime() + " (s)" ); - return v; - } - - }; - eventList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); - eventList.setAdapter(events); - - series1Spinner = (Spinner) findViewById(R.id.simulationSeries1); - series2Spinner = (Spinner) findViewById(R.id.simulationSeries2); - - List selectableSeries = new ArrayList(); - for( FlightDataType fdt : data.getTypes() ) { - if ( fdt == FlightDataType.TYPE_TIME ) { - - } else { - selectableSeries.add(fdt); - } - } - ArrayAdapter serieses = new ArrayAdapter(this,android.R.layout.simple_spinner_item,selectableSeries) { - - @Override - public View getView(int position, View convertView, - ViewGroup parent) { - View v = convertView; - if ( v == null ) { - LayoutInflater li = getLayoutInflater(); - v = li.inflate(android.R.layout.simple_spinner_item,null); - } - FlightDataType fdt = this.getItem(position); - ((TextView)v.findViewById(android.R.id.text1)).setText( fdt.toString() ); - return v; - } - - }; - series1Spinner.setAdapter(serieses); - series2Spinner.setAdapter(serieses); - - } - - public void draw( View v ) { - List eventsToShow = new ArrayList(); - { - SparseBooleanArray eventsSelected = eventList.getCheckedItemPositions(); - List flightEvents = data.getEvents(); - for( int i=0; i< flightEvents.size(); i++ ) { - if ( eventsSelected.get(i) ) { - eventsToShow.add(flightEvents.get(i) ); - } - } - } - FlightDataType series1 = (FlightDataType) series1Spinner.getSelectedItem(); - Log.d(TAG,"sereis1 = " + series1.toString()); - FlightDataType series2 = (FlightDataType) series2Spinner.getSelectedItem(); - Log.d(TAG,"series2 = " + series2.toString()); - - SimulationChart chart = new SimulationChart(); - chart.setFlightDataBranch(data); - chart.setSeries1(series1); - chart.setSeries2(series2); - chart.setFlightEvents(eventsToShow); - - startActivity(chart.execute(this)); - } - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/Base64Decoder.java b/src/net/sf/openrocket/android/thrustcurve/Base64Decoder.java deleted file mode 100644 index e172edc3..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/Base64Decoder.java +++ /dev/null @@ -1,122 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; - -public abstract class Base64Decoder { - - private static final String BASE64_CHARS = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - private static final char PAD_CHAR = '='; - - private final static short[] _charToBits = new short[128]; - - static { - - for (int i = 0; i < _charToBits.length; i++) - _charToBits[i] = -1; - - for (int i = 0; i < BASE64_CHARS.length(); i++) - _charToBits[BASE64_CHARS.charAt(i)] = (byte) i; - _charToBits[PAD_CHAR] = 0; - - } - - /** - * Decode the specified Base64 string and write binary data - * to the given stream. - * @param str Base64 encoded string - * @param w output stream - */ - public static String decodeData(String str) throws IOException - { - StringReader r; - int c1; - - if (str == null || str.length() < 1) - return null; - - r = new StringReader(str); - - StringWriter w = new StringWriter(); - - // spin through the input string - c1 = readToNonSpace(r); - while (c1 > 0) - { - int c2, c3, c4; - int p1, p2, p3, p4; - int pad, n; - - pad = 0; - - c2 = readToNonSpace(r); - c3 = readToNonSpace(r); - c4 = readToNonSpace(r); - if (c4 < 0) - throw new IllegalArgumentException("Encoded string ends prematurely."); - - p1 = charToBits(c1); - p2 = charToBits(c2); - - if (c3 == PAD_CHAR) - { - p3 = 0; - pad++; - } - else - p3 = charToBits(c3); - - if (c4 == PAD_CHAR) - { - p4 = 0; - pad++; - } - else - p4 = charToBits(c4); - - if (p1 < 0 || p2 < 0 || p3 < 0 || p4 < 0) - throw new IllegalArgumentException("Encoded string contains invalid characters."); - - n = (p1 << 18) | (p2 << 12) | (p3 << 6) | p4; - - w.write((byte) ((n & 0xFF0000) >> 16)); - if (pad < 2) - w.write((byte) ((n & 0x00FF00) >> 8)); - if (pad < 1) - w.write((byte) (n & 0x0000FF)); - - c1 = readToNonSpace(r); - if (c1 > 0 && pad > 0) - throw new IllegalArgumentException("Extra characters found after padding."); - } - - return w.toString(); - } - - - private static int readToNonSpace(Reader r) - throws IOException - { - int c; - - c = r.read(); - while (c >= 0 && Character.isWhitespace(c)) - c = r.read(); - - return c; - } - - private static int charToBits(int c) - { - // use it to look up the value - if (c < 0 || c >= _charToBits.length) - return -1; - else - return _charToBits[c]; - } - - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/DownloadRequest.java b/src/net/sf/openrocket/android/thrustcurve/DownloadRequest.java deleted file mode 100644 index 98d22c13..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/DownloadRequest.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.util.ArrayList; - -class DownloadRequest { - - private ArrayList motorIds = new ArrayList(); - - private String format = null; - - public void add( Integer motorId ) { - this.motorIds.add(motorId); - } - - public void setFormat( String format ) { - this.format = format; - } - - @Override - public String toString() { - StringBuilder w = new StringBuilder(); - - w.append("\n"); - w.append("\n"); - - if ( format != null ) { - w.append(" ").append(format).append("\n"); - } - - w.append(" \n"); - for( Integer i : motorIds ) { - w.append(" ").append(i).append("\n"); - } - w.append(" \n"); - w.append("\n"); - return w.toString(); - } - - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/DownloadResponse.java b/src/net/sf/openrocket/android/thrustcurve/DownloadResponse.java deleted file mode 100644 index 84e15916..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/DownloadResponse.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.util.HashMap; -import java.util.Map; - - -public class DownloadResponse { - - private Map data = new HashMap(); - - private String error = null; - - public void add( MotorBurnFile mbd ) { - MotorBurnFile currentData = data.get(mbd.getMotorId()); - if ( currentData == null || currentData.getDatapoints().size() < mbd.getDatapoints().size() ) { - data.put(mbd.getMotorId(),mbd); - } - } - - public MotorBurnFile getData(Integer motor_id) { - return data.get(motor_id); - } - - public void setError(String error) { - this.error = error; - } - - public String getError() { - return error; - } - - @Override - public String toString() { - return "DownloadResponse [error=" + error + ", data=" + data + "]"; - } - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/DownloadResponseParser.java b/src/net/sf/openrocket/android/thrustcurve/DownloadResponseParser.java deleted file mode 100644 index 7e24e7eb..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/DownloadResponseParser.java +++ /dev/null @@ -1,122 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.io.InputStream; - -import org.xml.sax.Attributes; - -import android.sax.Element; -import android.sax.EndElementListener; -import android.sax.EndTextElementListener; -import android.sax.RootElement; -import android.sax.StartElementListener; -import android.util.Log; -import android.util.Xml; - -public class DownloadResponseParser { - - private static final String TAG = "DownloadResponseParser"; - - private static final String thrustcurveURI = "http://www.thrustcurve.org/2009/DownloadResponse"; - - private static final String root_tag = "download-response"; - private static final String results_tag = "results"; - private static final String result_tag = "result"; - private static final String motor_id_tag = "motor-id"; - private static final String simfile_id_tag = "simfile-id"; - private static final String format_tag = "format"; - private static final String source_tag = "source"; - private static final String license_tag = "license"; - private static final String data_tag = "data"; - private static final String error_tag = "error"; - - public static DownloadResponse parse( InputStream in ) { - - final DownloadResponse ret = new DownloadResponse(); - final MotorBurnFile currentMotor = new MotorBurnFile(); - - // Have a place to put the data string and format. - // We hold on to these here, then push them into the currentMotor - // only if it a supported filetype - final StringHolder current_format = new StringHolder(); - final StringHolder current_data = new StringHolder(); - - RootElement rootEl = new RootElement(thrustcurveURI, root_tag); - /* - rootEl.setStartElementListener( - new StartElementListener() { - public void start(Attributes arg0) { - Log.d(TAG,"Start Element error"); - ret.setError("IsError"); - } - } - ); - */ - Element resultsEl = rootEl.getChild( thrustcurveURI, results_tag); - Element resultEl = resultsEl.getChild( thrustcurveURI, result_tag); - resultEl.setStartElementListener( - new StartElementListener() { - @Override - public void start(Attributes arg0) { - Log.d(TAG,"Start Element result"); - currentMotor.init(); - } - } - ); - - resultEl.setEndElementListener( - new EndElementListener() { - @Override - public void end() { - if ( SupportedFileTypes.isSupportedFileType(current_format.s) ) { - currentMotor.setFiletype(current_format.s); - String s = null; - try { - s = Base64Decoder.decodeData(current_data.s); - } catch ( Exception ex ) { - Log.d(TAG,"base64: " + ex.getMessage()); - } - currentMotor.decodeFile( s ); - } - ret.add((MotorBurnFile)currentMotor.clone()); - } - } - ); - - resultEl.getChild(thrustcurveURI,motor_id_tag).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setMotor_id(Integer.parseInt(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,format_tag).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - current_format.s = arg0; - } - } - ); - resultEl.getChild(thrustcurveURI,data_tag).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - current_data.s = arg0; - } - } - ); - try { - Xml.parse(in, Xml.Encoding.UTF_8, rootEl.getContentHandler()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return ret; - } - - private static class StringHolder { - public String s; - } - -} \ No newline at end of file diff --git a/src/net/sf/openrocket/android/thrustcurve/MotorBurnFile.java b/src/net/sf/openrocket/android/thrustcurve/MotorBurnFile.java deleted file mode 100644 index 58f7bb3e..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/MotorBurnFile.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.util.Vector; - -public class MotorBurnFile { - - private Integer motor_id; - private String filetype; - private Float length; - private String delays; - private Double propWeightG; - private Double totWeightG; - private Vector datapoints = new Vector(); - - public void init() { - this.motor_id = null; - this.filetype = null; - this.length = null; - this.delays = null; - this.propWeightG = null; - this.totWeightG = null; - this.datapoints = new Vector(); - } - - @Override - public MotorBurnFile clone() { - MotorBurnFile clone = new MotorBurnFile(); - clone.motor_id = this.motor_id; - clone.filetype = this.filetype; - clone.length = this.length; - clone.delays = this.delays; - clone.propWeightG = this.propWeightG; - clone.totWeightG = this.totWeightG; - clone.datapoints = this.datapoints; - return clone; - } - - public void decodeFile(String data){ - if (SupportedFileTypes.RASP_FORMAT.equals(filetype)) { - RaspBurnFile.parse(this,data); - } else if (SupportedFileTypes.ROCKSIM_FORMAT.equals(filetype) ){ - RSEBurnFile.parse(this,data); - } - } - - public Integer getMotorId() { - return motor_id; - } - public String getFileType() { - return filetype; - } - public Float getLength() { - return length; - } - public String getDelays() { - return delays; - } - public Double getPropWeightG() { - return propWeightG; - } - public Double getTotWeightG() { - return totWeightG; - } - public Vector getDatapoints() { - return datapoints; - } - - void setMotor_id(Integer motor_id) { - this.motor_id = motor_id; - } - void setFiletype(String filetype ) { - this.filetype = filetype; - } - void setLength(Float length) { - this.length = length; - } - void setDelays(String delays) { - this.delays = delays; - } - void setPropWeightG(Double propWeightG) { - this.propWeightG = propWeightG; - } - void setTotWeightG(Double totWeightG) { - this.totWeightG = totWeightG; - } - void setDatapoints(Vector datapoints) { - this.datapoints = datapoints; - } -} diff --git a/src/net/sf/openrocket/android/thrustcurve/RSEBurnFile.java b/src/net/sf/openrocket/android/thrustcurve/RSEBurnFile.java deleted file mode 100644 index 0c937571..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/RSEBurnFile.java +++ /dev/null @@ -1,131 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.Vector; - -import org.xml.sax.Attributes; - -import android.sax.Element; -import android.sax.RootElement; -import android.sax.StartElementListener; -import android.util.Log; -import android.util.Xml; - -class RSEBurnFile extends MotorBurnFile { - - private final static String TAG = "RSEBurnFile"; - - static void parse( MotorBurnFile that, String filecontents ) { - - parse(that, new ByteArrayInputStream(filecontents.getBytes()) ); - } - - private final static String root_tag = "engine-database"; - private final static String engine_list_tag = "engine-list"; - private final static String engine_tag = "engine"; - - private final static String delays_attr = "delays"; - private final static String len_attr = "len"; - private final static String propwgt_attr = "propWt"; - private final static String totwgt_attr = "initWt"; - - private final static String data_tag = "data"; - private final static String eng_data_tag = "eng-data"; - - private final static String time_attr="t"; - private final static String force_attr="f"; - - static void parse( final MotorBurnFile that, InputStream in ) { - - RootElement rootEl = new RootElement(root_tag); - Element engineEl = rootEl.getChild(engine_list_tag).getChild(engine_tag); - - final Vector datapoints = new Vector(); - - Log.d(TAG,"parsing start"); - - engineEl.setStartElementListener( - new StartElementListener() { - @Override - public void start(Attributes arg0) { - Log.d(TAG,"start engineEl"); - that.setPropWeightG(Double.parseDouble(arg0.getValue(propwgt_attr))); - that.setTotWeightG(Double.parseDouble(arg0.getValue(totwgt_attr))); - that.setLength(Float.parseFloat(arg0.getValue(len_attr))); - that.setDelays(arg0.getValue(delays_attr)); - Log.d(TAG, "me is now " + that.toString()); - } - } - ); - - Element datapointEl = engineEl.getChild(data_tag).getChild(eng_data_tag); - datapointEl.setStartElementListener( - new StartElementListener() { - @Override - public void start(Attributes attributes) { - Double x = Double.parseDouble(attributes.getValue(time_attr)); - Double y = Double.parseDouble(attributes.getValue(force_attr)); - Log.d(TAG, "add data point " + x + "," + y); - datapoints.add(x); - datapoints.add(y); - } - } - ); - - try { - Xml.parse(in, Xml.Encoding.UTF_8, rootEl.getContentHandler()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - that.setDatapoints(datapoints); - } -} -// -// -// -// -// Apogee C4 RASP.ENG file made from NAR published data -// File produced September 4, 2000 -// The total impulse, peak thrust, average thrust and burn time are -// the same as the averaged static test data on the NAR web site in -// the certification file. The curve drawn with these data points is as -// close to the certification curve as can be with such a limited -// number of points (32) allowed with wRASP up to v1.6. -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// -// diff --git a/src/net/sf/openrocket/android/thrustcurve/RaspBurnFile.java b/src/net/sf/openrocket/android/thrustcurve/RaspBurnFile.java deleted file mode 100644 index 2c2e834e..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/RaspBurnFile.java +++ /dev/null @@ -1,85 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.io.IOException; -import java.io.LineNumberReader; -import java.io.StringReader; -import java.util.Vector; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import android.util.Log; - - -class RaspBurnFile{ - - private final static String TAG = "RaspBurnFile"; - - private final static int HEADER = 0; - private final static int DATA = 1; - private final static Pattern headerPattern = Pattern.compile("(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)\\s+(\\S*)"); - private final static Pattern dataPattern = Pattern.compile("(\\S*)\\s+(\\S*)"); - - static void parse( MotorBurnFile that, String filecontents ) { - - int state = HEADER; - - LineNumberReader reader = new LineNumberReader( new StringReader(filecontents)); - - Vector datapoints = new Vector(); - - String line; - Matcher m; - try { - while ( (line = reader.readLine()) != null ) { - line = line.trim(); - Log.d("RASP",line); - if ( line.startsWith(";")) { - continue; - } - switch (state) { - - case HEADER: - Log.d("RASP","header"); - m = headerPattern.matcher(line); - if ( m.matches() ) { - Log.d("RASP","header matches"); - - /*motorName = m.group(1);*/ - /*diameter = Integer.decode(m.group(2));*/ - that.setLength(Float.parseFloat(m.group(3)) ); - String delays = m.group(4); - if ( delays != null ) { - delays = delays.replace("-", ","); - that.setDelays(delays); - } - that.setPropWeightG(Double.parseDouble(m.group(5))*1000.0); - that.setTotWeightG(Double.parseDouble(m.group(6))*1000.0); - /*manufacturer = m.group(7);*/ - - } - state = DATA; - break; - - case DATA: - Log.d("RASP","data"); - m = dataPattern.matcher(line); - if ( m.matches() ) { - Log.d("RASP","data matches"); - Double x = Double.parseDouble(m.group(1)); - Double y = Double.parseDouble(m.group(2)); - Log.d("RASP","data matches ("+x+","+y+")"); - datapoints.add(x); - datapoints.add(y); - } - break; - } - that.setDatapoints(datapoints); - } - } catch (IOException ex ) { - Log.d(TAG,"Unable to parse Rasp file: " + ex); - } - - } - - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/SearchRequest.java b/src/net/sf/openrocket/android/thrustcurve/SearchRequest.java deleted file mode 100644 index 681c049f..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/SearchRequest.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -public class SearchRequest { - - private String manufacturer; - private String designation; - private String brand_name; - - private String common_name; - private String impulse_class; - private Integer diameter; - - /* - public enum Type { - "SU"; - "reload"; - "hybrid" - }; - */ - private String type; - - public void setManufacturer(String manufacturer) { - this.manufacturer = null; - if ( manufacturer != null ) { - manufacturer = manufacturer.trim(); - if ( ! "".equals(manufacturer) ) { - this.manufacturer = manufacturer; - } - } - } - - public void setDesignation(String designation) { - this.designation = designation; - } - - public void setBrand_name(String brand_name) { - this.brand_name = brand_name; - } - - public void setCommon_name(String common_name) { - if ( common_name == null ) { - this.common_name = null; - return; - } - this.common_name = common_name.trim(); - if ( "".equals(this.common_name)) { - this.common_name = null; - } - } - - public void setImpulse_class(String impulse_class) { - this.impulse_class = null; - if ( impulse_class != null ) { - this.impulse_class = impulse_class.trim(); - if ( "".equals(impulse_class) ) { - this.impulse_class = null; - } - } - } - - public void setDiameter(Integer diameter) { - this.diameter = diameter; - } - - public void setDiameter(String diameter) { - this.diameter = null; - if ( diameter == null ) { - return; - } - try { - this.diameter = Integer.decode(diameter); - } catch ( NumberFormatException ex ) { - this.diameter = null; - } - } - - public void setType(String type) { - this.type = type; - } - - @Override - public String toString() { - StringBuilder w = new StringBuilder(); - - w.append("\n"); - w.append("\n"); - - if ( manufacturer != null ) { - w.append(" ").append(manufacturer).append("\n"); - } - if ( designation != null ) { - w.append(" ").append(designation).append("\n"); - } - if ( brand_name != null ) { - w.append(" ").append(brand_name).append("\n"); - } - if ( common_name != null ) { - w.append(" ").append(common_name).append("\n"); - } - if ( impulse_class != null ) { - w.append(" ").append(impulse_class).append("\n"); - } - if ( diameter != null ) { - w.append(" ").append(diameter).append("\n"); - } - if ( type != null ) { - w.append(" ").append(type).append("\n"); - } - w.append("*"); - w.append("50"); - w.append("\n"); - return w.toString(); - } -} diff --git a/src/net/sf/openrocket/android/thrustcurve/SearchResponse.java b/src/net/sf/openrocket/android/thrustcurve/SearchResponse.java deleted file mode 100644 index 48cbfefb..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/SearchResponse.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.util.ArrayList; -import java.util.List; - - -public class SearchResponse { - - private List results = new ArrayList(); - - private int matches; - - private String error; - - public List getResults() { - return results; - } - - public void setResults(List results) { - this.results = results; - } - - public int getMatches() { - return matches; - } - - public void setMatches(int matches) { - this.matches = matches; - } - - public String getError() { - return error; - } - - public void setError(String error) { - this.error = error; - } - - @Override - public String toString() { - return "SearchResult [results=" + results + ", matches=" + matches - + ", error=" + error + "]"; - } - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/SearchResponseParser.java b/src/net/sf/openrocket/android/thrustcurve/SearchResponseParser.java deleted file mode 100644 index be532435..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/SearchResponseParser.java +++ /dev/null @@ -1,281 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.io.InputStream; - -import org.xml.sax.Attributes; - -import android.sax.Element; -import android.sax.EndElementListener; -import android.sax.EndTextElementListener; -import android.sax.RootElement; -import android.sax.StartElementListener; -import android.util.Xml; - -public class SearchResponseParser { - - private static final String thrustcurveURI = "http://www.thrustcurve.org/2008/SearchResponse"; - /* - * XML Tags in SearchResult xsd - */ - private static final String root_tag = "search-response"; - private static final String criteria = "criteria"; - private static final String criterion = "criterion"; - private static final String name = "name"; - private static final String value = "value"; - private static final String matches = "matches"; - private static final String results = "results"; - private static final String result = "result"; - - private static final String motor_id = "motor-id"; - private static final String manufacturer = "manufacturer"; - private static final String manufacturer_abbr = "manufacturer-abbrev"; - private static final String designation = "designation"; - private static final String brand_name = "brand-name"; - private static final String common_name = "common-name"; - private static final String impulse_class = "impulse-class"; - private static final String diameter = "diameter"; - private static final String length = "length"; - private static final String type = "type"; - private static final String cert_org = "cert-org"; - private static final String avg_thrust_n = "avg-thrust-n"; - private static final String max_thrust_n = "max-thrust-n"; - private static final String tot_impulse_ns = "tot-impulse-ns"; - private static final String burn_time_s = "burn-time-s"; - private static final String data_files = "data-files"; - private static final String info_url = "info-url"; - private static final String total_weight_g = "total-weight-g"; - private static final String prop_weight_g = "prop-weight-g"; - private static final String delays = "delays"; - private static final String case_info = "case-info"; - private static final String prop_info = "prop-info"; - private static final String updated_on = "updated-on"; - - public static SearchResponse parse( InputStream in ) { - - final SearchResponse ret = new SearchResponse(); - final TCMotor currentMotor = new TCMotor(); - - RootElement rootEl = new RootElement(thrustcurveURI, root_tag); - Element criteriaEl = rootEl.getChild( thrustcurveURI, criteria); - - criteriaEl.getChild(thrustcurveURI,matches).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - ret.setMatches(Integer.parseInt(arg0)); - } - } - ); - Element resultsEl = rootEl.getChild(thrustcurveURI,results); - Element resultEl = resultsEl.getChild(thrustcurveURI,result); - - resultEl.setStartElementListener( - new StartElementListener() { - @Override - public void start(Attributes arg0) { - currentMotor.init(); - } - } - ); - - resultEl.setEndElementListener( - new EndElementListener() { - @Override - public void end() { - ret.getResults().add((TCMotor)currentMotor.clone()); - } - } - ); - - resultEl.getChild(thrustcurveURI,motor_id).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setMotor_id(Integer.parseInt(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,manufacturer).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - if ( arg0 != null ) { - currentMotor.setManufacturer(arg0); - } - } - } - ); - resultEl.getChild(thrustcurveURI,manufacturer_abbr).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - if ( arg0 != null ) { - currentMotor.setManufacturer_abbr(arg0); - } - } - } - ); - resultEl.getChild(thrustcurveURI,designation).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setDesignation(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,brand_name).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setBrand_name(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,common_name).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setCommon_name(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,impulse_class).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setImpulse_class(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,diameter).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setDiameter(Float.parseFloat(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,length).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setLength(Float.parseFloat(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,type).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setType(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,cert_org).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setCert_org(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,avg_thrust_n).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setAvg_thrust_n(Float.parseFloat(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,max_thrust_n).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setMax_thrust_n(Float.parseFloat(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,tot_impulse_ns).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setTot_impulse_ns(Float.parseFloat(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,burn_time_s).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setBurn_time_s(Float.parseFloat(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,data_files).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setData_files(Integer.parseInt(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,info_url).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setInfo_url(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,total_weight_g).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setTot_mass_g(Double.parseDouble(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,prop_weight_g).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setProp_mass_g(Double.parseDouble(arg0)); - } - } - ); - resultEl.getChild(thrustcurveURI,delays).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setDelays(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,case_info).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setCase_info(arg0); - } - } - ); - resultEl.getChild(thrustcurveURI,prop_info).setEndTextElementListener( - new EndTextElementListener() { - @Override - public void end(String arg0) { - currentMotor.setProp_info(arg0); - } - } - ); - - - try { - Xml.parse(in, Xml.Encoding.UTF_8, rootEl.getContentHandler()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return ret; - } - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/SupportedFileTypes.java b/src/net/sf/openrocket/android/thrustcurve/SupportedFileTypes.java deleted file mode 100644 index c1230164..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/SupportedFileTypes.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -public abstract class SupportedFileTypes { - - public final static String ROCKSIM_FORMAT = "RockSim"; - public final static String RASP_FORMAT = "RASP"; - - public static boolean isSupportedFileType( String arg0 ) { - return (ROCKSIM_FORMAT.equals(arg0) || RASP_FORMAT.equals(arg0)); - } -} diff --git a/src/net/sf/openrocket/android/thrustcurve/TCMotor.java b/src/net/sf/openrocket/android/thrustcurve/TCMotor.java deleted file mode 100644 index 477029ec..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/TCMotor.java +++ /dev/null @@ -1,299 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.util.Date; -import java.util.Vector; - -public class TCMotor implements Cloneable { - - private Integer motor_id; - private String manufacturer; - private String manufacturer_abbr; - private String designation; - private String brand_name; - private String common_name; - private String impulse_class; - private Float diameter; - private Float length; - private String type; - private String cert_org; - private Float avg_thrust_n; - private Float max_thrust_n; - private Float tot_impulse_ns; - private Float burn_time_s; - private Integer data_files; - private String info_url; - private Double tot_mass_g; - private Double prop_mass_g; - private String delays; - private String case_info; - private String prop_info; - private Date updated_on; - private Vector burndata; - - public void init() { - motor_id = null; - manufacturer = null; - manufacturer_abbr = null; - designation = null; - brand_name = null; - common_name = null; - impulse_class = null; - diameter = null; - length = null; - type = null; - cert_org = null; - avg_thrust_n = null; - max_thrust_n = null; - tot_impulse_ns = null; - burn_time_s = null; - data_files = null; - info_url = null; - tot_mass_g = null; - prop_mass_g = null; - delays = null; - case_info = null; - prop_info = null; - updated_on = null; - burndata = null; - } - - @Override - public TCMotor clone() { - TCMotor clone = new TCMotor(); - clone.motor_id = this.motor_id; - clone.manufacturer = this.manufacturer; - clone.manufacturer_abbr = this.manufacturer_abbr; - clone.designation = this.designation; - clone.brand_name = this.brand_name; - clone.common_name = this.common_name; - clone.impulse_class = this.impulse_class; - clone.diameter = this.diameter; - clone.length = this.length; - clone.type = this.type; - clone.cert_org = this.cert_org; - clone.avg_thrust_n = this.avg_thrust_n; - clone.max_thrust_n = this.max_thrust_n; - clone.tot_impulse_ns = this.tot_impulse_ns; - clone.burn_time_s = this.burn_time_s; - clone.data_files = this.data_files; - clone.info_url = this.info_url; - clone.tot_mass_g = this.tot_mass_g; - clone.prop_mass_g = this.prop_mass_g; - clone.delays = this.delays; - clone.case_info = this.case_info; - clone.prop_info = this.prop_info; - clone.updated_on = this.updated_on; - clone.burndata = this.burndata; - return clone; - } - - public Integer getMotor_id() { - return motor_id; - } - - public void setMotor_id(Integer motor_id) { - this.motor_id = motor_id; - } - - public String getManufacturer() { - return manufacturer; - } - - public void setManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - } - - public String getManufacturer_abbr() { - return manufacturer_abbr; - } - - public void setManufacturer_abbr(String manufacturer_abbr) { - this.manufacturer_abbr = manufacturer_abbr; - } - - public String getDesignation() { - return designation; - } - - public void setDesignation(String designation) { - this.designation = designation; - } - - public String getBrand_name() { - return brand_name; - } - - public void setBrand_name(String brand_name) { - this.brand_name = brand_name; - } - - public String getCommon_name() { - return common_name; - } - - public void setCommon_name(String common_name) { - this.common_name = common_name; - } - - public String getImpulse_class() { - return impulse_class; - } - - public void setImpulse_class(String impulse_class) { - this.impulse_class = impulse_class; - } - - public Float getDiameter() { - return diameter; - } - - public void setDiameter(Float diameter) { - this.diameter = diameter; - } - - public Float getLength() { - return length; - } - - public void setLength(Float length) { - this.length = length; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCert_org() { - return cert_org; - } - - public void setCert_org(String cert_org) { - this.cert_org = cert_org; - } - - public Float getAvg_thrust_n() { - return avg_thrust_n; - } - - public void setAvg_thrust_n(Float avg_thrust_n) { - this.avg_thrust_n = avg_thrust_n; - } - - public Float getMax_thrust_n() { - return max_thrust_n; - } - - public void setMax_thrust_n(Float max_thrust_n) { - this.max_thrust_n = max_thrust_n; - } - - public Float getTot_impulse_ns() { - return tot_impulse_ns; - } - - public void setTot_impulse_ns(Float tot_impulse_ns) { - this.tot_impulse_ns = tot_impulse_ns; - } - - public Float getBurn_time_s() { - return burn_time_s; - } - - public void setBurn_time_s(Float burn_time_s) { - this.burn_time_s = burn_time_s; - } - - public Integer getData_files() { - return data_files; - } - - public void setData_files(Integer data_files) { - this.data_files = data_files; - } - - public String getInfo_url() { - return info_url; - } - - public void setInfo_url(String info_url) { - this.info_url = info_url; - } - - public Double getTot_mass_g() { - return tot_mass_g; - } - - public void setTot_mass_g(Double tot_mass_g) { - this.tot_mass_g = tot_mass_g; - } - - public Double getProp_mass_g() { - return prop_mass_g; - } - - public void setProp_mass_g(Double prop_mass_g) { - this.prop_mass_g = prop_mass_g; - } - - public String getDelays() { - return delays; - } - - public void setDelays(String delays) { - this.delays = delays; - } - - public String getCase_info() { - return case_info; - } - - public void setCase_info(String case_info) { - this.case_info = case_info; - } - - public String getProp_info() { - return prop_info; - } - - public void setProp_info(String prop_info) { - this.prop_info = prop_info; - } - - public Date getUpdated_on() { - return updated_on; - } - - public void setUpdated_on(Date updated_on) { - this.updated_on = updated_on; - } - - public Vector getBurndata() { - return burndata; - } - - public void setBurndata(Vector burndata) { - this.burndata = burndata; - } - - @Override - public String toString() { - return "TCMotor [motor_id=" + motor_id + ", manufacturer=" - + manufacturer + ", manufacturer_abbr=" + manufacturer_abbr - + ", designation=" + designation + ", brand_name=" + brand_name - + ", common_name=" + common_name + ", impulse_class=" - + impulse_class + ", diameter=" + diameter + ", length=" - + length + ", type=" + type + ", cert_org=" + cert_org - + ", avg_thrust_n=" + avg_thrust_n + ", max_thrust_n=" - + max_thrust_n + ", tot_impulse_ns=" + tot_impulse_ns - + ", burn_time_s=" + burn_time_s + ", data_files=" + data_files - + ", info_url=" + info_url + ", tot_mass_g=" + tot_mass_g - + ", prop_mass_g=" + prop_mass_g + ", delays=" + delays - + ", case_info=" + case_info + ", prop_info=" + prop_info - + ", updated_on=" + updated_on + "]"; - } - -} diff --git a/src/net/sf/openrocket/android/thrustcurve/TCQueryActivity.java b/src/net/sf/openrocket/android/thrustcurve/TCQueryActivity.java deleted file mode 100644 index 8f5a7835..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/TCQueryActivity.java +++ /dev/null @@ -1,256 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.util.Vector; - -import net.sf.openrocket.R; -import net.sf.openrocket.android.db.DbAdapter; -import net.sf.openrocket.android.motor.Motor; -import android.app.Activity; -import android.app.AlertDialog; -import android.app.ProgressDialog; -import android.content.DialogInterface; -import android.os.Bundle; -import android.os.Handler; -import android.util.Log; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.Spinner; - -public class TCQueryActivity extends Activity { - - private static final String TAG = "ThrustCurveQueryActivity"; - - private DbAdapter mDbHelper; - - private ProgressDialog progress; - private Thread downloadThread; - private Handler handler; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.tcqueryform); - - mDbHelper = new DbAdapter(this); - mDbHelper.open(); - - final Spinner manufacturerField = (Spinner) findViewById(R.id.TCMotorSearchFormManufacturerField); - final Spinner impulseField = (Spinner) findViewById(R.id.TCMotorSearchFormImpulseField); - final Spinner diameterField = (Spinner) findViewById(R.id.TCMotorSearchFormDiameterField); - final EditText commonNameField = (EditText) findViewById(R.id.TCMotorSearchFormCommonNameField); - - Button submitButton = (Button) findViewById(R.id.TCMotorSearchFromSubmitButton); - submitButton.setOnClickListener( - new View.OnClickListener() { - @Override - public void onClick( View v ) { - Log.d(TAG,"submit button clicked"); - - String commonName = commonNameField.getText().toString(); - - SearchRequest r = new SearchRequest(); - if ( manufacturerField.getSelectedItemPosition() != 0) { - String m = (String) manufacturerField.getSelectedItem(); - Log.d(TAG,"manufacturer = " + m); - r.setManufacturer(m); - } - if ( impulseField.getSelectedItemPosition() != 0 ) { - String impulse = (String) impulseField.getSelectedItem(); - Log.d(TAG,"impulse = " + impulse); - r.setImpulse_class(impulse); - } - if ( diameterField.getSelectedItemPosition() != 0 ) { - String diameter = (String)diameterField.getSelectedItem(); - Log.d(TAG,"diameter = " + diameter); - r.setDiameter(diameter); - } - r.setCommon_name(commonName); - - Downloader d = new Downloader(r); - - handler = new Handler(); - progress = ProgressDialog.show(TCQueryActivity.this, null, ""); - - downloadThread = new Thread( d ); - downloadThread.start(); - } - } - ); - } - - @Override - public Object onRetainNonConfigurationInstance() { - return downloadThread; - } - - @Override - protected void onDestroy() { - mDbHelper.close(); - if ( progress != null ) { - if ( progress.isShowing() ) { - progress.dismiss(); - } - progress = null; - } - super.onDestroy(); - } - - private class UpdateMessage implements Runnable { - private String newMessage; - UpdateMessage( String message ) { - this.newMessage = message; - } - @Override - public void run() { - progress.setMessage(newMessage); - } - } - - private class Dismiss implements Runnable { - @Override - public void run() { - progress.dismiss(); - TCQueryActivity.this.finish(); - } - } - - private class Error implements Runnable { - private String newMessage; - Error( String message ) { - this.newMessage = message; - } - @Override - public void run() { - progress.dismiss(); - final AlertDialog dialog = new AlertDialog.Builder(TCQueryActivity.this).create(); - dialog.setMessage(newMessage); - dialog.setButton(DialogInterface.BUTTON_NEUTRAL,"Dismiss", new DialogInterface.OnClickListener() { - - @Override - public void onClick(DialogInterface arg0, int arg1) { - dialog.dismiss(); - } - - }); - dialog.show(); - } - } - private class Downloader implements Runnable { - - SearchRequest request; - - Downloader( SearchRequest request ) { - this.request = request; - } - - @Override - public void run() { - try { - handler.post( new UpdateMessage("Quering Thrustcurve")); - SearchResponse res = new ThrustCurveAPI().doSearch(request); - - int total = res.getResults().size(); - int count = 1; - for( TCMotor mi : res.getResults() ) { - handler.post(new UpdateMessage("Downloading details " + count + " of " + total)); - count++; - if ( mi.getData_files() == null || mi.getData_files().intValue() == 0 ) { - continue; - } - - MotorBurnFile b = new ThrustCurveAPI().downloadData(mi.getMotor_id()); - - if ( b != null ) { - if ( b.getLength() != null ) { - mi.setLength( b.getLength() ); - } - if ( b.getPropWeightG() != null ) { - mi.setProp_mass_g(b.getPropWeightG()); - } - if ( b.getTotWeightG() != null ) { - mi.setTot_mass_g(b.getTotWeightG()); - } - if ( b.getDelays() != null ) { - mi.setDelays(b.getDelays()); - } - mi.setBurndata(b.getDatapoints()); - } - Log.d(TAG, mi.toString()); - - // convert to Motors. One per delay. - Motor m = new Motor(); - // Base name of motor. - String name = mi.getCommon_name() + "-"; - - m.setManufacturer(mi.getManufacturer_abbr()); - // Convert impulse class. ThrustCurve puts mmx, 1/4a and 1/2a as A. - m.setImpulseClass(mi.getImpulse_class()); - if ( "a".equalsIgnoreCase(mi.getImpulse_class())) { - if( mi.getCommon_name().startsWith("1/2A") ) { - m.setImpulseClass("1/2A"); - } else if (mi.getCommon_name().startsWith("1/4A") ) { - m.setImpulseClass("1/4A"); - } else if (mi.getCommon_name().startsWith("Micro") ) { - m.setImpulseClass("1/8A"); - } - } - m.setAvgThrust(mi.getAvg_thrust_n()); - m.setBurndata(mi.getBurndata()); - m.setBurnTime(mi.getBurn_time_s()); - m.setDiameter(mi.getDiameter() == null ? null : mi.getDiameter().longValue()); - m.setLength(mi.getLength()); - m.setMaxThrust(mi.getMax_thrust_n()); - m.setPropMass(mi.getProp_mass_g()); - m.setTotalImpulse(mi.getTot_impulse_ns()); - m.setTotMass(mi.getTot_mass_g()); - // Convert Case Info. - if ( mi.getCase_info() == null - || "single use".equalsIgnoreCase(mi.getCase_info()) - || "single-use".equalsIgnoreCase(mi.getCase_info())) { - m.setCaseInfo(mi.getType()+ " " + mi.getDiameter() + "x" + mi.getLength()); - } else { - m.setCaseInfo(mi.getCase_info()); - } - - Vector delays = new Vector(); - { - String delaysString = mi.getDelays(); - if ( delaysString != null ) { - delaysString = delaysString.trim(); - } - - if ( delaysString == null || "".equals(delaysString)) { - delays.add(""); - } else { - String[] delayString = delaysString.split(","); - for( String d : delayString ) { - delays.add( d.trim() ); - } - } - } - - for( String d: delays ) { - if ( "100".equals(d) ) { - m.setName(name + "P"); - } else { - m.setName(name + d); - } - mDbHelper.getMotorDao().insertOrUpdateMotor(m); - } - } - if ( total < res.getMatches() ) { - handler.post( new Error( total + " motors downloaded, " + res.getMatches() + " matched. Try restricting the query more.") ); - } else { - handler.post( new Dismiss()); - } - } - catch( Exception ex){ - Log.d(TAG,ex.toString()); - handler.post( new Error(ex.toString()) ); - } - - } - } -} - diff --git a/src/net/sf/openrocket/android/thrustcurve/ThrustCurveAPI.java b/src/net/sf/openrocket/android/thrustcurve/ThrustCurveAPI.java deleted file mode 100644 index 9241228b..00000000 --- a/src/net/sf/openrocket/android/thrustcurve/ThrustCurveAPI.java +++ /dev/null @@ -1,80 +0,0 @@ -package net.sf.openrocket.android.thrustcurve; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; - -import android.util.Log; - - -public class ThrustCurveAPI { - - private final static String TAG = "ThrustCurveAPI"; - - private String url_base = "http://www.thrustcurve.org/servlets/"; - - public SearchResponse doSearch( SearchRequest request ) throws MalformedURLException, IOException { - - String requestString = request.toString(); - - Log.d(TAG, "doSearch: " + requestString); - URL url = new URL(url_base + "search"); - - OutputStream stream; - - URLConnection conn = url.openConnection(); - conn.setConnectTimeout(2000); - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setUseCaches(false); - - stream = conn.getOutputStream(); - - stream.write(requestString.getBytes()); - - InputStream is = conn.getInputStream(); - - SearchResponse result = SearchResponseParser.parse(is); - Log.d(TAG,result.toString()); - - return result; - } - - public MotorBurnFile downloadData( Integer motor_id ) throws MalformedURLException, IOException { - - if ( motor_id == null ) { - return null; - } - DownloadRequest dr = new DownloadRequest(); - dr.add(motor_id); - - String requestString = dr.toString(); - - Log.d(TAG, "downloadData: " + requestString); - URL url = new URL(url_base + "download"); - - OutputStream stream; - - URLConnection conn = url.openConnection(); - conn.setDoInput(true); - conn.setDoOutput(true); - conn.setUseCaches(false); - - stream = conn.getOutputStream(); - - stream.write(requestString.getBytes()); - - InputStream is = conn.getInputStream(); - - DownloadResponse downloadResponse = DownloadResponseParser.parse(is); - Log.d(TAG,downloadResponse.toString()); - - MotorBurnFile mbf = downloadResponse.getData(motor_id); - - return mbf; - - } -}